app.js 773 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080
  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. // ======================== IPTABLES FIREWALL ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function nativeNATChain(chain) {
  3372. const value = (chain || '').toLowerCase();
  3373. if (value === 'dstnat') return 'prerouting';
  3374. if (value === 'srcnat') return 'postrouting';
  3375. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3376. }
  3377. function nativeFirewallTarget(action) {
  3378. const name = (action || '').toLowerCase();
  3379. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3380. }
  3381. function renderRuleFlag(disabled, hasComment) {
  3382. let flags = '';
  3383. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3384. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3385. return flags || '<span class="text-slate-600">-</span>';
  3386. }
  3387. function renderActionBadge(action) {
  3388. const act = (action || '').toLowerCase();
  3389. let color = 'bg-slate-800 text-slate-300';
  3390. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3391. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3392. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3393. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3394. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3395. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3396. }
  3397. function switchFWSubTab(tab) {
  3398. state.fwSubTab = tab;
  3399. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3400. tabs.forEach(t => {
  3401. const panel = document.getElementById(`fw-subtab-${t}`);
  3402. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3403. if (panel) {
  3404. if (t === tab) panel.classList.remove('hidden');
  3405. else panel.classList.add('hidden');
  3406. }
  3407. if (btn) {
  3408. if (t === tab) {
  3409. 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';
  3410. } else {
  3411. 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';
  3412. }
  3413. }
  3414. });
  3415. const addBtn = document.getElementById('fw-primary-add-btn');
  3416. if (addBtn) {
  3417. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3418. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3419. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3420. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3421. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3422. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3423. }
  3424. if (tab === 'filter') renderFilterRules();
  3425. else if (tab === 'nat') renderNATRules();
  3426. else if (tab === 'mangle') renderMangleRules();
  3427. else if (tab === 'addrlist') renderAddressLists();
  3428. else if (tab === 'geo') loadGeoIP();
  3429. else if (tab === 'connections') loadConnections();
  3430. setTimeout(initTableSorting, 50);
  3431. }
  3432. function openCurrentFWModal() {
  3433. if (state.fwSubTab === 'filter') openAddFilterModal();
  3434. else if (state.fwSubTab === 'nat') openAddNATModal();
  3435. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3436. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3437. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3438. else if (state.fwSubTab === 'connections') loadConnections();
  3439. }
  3440. async function loadFirewall(populateDropdowns = true) {
  3441. try {
  3442. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3443. fetch(`${API_BASE}/firewall/summary`),
  3444. fetch(`${API_BASE}/firewall/filter`),
  3445. fetch(`${API_BASE}/firewall/nat`),
  3446. fetch(`${API_BASE}/firewall/mangle`),
  3447. fetch(`${API_BASE}/firewall/address-lists`),
  3448. fetch(`${API_BASE}/firewall/geoip/status`),
  3449. fetch(`${API_BASE}/firewall/geoip/countries`)
  3450. ]);
  3451. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3452. const applyError = document.getElementById('fw-apply-error');
  3453. if (applyError) {
  3454. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3455. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3456. }
  3457. if (filterRes.ok) state.filterRules = await filterRes.json();
  3458. if (natRes.ok) state.natRules = await natRes.json();
  3459. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3460. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3461. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3462. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3463. 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); }
  3464. // Badges
  3465. const bFilter = document.getElementById('fw-badge-filter');
  3466. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3467. const bNat = document.getElementById('fw-badge-nat');
  3468. if (bNat) bNat.innerText = (state.natRules || []).length;
  3469. const bMangle = document.getElementById('fw-badge-mangle');
  3470. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3471. const bAddr = document.getElementById('fw-badge-addrlist');
  3472. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3473. const bGeo = document.getElementById('fw-badge-geo');
  3474. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3475. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3476. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3477. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3478. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3479. const tbodyFilter = document.getElementById('filter-table-body');
  3480. if (tbodyFilter) {
  3481. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3482. tbodyFilter.dataset.sig = sigFilter;
  3483. renderFilterRules();
  3484. } else {
  3485. // In-place live stats update (ZERO flicker)
  3486. (state.filterRules || []).forEach(r => {
  3487. const p = document.getElementById(`filter-pkts-${r.id}`);
  3488. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3489. const b = document.getElementById(`filter-bytes-${r.id}`);
  3490. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3491. });
  3492. }
  3493. }
  3494. const tbodyNat = document.getElementById('nat-table-body');
  3495. if (tbodyNat) {
  3496. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3497. tbodyNat.dataset.sig = sigNat;
  3498. renderNATRules();
  3499. } else {
  3500. (state.natRules || []).forEach(r => {
  3501. const p = document.getElementById(`nat-pkts-${r.id}`);
  3502. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3503. const b = document.getElementById(`nat-bytes-${r.id}`);
  3504. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3505. });
  3506. }
  3507. }
  3508. const tbodyMangle = document.getElementById('mangle-table-body');
  3509. if (tbodyMangle) {
  3510. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3511. tbodyMangle.dataset.sig = sigMangle;
  3512. renderMangleRules();
  3513. } else {
  3514. (state.mangleRules || []).forEach(r => {
  3515. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3516. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3517. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3518. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3519. });
  3520. }
  3521. }
  3522. const tbodyAddr = document.getElementById('addrlist-table-body');
  3523. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3524. tbodyAddr.dataset.sig = sigAddr;
  3525. renderAddressLists();
  3526. }
  3527. renderGeoCountries();
  3528. if (state.fwSubTab === 'connections') {
  3529. loadConnections();
  3530. }
  3531. } catch (err) {
  3532. console.error('Failed to load firewall:', err);
  3533. }
  3534. }
  3535. // ----------------- Filter Rules -----------------
  3536. function renderFilterRules() {
  3537. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3538. const tbody = document.getElementById('filter-table-body');
  3539. const empty = document.getElementById('filter-empty');
  3540. if (!tbody) return;
  3541. tbody.innerHTML = '';
  3542. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3543. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3544. if (rules.length === 0) {
  3545. empty?.classList.remove('hidden');
  3546. return;
  3547. }
  3548. empty?.classList.add('hidden');
  3549. rules.forEach((raw, idx) => {
  3550. const r = safeFirewallRow(raw);
  3551. const tr = document.createElement('tr');
  3552. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3553. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3554. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3555. let actionExtra = '';
  3556. if (r.action === 'reject') {
  3557. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3558. } else if (r.action === 'jump') {
  3559. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3560. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3561. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3562. } else if (r.action === 'log' && r.log_prefix) {
  3563. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3564. }
  3565. tr.innerHTML = `
  3566. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3567. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3568. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3569. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3570. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3571. <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>
  3572. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3573. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3574. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3575. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3576. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3577. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3578. </td>
  3579. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3580. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3581. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3582. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3583. <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>
  3584. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3585. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3586. </td>
  3587. `;
  3588. tbody.appendChild(tr);
  3589. });
  3590. }
  3591. function formatTarget(addr, list, geo) {
  3592. const parts = [];
  3593. if (addr) parts.push(`<span>${addr}</span>`);
  3594. if (list) {
  3595. const inv = list.startsWith('!') ? '!' : '';
  3596. const clean = list.replace(/^!/, '');
  3597. 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>`);
  3598. }
  3599. if (geo) {
  3600. const inv = geo.startsWith('!') ? '!' : '';
  3601. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3602. 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>`);
  3603. }
  3604. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3605. return parts.join(' ');
  3606. }
  3607. function populateInterfaceSelect(selectId, currentVal = '') {
  3608. const sel = document.getElementById(selectId);
  3609. if (!sel) return;
  3610. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3611. (state.interfaces || []).forEach(i => {
  3612. const opt = document.createElement('option');
  3613. opt.value = i.name;
  3614. opt.innerText = `${i.name} (${i.role || i.type})`;
  3615. if (i.name === currentVal) opt.selected = true;
  3616. sel.appendChild(opt);
  3617. });
  3618. }
  3619. function populateAddressListSelect(selectId, currentVal = '') {
  3620. const sel = document.getElementById(selectId);
  3621. if (!sel) return;
  3622. sel.innerHTML = '<option value="">(None)</option>';
  3623. const cleanVal = (currentVal || '').replace(/^!/, '');
  3624. 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_'));
  3625. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3626. customNames.forEach(name => {
  3627. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3628. const opt = document.createElement('option');
  3629. opt.value = name;
  3630. opt.innerText = `${name} (${count} entries)`;
  3631. if (name === cleanVal) opt.selected = true;
  3632. sel.appendChild(opt);
  3633. });
  3634. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3635. const opt = document.createElement('option');
  3636. opt.value = cleanVal;
  3637. opt.innerText = cleanVal;
  3638. opt.selected = true;
  3639. sel.appendChild(opt);
  3640. }
  3641. populateCommonAddrListDatalist();
  3642. }
  3643. function populateCommonAddrListDatalist() {
  3644. const dl = document.getElementById('fw-addrlist-datalist');
  3645. if (!dl) return;
  3646. dl.innerHTML = '';
  3647. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3648. names.forEach(name => {
  3649. const opt = document.createElement('option');
  3650. opt.value = name;
  3651. dl.appendChild(opt);
  3652. });
  3653. }
  3654. function populateGeoIPSelect(selectId, currentVal = '') {
  3655. const sel = document.getElementById(selectId);
  3656. if (!sel) return;
  3657. sel.innerHTML = '<option value="">(None)</option>';
  3658. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3659. // Presets optgroup
  3660. const grpPresets = document.createElement('optgroup');
  3661. grpPresets.label = '⚡ Regional Presets';
  3662. const presets = [
  3663. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3664. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3665. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3666. ];
  3667. presets.forEach(p => {
  3668. const opt = document.createElement('option');
  3669. opt.value = p.code;
  3670. opt.innerText = p.label;
  3671. if (p.code === cleanVal) opt.selected = true;
  3672. grpPresets.appendChild(opt);
  3673. });
  3674. sel.appendChild(grpPresets);
  3675. // All Countries optgroup
  3676. const grpCountries = document.createElement('optgroup');
  3677. grpCountries.label = '🌍 All Countries';
  3678. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3679. countries.forEach(c => {
  3680. const opt = document.createElement('option');
  3681. opt.value = c.code;
  3682. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3683. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3684. if (c.code === cleanVal) opt.selected = true;
  3685. grpCountries.appendChild(opt);
  3686. });
  3687. sel.appendChild(grpCountries);
  3688. }
  3689. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3690. function switchFwRuleTab(tab) {
  3691. state.activeFwRuleTab = tab;
  3692. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3693. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3694. btn.classList.add('text-slate-400', 'border-transparent');
  3695. });
  3696. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3697. if (activeBtn) {
  3698. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3699. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3700. }
  3701. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3702. const activePane = document.getElementById(`fw-pane-${tab}`);
  3703. if (activePane) activePane.classList.remove('hidden');
  3704. if (tab === 'statistics') {
  3705. startFwStatPolling();
  3706. } else {
  3707. stopFwStatPolling();
  3708. }
  3709. }
  3710. function toggleFwField(fieldKey, expand) {
  3711. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3712. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3713. if (!plusBtn || !fieldBox) return;
  3714. if (expand) {
  3715. plusBtn.classList.add('hidden');
  3716. fieldBox.classList.remove('hidden');
  3717. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3718. if (valInput) valInput.focus();
  3719. } else {
  3720. fieldBox.classList.add('hidden');
  3721. plusBtn.classList.remove('hidden');
  3722. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3723. if (valInput) {
  3724. if (valInput.tagName === 'SELECT') {
  3725. valInput.selectedIndex = 0;
  3726. } else {
  3727. valInput.value = '';
  3728. }
  3729. }
  3730. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3731. if (invInput) invInput.checked = false;
  3732. if (fieldKey === 'cs') {
  3733. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3734. const el = document.getElementById(id);
  3735. if (el) el.checked = false;
  3736. });
  3737. }
  3738. if (fieldKey === 'natstate') {
  3739. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3740. const el = document.getElementById(id);
  3741. if (el) el.checked = false;
  3742. });
  3743. }
  3744. if (fieldKey === 'days') {
  3745. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3746. const el = document.getElementById(`fw-day-${d}`);
  3747. if (el) el.checked = true;
  3748. });
  3749. }
  3750. }
  3751. }
  3752. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3753. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3754. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3755. toggleFwField(fieldKey, true);
  3756. let strVal = String(value);
  3757. if (hasInvert) {
  3758. const inv = strVal.startsWith('!');
  3759. if (inv) strVal = strVal.slice(1);
  3760. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3761. if (invEl) invEl.checked = inv;
  3762. else if (inv) strVal = '!'+strVal;
  3763. }
  3764. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3765. 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; }
  3766. } else {
  3767. toggleFwField(fieldKey, false);
  3768. }
  3769. }
  3770. function getFwFieldVal(fieldKey, hasInvert = false) {
  3771. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3772. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3773. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3774. let v = valEl ? valEl.value.trim() : '';
  3775. if (!v) return '';
  3776. if (hasInvert) {
  3777. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3778. if (invEl && invEl.checked) {
  3779. v = '!' + v.replace(/^!/, '');
  3780. }
  3781. }
  3782. return v;
  3783. }
  3784. function toggleMaximizeFilterModal() {
  3785. const win = document.getElementById('filter-modal-window');
  3786. if (!win) return;
  3787. if (win.classList.contains('max-w-[720px]')) {
  3788. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3789. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3790. } else {
  3791. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3792. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3793. }
  3794. }
  3795. const FW_NATIVE_CHAINS = {
  3796. filter: [
  3797. { id: 'forward', label: 'FORWARD (routed through router)' },
  3798. { id: 'input', label: 'INPUT (destined to this router)' },
  3799. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3800. ],
  3801. nat: [
  3802. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3803. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3804. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3805. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3806. ],
  3807. mangle: [
  3808. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3809. { id: 'input', label: 'INPUT (destined to this machine)' },
  3810. { id: 'forward', label: 'FORWARD (routed through router)' },
  3811. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3812. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3813. ]
  3814. };
  3815. function populateChainDropdown(table, currentChain) {
  3816. const sel = document.getElementById(`${table}-modal-chain-select`);
  3817. if (!sel) return;
  3818. const cur = (currentChain || '').trim();
  3819. const lower = cur.toLowerCase();
  3820. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3821. const rules = state[rulesKey] || [];
  3822. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3823. const customChains = new Set();
  3824. rules.forEach(r => {
  3825. if (r.chain) {
  3826. const c = r.chain.trim();
  3827. const l = c.toLowerCase();
  3828. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3829. customChains.add(c);
  3830. }
  3831. }
  3832. });
  3833. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3834. if (isCurrentCustom) {
  3835. customChains.add(cur);
  3836. }
  3837. let html = '';
  3838. FW_NATIVE_CHAINS[table].forEach(c => {
  3839. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3840. });
  3841. if (customChains.size > 0) {
  3842. html += `<optgroup label="Custom Chains">`;
  3843. customChains.forEach(c => {
  3844. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3845. });
  3846. html += `</optgroup>`;
  3847. }
  3848. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3849. sel.innerHTML = html;
  3850. if (isCurrentCustom) {
  3851. sel.value = cur;
  3852. } else if (nativeIds.includes(lower)) {
  3853. sel.value = lower;
  3854. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3855. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3856. } else {
  3857. sel.value = nativeIds[0];
  3858. }
  3859. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3860. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3861. if (isCurrentCustom || sel.value === '__custom__') {
  3862. if (customWrap) customWrap.classList.remove('hidden');
  3863. if (customInput) customInput.value = cur;
  3864. } else {
  3865. if (customWrap) customWrap.classList.add('hidden');
  3866. if (customInput) customInput.value = '';
  3867. }
  3868. const chainInput = document.getElementById(`${table}-modal-chain`);
  3869. if (chainInput) chainInput.value = cur || sel.value;
  3870. }
  3871. function syncFilterChainFromSelect() {
  3872. const sel = document.getElementById('filter-modal-chain-select');
  3873. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3874. const customInput = document.getElementById('filter-modal-custom-input');
  3875. const chainInput = document.getElementById('filter-modal-chain');
  3876. if (!sel || !chainInput) return;
  3877. if (sel.value === '__custom__') {
  3878. if (customWrap) customWrap.classList.remove('hidden');
  3879. if (customInput) {
  3880. customInput.value = '';
  3881. customInput.focus();
  3882. }
  3883. chainInput.value = '';
  3884. } else {
  3885. if (customWrap) customWrap.classList.add('hidden');
  3886. chainInput.value = sel.value;
  3887. }
  3888. handleFilterChainChange();
  3889. }
  3890. function syncFilterCustomChainInput() {
  3891. const customInput = document.getElementById('filter-modal-custom-input');
  3892. const chainInput = document.getElementById('filter-modal-chain');
  3893. if (customInput && chainInput) {
  3894. chainInput.value = customInput.value.trim();
  3895. }
  3896. handleFilterChainChange();
  3897. }
  3898. function handleFilterChainChange() {
  3899. const chainInput = document.getElementById('filter-modal-chain');
  3900. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3901. const sel = document.getElementById('filter-modal-chain-select');
  3902. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3903. if (['forward', 'input', 'output'].includes(chain)) {
  3904. sel.value = chain;
  3905. }
  3906. }
  3907. const hintEl = document.getElementById('filter-chain-hint');
  3908. if (hintEl) {
  3909. if (chain === 'forward') {
  3910. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3911. } else if (chain === 'input') {
  3912. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3913. } else if (chain === 'output') {
  3914. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3915. } else {
  3916. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3917. }
  3918. }
  3919. const rowIn = document.getElementById('fw-row-iniface');
  3920. const rowInList = document.getElementById('fw-row-inifacelist');
  3921. const rowOut = document.getElementById('fw-row-outiface');
  3922. const rowOutList = document.getElementById('fw-row-outifacelist');
  3923. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3924. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3925. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3926. if (chain === 'input') {
  3927. if (rowIn) rowIn.classList.remove('hidden');
  3928. if (rowInList) rowInList.classList.remove('hidden');
  3929. if (rowOut) rowOut.classList.add('hidden');
  3930. if (rowOutList) rowOutList.classList.add('hidden');
  3931. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3932. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  3933. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3934. } else if (chain === 'output') {
  3935. if (rowIn) rowIn.classList.add('hidden');
  3936. if (rowInList) rowInList.classList.add('hidden');
  3937. if (rowOut) rowOut.classList.remove('hidden');
  3938. if (rowOutList) rowOutList.classList.remove('hidden');
  3939. if (rowInBridge) rowInBridge.classList.add('hidden');
  3940. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  3941. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  3942. } else {
  3943. if (rowIn) rowIn.classList.remove('hidden');
  3944. if (rowInList) rowInList.classList.remove('hidden');
  3945. if (rowOut) rowOut.classList.remove('hidden');
  3946. if (rowOutList) rowOutList.classList.remove('hidden');
  3947. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3948. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  3949. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3950. }
  3951. checkFilterActionChainCompatibility();
  3952. }
  3953. function checkFilterActionChainCompatibility() {
  3954. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  3955. const warnBox = document.getElementById('filter-action-incompatible-warn');
  3956. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  3957. if (!warnBox || !warnMsg) return;
  3958. if (chain === 'prerouting' || chain === 'postrouting') {
  3959. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  3960. warnBox.classList.remove('hidden');
  3961. } else {
  3962. warnBox.classList.add('hidden');
  3963. }
  3964. }
  3965. function openAddFilterModal() {
  3966. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3967. switchFwRuleTab('general');
  3968. setFirewallDays('fw', '');
  3969. const badge = document.getElementById('fw-modal-badge');
  3970. if (badge) badge.innerText = 'New...';
  3971. document.getElementById('filter-modal-id').value = '';
  3972. document.getElementById('filter-modal-family').value = '4';
  3973. document.getElementById('filter-modal-enabled').checked = true;
  3974. document.getElementById('filter-modal-comment').value = '';
  3975. document.getElementById('filter-modal-chain').value = 'forward';
  3976. populateChainDropdown('filter', 'forward');
  3977. handleFilterChainChange();
  3978. document.getElementById('filter-modal-action').value = 'accept';
  3979. document.getElementById('filter-modal-log').checked = false;
  3980. populateInterfaceSelect('fw-val-iniface');
  3981. populateInterfaceSelect('fw-val-outiface');
  3982. populateAddressListSelect('fw-val-srclist');
  3983. populateAddressListSelect('fw-val-dstlist');
  3984. populateGeoIPSelect('fw-val-srcgeo');
  3985. populateGeoIPSelect('fw-val-dstgeo');
  3986. const allFieldKeys = [
  3987. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3988. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3989. 'routingmark', 'conntype', 'cs', 'natstate',
  3990. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3991. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3992. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3993. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3994. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3995. ];
  3996. allFieldKeys.forEach(k => toggleFwField(k, false));
  3997. resetRuleCounterDisplay();
  3998. toggleFilterActionFields();
  3999. refreshFirewallRejectTypes();
  4000. document.getElementById('filter-modal').classList.remove('hidden');
  4001. }
  4002. function openEditFilterModal(id) {
  4003. id = decodeURIComponent(id);
  4004. const r = (state.filterRules || []).find(rule => rule.id === id);
  4005. if (!r) return;
  4006. switchFwRuleTab('general');
  4007. const badge = document.getElementById('fw-modal-badge');
  4008. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4009. document.getElementById('filter-modal-id').value = r.id;
  4010. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4011. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4012. document.getElementById('filter-modal-comment').value = r.comment || '';
  4013. const filterChain = r.chain || 'forward';
  4014. document.getElementById('filter-modal-chain').value = filterChain;
  4015. populateChainDropdown('filter', filterChain);
  4016. handleFilterChainChange();
  4017. setFirewallActionSelection('filter', r.action || 'accept');
  4018. document.getElementById('filter-modal-log').checked = !!r.log;
  4019. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4020. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4021. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4022. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4023. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4024. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4025. setFwFieldVal('src', r.src_address, true);
  4026. setFwFieldVal('dst', r.dst_address, true);
  4027. setFwFieldVal('srclist', r.src_address_list, true);
  4028. setFwFieldVal('dstlist', r.dst_address_list, true);
  4029. setFwFieldVal('srcgeo', r.src_geoip, true);
  4030. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4031. if (r.protocol && r.protocol !== 'all') {
  4032. setFwFieldVal('proto', r.protocol, true);
  4033. } else {
  4034. toggleFwField('proto', false);
  4035. }
  4036. setFwFieldVal('sport', r.src_port, true);
  4037. setFwFieldVal('dport', r.dst_port, true);
  4038. setFwFieldVal('anyport', r.any_port, true);
  4039. setFwFieldVal('iniface', r.in_interface, true);
  4040. setFwFieldVal('outiface', r.out_interface, true);
  4041. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4042. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4043. setFwFieldVal('pktmark', r.packet_mark, true);
  4044. setFwFieldVal('connmark', r.connection_mark, true);
  4045. setFwFieldVal('routingmark', r.routing_mark, true);
  4046. setFwFieldVal('conntype', r.connection_type, false);
  4047. const states = r.connection_state || [];
  4048. if (states.length > 0) {
  4049. toggleFwField('cs', true);
  4050. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4051. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4052. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4053. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4054. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4055. } else {
  4056. toggleFwField('cs', false);
  4057. }
  4058. const natStates = r.connection_nat_state || [];
  4059. if (natStates.length > 0) {
  4060. toggleFwField('natstate', true);
  4061. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4062. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4063. } else {
  4064. toggleFwField('natstate', false);
  4065. }
  4066. // Advanced tab fields
  4067. setFwFieldVal('layer7', r.layer7_protocol, false);
  4068. setFwFieldVal('content', r.content, false);
  4069. setFwFieldVal('connbytes', r.connection_bytes, false);
  4070. setFwFieldVal('connrate', r.connection_rate, false);
  4071. setFwFieldVal('pcc', r.pcc, false);
  4072. setFwFieldVal('srcmac', r.src_mac_address, true);
  4073. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4074. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4075. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4076. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4077. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4078. setFwFieldVal('tlshost', r.tls_host, false);
  4079. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4080. setFwFieldVal('priority', r.priority, false);
  4081. setFwFieldVal('dscp', r.dscp, false);
  4082. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4083. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4084. setFwFieldVal('pktsize', r.packet_size, false);
  4085. setFwFieldVal('random', r.random, false);
  4086. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4087. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4088. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4089. setFwFieldVal('ttl', r.ttl, false);
  4090. // Extra tab fields
  4091. setFwFieldVal('time', r.time, false);
  4092. if (r.days) {
  4093. toggleFwField('days', true);
  4094. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4095. const chk = document.getElementById(`fw-day-${d}`);
  4096. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4097. });
  4098. } else {
  4099. toggleFwField('days', false);
  4100. }
  4101. setFwFieldVal('limit', r.limit, false);
  4102. setFwFieldVal('dstlimit', r.dst_limit, false);
  4103. setFwFieldVal('psd', r.psd, false);
  4104. // Action fields
  4105. if (r.reject_with) {
  4106. const rwEl = document.getElementById('filter-modal-rejectwith');
  4107. if (rwEl) rwEl.value = r.reject_with;
  4108. }
  4109. if (r.jump_target) {
  4110. const jtEl = document.getElementById('filter-modal-jumptarget');
  4111. if (jtEl) jtEl.value = r.jump_target;
  4112. }
  4113. if (r.address_list) {
  4114. const alEl = document.getElementById('filter-modal-action-addrlist');
  4115. if (alEl) alEl.value = r.address_list;
  4116. }
  4117. if (r.address_list_timeout) {
  4118. const toEl = document.getElementById('filter-modal-action-timeout');
  4119. if (toEl) toEl.value = r.address_list_timeout;
  4120. }
  4121. setFwFieldVal('logprefix', r.log_prefix, false);
  4122. // Statistics
  4123. const bEl = document.getElementById('fw-stat-bytes');
  4124. const pEl = document.getElementById('fw-stat-packets');
  4125. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4126. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4127. state.fwLastBytes = r.bytes || 0;
  4128. state.fwLastPackets = r.packets || 0;
  4129. state.fwLastTimestamp = Date.now();
  4130. state.fwStatRateHistory = new Array(30).fill(0);
  4131. state.fwStatPktHistory = new Array(30).fill(0);
  4132. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4133. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4134. toggleFilterActionFields();
  4135. refreshFirewallRejectTypes();
  4136. document.getElementById('filter-modal').classList.remove('hidden');
  4137. }
  4138. function closeFilterModal() {
  4139. stopFwStatPolling();
  4140. document.getElementById('filter-modal').classList.add('hidden');
  4141. }
  4142. function toggleFilterActionFields() {
  4143. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4144. const rejectBox = document.getElementById('filter-action-reject-box');
  4145. const jumpBox = document.getElementById('filter-action-jump-box');
  4146. const addrBox = document.getElementById('filter-action-addrlist-box');
  4147. if (rejectBox) {
  4148. if (act === 'reject') rejectBox.classList.remove('hidden');
  4149. else rejectBox.classList.add('hidden');
  4150. }
  4151. if (jumpBox) {
  4152. if (act === 'jump') jumpBox.classList.remove('hidden');
  4153. else jumpBox.classList.add('hidden');
  4154. }
  4155. if (addrBox) {
  4156. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4157. addrBox.classList.remove('hidden');
  4158. } else {
  4159. addrBox.classList.add('hidden');
  4160. }
  4161. }
  4162. if (act === 'log') {
  4163. const logEl = document.getElementById('filter-modal-log');
  4164. if (logEl) logEl.checked = true;
  4165. toggleFwField('logprefix', true);
  4166. }
  4167. }
  4168. function toggleFwLogPrefix() {
  4169. const isLog = document.getElementById('filter-modal-log')?.checked;
  4170. toggleFwField('logprefix', !!isLog);
  4171. }
  4172. function copyFilterRule() {
  4173. document.getElementById('filter-modal-id').value = '';
  4174. const badge = document.getElementById('fw-modal-badge');
  4175. if (badge) badge.innerText = 'New...';
  4176. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4177. }
  4178. function resetRuleCounterDisplay() {
  4179. state.fwStatRateHistory = new Array(30).fill(0);
  4180. state.fwStatPktHistory = new Array(30).fill(0);
  4181. state.fwLastBytes = 0;
  4182. state.fwLastPackets = 0;
  4183. state.fwLastTimestamp = Date.now();
  4184. const bEl = document.getElementById('fw-stat-bytes');
  4185. const pEl = document.getElementById('fw-stat-packets');
  4186. const rEl = document.getElementById('fw-stat-rate');
  4187. const prEl = document.getElementById('fw-stat-pktrate');
  4188. if (bEl) bEl.value = '0 B';
  4189. if (pEl) pEl.value = '0';
  4190. if (rEl) rEl.value = '0 bps';
  4191. if (prEl) prEl.value = '0 p/s';
  4192. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4193. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4194. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4195. }
  4196. async function resetAllFwCounters() {
  4197. try {
  4198. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4199. if (res.ok) {
  4200. resetRuleCounterDisplay();
  4201. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4202. loadFirewall(false);
  4203. }
  4204. } catch (err) {
  4205. showToast('Error', err.message, 'error');
  4206. }
  4207. }
  4208. async function applyFilterRule(closeAfter = false) {
  4209. const id = document.getElementById('filter-modal-id').value;
  4210. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4211. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4212. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4213. const chainLower = chain.toLowerCase();
  4214. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4215. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4216. switchFwRuleTab('general');
  4217. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4218. return;
  4219. }
  4220. const action = document.getElementById('filter-modal-action').value;
  4221. const comment = document.getElementById('filter-modal-comment').value.trim();
  4222. const enabled = document.getElementById('filter-modal-enabled').checked;
  4223. const src = getFwFieldVal('src', true);
  4224. const dst = getFwFieldVal('dst', true);
  4225. const srclist = getFwFieldVal('srclist', true);
  4226. const dstlist = getFwFieldVal('dstlist', true);
  4227. const srcgeo = getFwFieldVal('srcgeo', true);
  4228. const dstgeo = getFwFieldVal('dstgeo', true);
  4229. const proto = getFwFieldVal('proto', true);
  4230. const sport = getFwFieldVal('sport', true);
  4231. const dport = getFwFieldVal('dport', true);
  4232. const anyport = getFwFieldVal('anyport', true);
  4233. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4234. switchFwRuleTab('general'); toggleFwField('proto', true);
  4235. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4236. }
  4237. let iniface = getFwFieldVal('iniface', true);
  4238. let outiface = getFwFieldVal('outiface', true);
  4239. let inifacelist = getFwFieldVal('inifacelist', true);
  4240. let outifacelist = getFwFieldVal('outifacelist', true);
  4241. if (chainLower === 'input') {
  4242. outiface = '';
  4243. outifacelist = '';
  4244. } else if (chainLower === 'output') {
  4245. iniface = '';
  4246. inifacelist = '';
  4247. }
  4248. const pktmark = getFwFieldVal('pktmark', true);
  4249. const connmark = getFwFieldVal('connmark', true);
  4250. const routingmark = getFwFieldVal('routingmark', true);
  4251. const conntype = getFwFieldVal('conntype', false);
  4252. const states = [];
  4253. const csBox = document.getElementById('fw-field-cs');
  4254. if (csBox && !csBox.classList.contains('hidden')) {
  4255. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4256. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4257. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4258. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4259. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4260. }
  4261. const natStates = [];
  4262. const natBox = document.getElementById('fw-field-natstate');
  4263. if (natBox && !natBox.classList.contains('hidden')) {
  4264. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4265. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4266. }
  4267. const payload = {
  4268. ip_version: Number(document.getElementById('filter-modal-family').value),
  4269. id,
  4270. chain,
  4271. action,
  4272. protocol: proto || 'all',
  4273. src_address: src,
  4274. dst_address: dst,
  4275. src_port: sport,
  4276. dst_port: dport,
  4277. any_port: anyport,
  4278. in_interface: iniface,
  4279. out_interface: outiface,
  4280. in_interface_list: inifacelist,
  4281. out_interface_list: outifacelist,
  4282. packet_mark: pktmark,
  4283. connection_mark: connmark,
  4284. routing_mark: routingmark,
  4285. connection_type: conntype,
  4286. connection_state: states,
  4287. connection_nat_state: natStates,
  4288. src_address_list: srclist,
  4289. dst_address_list: dstlist,
  4290. src_geoip: srcgeo,
  4291. dst_geoip: dstgeo,
  4292. comment,
  4293. disabled: !enabled,
  4294. // Advanced tab
  4295. content: getFwFieldVal('content', false),
  4296. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4297. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4298. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4299. ipsec_policy: getFwFieldVal('ipsec', false),
  4300. dscp: getFwFieldVal('dscp', false),
  4301. tcp_mss: getFwFieldVal('tcpmss', false),
  4302. tos: document.getElementById('fw-val-tos')?.value || '',
  4303. packet_size: getFwFieldVal('pktsize', false),
  4304. random: getFwFieldVal('random', false),
  4305. tcp_flags: getFwFieldVal('tcpflags', false),
  4306. icmp_options: getFwFieldVal('icmpoptions', false),
  4307. ttl: getFwFieldVal('ttl', false),
  4308. days: selectedDays,
  4309. // Extra tab
  4310. time: getFwFieldVal('time', false),
  4311. limit: getFwFieldVal('limit', false),
  4312. // Action tab
  4313. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4314. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4315. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4316. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4317. log: document.getElementById('filter-modal-log')?.checked || false,
  4318. log_prefix: getFwFieldVal('logprefix', false)
  4319. };
  4320. try {
  4321. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4322. method: 'POST',
  4323. headers: { 'Content-Type': 'application/json' },
  4324. body: JSON.stringify(payload)
  4325. });
  4326. if (res.ok) {
  4327. const data = await res.json();
  4328. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4329. loadFirewall(false);
  4330. if (closeAfter) {
  4331. closeFilterModal();
  4332. } else {
  4333. if (data.id) {
  4334. document.getElementById('filter-modal-id').value = data.id;
  4335. const badge = document.getElementById('fw-modal-badge');
  4336. if (badge) badge.innerText = `#${data.id}`;
  4337. }
  4338. }
  4339. } else {
  4340. const err = await res.json();
  4341. showToast('Error', err.message || 'Failed to save rule', 'error');
  4342. }
  4343. } catch (err) {
  4344. showToast('Error', err.message, 'error');
  4345. }
  4346. }
  4347. function submitSaveFilterRule(e) {
  4348. if (e && e.preventDefault) e.preventDefault();
  4349. return applyFilterRule(true);
  4350. }
  4351. function startFwStatPolling() {
  4352. stopFwStatPolling();
  4353. pollRuleStats();
  4354. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4355. }
  4356. function stopFwStatPolling() {
  4357. if (state.fwStatInterval) {
  4358. clearInterval(state.fwStatInterval);
  4359. state.fwStatInterval = null;
  4360. }
  4361. }
  4362. async function pollRuleStats() {
  4363. const id = document.getElementById('filter-modal-id')?.value;
  4364. if (!id) {
  4365. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4366. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4367. return;
  4368. }
  4369. try {
  4370. const res = await fetch(`${API_BASE}/firewall/filter`);
  4371. if (!res.ok) return;
  4372. const rules = await res.json();
  4373. const r = rules.find(x => x.id === id);
  4374. if (!r) return;
  4375. const now = Date.now();
  4376. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4377. state.fwLastTimestamp = now;
  4378. const curBytes = r.bytes || 0;
  4379. const curPackets = r.packets || 0;
  4380. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4381. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4382. state.fwLastBytes = curBytes;
  4383. state.fwLastPackets = curPackets;
  4384. const rateBps = Math.round((deltaBytes * 8) / dt);
  4385. const ratePkt = Math.round(deltaPkts / dt);
  4386. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4387. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4388. state.fwStatRateHistory.push(rateBps);
  4389. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4390. state.fwStatPktHistory.push(ratePkt);
  4391. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4392. const bEl = document.getElementById('fw-stat-bytes');
  4393. const pEl = document.getElementById('fw-stat-packets');
  4394. const rEl = document.getElementById('fw-stat-rate');
  4395. const prEl = document.getElementById('fw-stat-pktrate');
  4396. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4397. if (pEl) pEl.value = curPackets.toLocaleString();
  4398. if (rEl) rEl.value = formatBps(rateBps);
  4399. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4400. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4401. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4402. } catch (e) {
  4403. console.error('Error polling rule stats', e);
  4404. }
  4405. }
  4406. function formatBps(bps) {
  4407. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4408. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4409. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4410. return bps + ' bps';
  4411. }
  4412. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4413. const svg = document.getElementById(svgId);
  4414. if (!svg) return;
  4415. const w = 500;
  4416. const h = 100;
  4417. const paddingRight = 45;
  4418. const graphWidth = w - paddingRight;
  4419. const maxVal = Math.max(5, ...dataArray);
  4420. const currentVal = dataArray[dataArray.length - 1] || 0;
  4421. const leg = document.getElementById(legendId);
  4422. if (leg) {
  4423. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4424. }
  4425. let gridLines = '';
  4426. for (let i = 0; i <= 5; i++) {
  4427. const y = 8 + (i * (h - 18) / 5);
  4428. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4429. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4430. gridLines += `
  4431. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4432. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4433. `;
  4434. }
  4435. const step = graphWidth / (dataArray.length - 1);
  4436. const points = dataArray.map((val, idx) => {
  4437. const x = idx * step;
  4438. const y = (h - 10) - (val / maxVal) * (h - 20);
  4439. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4440. });
  4441. const polylineStr = points.join(' ');
  4442. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4443. svg.innerHTML = `
  4444. ${gridLines}
  4445. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4446. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4447. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4448. `;
  4449. }
  4450. async function moveFilterRule(id, dir) {
  4451. id = decodeURIComponent(id);
  4452. try {
  4453. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4454. method: 'POST',
  4455. headers: { 'Content-Type': 'application/json' },
  4456. body: JSON.stringify({ direction: dir })
  4457. });
  4458. if (!res.ok) throw new Error(await responseError(res));
  4459. await loadFirewall(false);
  4460. } catch (err) {
  4461. showToast('Error', err.message, 'error');
  4462. }
  4463. }
  4464. async function toggleFilterRuleState(id, disabled) {
  4465. id = decodeURIComponent(id);
  4466. try {
  4467. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4468. method: 'POST',
  4469. headers: { 'Content-Type': 'application/json' },
  4470. body: JSON.stringify({ disabled })
  4471. });
  4472. if (!res.ok) throw new Error(await responseError(res));
  4473. await loadFirewall(false);
  4474. } catch (err) {
  4475. showToast('Error', err.message, 'error');
  4476. }
  4477. }
  4478. async function deleteFilterRule(id) {
  4479. id = decodeURIComponent(id);
  4480. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4481. try {
  4482. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4483. if (!res.ok) throw new Error(await responseError(res));
  4484. {
  4485. showToast('Deleted', 'Filter rule removed', 'success');
  4486. loadFirewall(false);
  4487. }
  4488. } catch (err) {
  4489. showToast('Error', err.message, 'error');
  4490. }
  4491. }
  4492. // ----------------- NAT Rules -----------------
  4493. function renderNATRules() {
  4494. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4495. const tbody = document.getElementById('nat-table-body');
  4496. const empty = document.getElementById('nat-empty');
  4497. if (!tbody) return;
  4498. tbody.innerHTML = '';
  4499. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4500. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4501. if (rules.length === 0) {
  4502. empty?.classList.remove('hidden');
  4503. return;
  4504. }
  4505. empty?.classList.add('hidden');
  4506. rules.forEach((raw, idx) => {
  4507. const r = safeFirewallRow(raw);
  4508. const tr = document.createElement('tr');
  4509. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4510. let toTarget = '-';
  4511. if (r.action === 'jump') {
  4512. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4513. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4514. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4515. } else if (r.action === 'redirect') {
  4516. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4517. } else if (r.action === 'masquerade') {
  4518. 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>`;
  4519. } else if (r.action === 'log') {
  4520. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4521. } else {
  4522. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4523. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4524. }
  4525. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4526. tr.innerHTML = `
  4527. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4528. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4529. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4530. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4531. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4532. <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>
  4533. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4534. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4535. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4536. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4537. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4538. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4539. </td>
  4540. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4541. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4542. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4543. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4544. <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>
  4545. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4546. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4547. </td>
  4548. `;
  4549. tbody.appendChild(tr);
  4550. });
  4551. }
  4552. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4553. function switchNATRuleTab(tab) {
  4554. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4555. state.activeNATRuleTab = tab;
  4556. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4557. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4558. btn.classList.add('text-slate-400', 'border-transparent');
  4559. });
  4560. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4561. if (activeBtn) {
  4562. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4563. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4564. }
  4565. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4566. const activePane = document.getElementById(`nat-pane-${tab}`);
  4567. if (activePane) activePane.classList.remove('hidden');
  4568. if (tab === 'statistics') {
  4569. startNATStatPolling();
  4570. } else {
  4571. stopNATStatPolling();
  4572. }
  4573. }
  4574. function toggleNATField(fieldKey, expand) {
  4575. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4576. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4577. if (!plusBtn || !fieldBox) return;
  4578. if (expand) {
  4579. plusBtn.classList.add('hidden');
  4580. fieldBox.classList.remove('hidden');
  4581. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4582. if (valInput) valInput.focus();
  4583. } else {
  4584. fieldBox.classList.add('hidden');
  4585. plusBtn.classList.remove('hidden');
  4586. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4587. if (valInput) {
  4588. if (valInput.tagName === 'SELECT') {
  4589. valInput.selectedIndex = 0;
  4590. } else {
  4591. valInput.value = '';
  4592. }
  4593. }
  4594. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4595. if (invInput) invInput.checked = false;
  4596. if (fieldKey === 'days') {
  4597. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4598. const el = document.getElementById(`nat-day-${d}`);
  4599. if (el) el.checked = true;
  4600. });
  4601. }
  4602. }
  4603. }
  4604. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4605. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4606. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4607. toggleNATField(fieldKey, true);
  4608. let strVal = String(value);
  4609. if (hasInvert) {
  4610. const inv = strVal.startsWith('!');
  4611. if (inv) strVal = strVal.slice(1);
  4612. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4613. if (invEl) invEl.checked = inv;
  4614. else if (inv) strVal = '!'+strVal;
  4615. }
  4616. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4617. 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; }
  4618. } else {
  4619. toggleNATField(fieldKey, false);
  4620. }
  4621. }
  4622. function getNATFieldVal(fieldKey, hasInvert = false) {
  4623. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4624. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4625. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4626. let v = valEl ? valEl.value.trim() : '';
  4627. if (!v) return '';
  4628. if (hasInvert) {
  4629. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4630. if (invEl && invEl.checked) {
  4631. v = '!' + v.replace(/^!/, '');
  4632. }
  4633. }
  4634. return v;
  4635. }
  4636. function toggleMaximizeNATModal() {
  4637. const win = document.getElementById('nat-modal-window');
  4638. if (!win) return;
  4639. if (win.classList.contains('max-w-[720px]')) {
  4640. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4641. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4642. } else {
  4643. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4644. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4645. }
  4646. }
  4647. function syncNATChainFromSelect() {
  4648. const sel = document.getElementById('nat-modal-chain-select');
  4649. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4650. const customInput = document.getElementById('nat-modal-custom-input');
  4651. const chainInput = document.getElementById('nat-modal-chain');
  4652. if (!sel || !chainInput) return;
  4653. if (sel.value === '__custom__') {
  4654. if (customWrap) customWrap.classList.remove('hidden');
  4655. if (customInput) {
  4656. customInput.value = '';
  4657. customInput.focus();
  4658. }
  4659. chainInput.value = '';
  4660. } else {
  4661. if (customWrap) customWrap.classList.add('hidden');
  4662. chainInput.value = sel.value;
  4663. const actEl = document.getElementById('nat-modal-action');
  4664. if (actEl) {
  4665. const curAct = actEl.value;
  4666. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4667. actEl.value = 'dst-nat';
  4668. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4669. actEl.value = 'masquerade';
  4670. }
  4671. }
  4672. }
  4673. handleNATChainChange();
  4674. }
  4675. function syncNATCustomChainInput() {
  4676. const customInput = document.getElementById('nat-modal-custom-input');
  4677. const chainInput = document.getElementById('nat-modal-chain');
  4678. if (customInput && chainInput) {
  4679. chainInput.value = customInput.value.trim();
  4680. }
  4681. handleNATChainChange();
  4682. }
  4683. function handleNATChainChange() {
  4684. const chainInput = document.getElementById('nat-modal-chain');
  4685. const rawChain = (chainInput?.value || 'postrouting').trim();
  4686. const chain = nativeNATChain(rawChain).toLowerCase();
  4687. const sel = document.getElementById('nat-modal-chain-select');
  4688. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4689. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4690. sel.value = chain;
  4691. }
  4692. }
  4693. const hintEl = document.getElementById('nat-chain-hint');
  4694. if (hintEl) {
  4695. if (chain === 'prerouting') {
  4696. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4697. } else if (chain === 'postrouting') {
  4698. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4699. } else if (chain === 'output') {
  4700. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4701. } else if (chain === 'input') {
  4702. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4703. } else {
  4704. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4705. }
  4706. }
  4707. const rowIn = document.getElementById('nat-row-iniface');
  4708. const rowInList = document.getElementById('nat-row-inifacelist');
  4709. const rowOut = document.getElementById('nat-row-outiface');
  4710. const rowOutList = document.getElementById('nat-row-outifacelist');
  4711. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4712. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4713. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4714. if (chain === 'prerouting' || chain === 'input') {
  4715. if (rowIn) rowIn.classList.remove('hidden');
  4716. if (rowInList) rowInList.classList.remove('hidden');
  4717. if (rowOut) rowOut.classList.add('hidden');
  4718. if (rowOutList) rowOutList.classList.add('hidden');
  4719. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4720. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4721. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4722. } else if (chain === 'postrouting' || chain === 'output') {
  4723. if (rowIn) rowIn.classList.add('hidden');
  4724. if (rowInList) rowInList.classList.add('hidden');
  4725. if (rowOut) rowOut.classList.remove('hidden');
  4726. if (rowOutList) rowOutList.classList.remove('hidden');
  4727. if (rowInBridge) rowInBridge.classList.add('hidden');
  4728. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4729. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4730. } else {
  4731. if (rowIn) rowIn.classList.remove('hidden');
  4732. if (rowInList) rowInList.classList.remove('hidden');
  4733. if (rowOut) rowOut.classList.remove('hidden');
  4734. if (rowOutList) rowOutList.classList.remove('hidden');
  4735. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4736. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4737. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4738. }
  4739. checkNATActionChainCompatibility();
  4740. toggleNATActionFields();
  4741. }
  4742. function checkNATActionChainCompatibility() {
  4743. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4744. const chain = nativeNATChain(rawChain).toLowerCase();
  4745. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4746. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4747. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4748. if (!warnBox || !warnMsg) return;
  4749. let msg = '';
  4750. if (['dst-nat', 'redirect'].includes(action)) {
  4751. if (chain !== 'prerouting' && chain !== 'output') {
  4752. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4753. }
  4754. } else if (action === 'masquerade') {
  4755. if (chain !== 'postrouting') {
  4756. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4757. }
  4758. } else if (action === 'src-nat') {
  4759. if (chain !== 'postrouting' && chain !== 'input') {
  4760. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4761. }
  4762. }
  4763. if (msg) {
  4764. warnMsg.textContent = msg;
  4765. warnBox.classList.remove('hidden');
  4766. } else {
  4767. warnBox.classList.add('hidden');
  4768. }
  4769. }
  4770. function toggleNATActionFields() {
  4771. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4772. const rowAddr = document.getElementById('nat-row-toaddr');
  4773. const rowPort = document.getElementById('nat-row-toport');
  4774. const jumpBox = document.getElementById('nat-action-jump-box');
  4775. const addrBox = document.getElementById('nat-action-addrlist-box');
  4776. // Hide all dynamic rows first
  4777. if (rowAddr) rowAddr.classList.add('hidden');
  4778. if (rowPort) rowPort.classList.add('hidden');
  4779. if (jumpBox) jumpBox.classList.add('hidden');
  4780. if (addrBox) addrBox.classList.add('hidden');
  4781. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4782. if (rowAddr) rowAddr.classList.remove('hidden');
  4783. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4784. } else if (act === 'redirect' || act === 'masquerade') {
  4785. if (rowPort) rowPort.classList.remove('hidden');
  4786. } else if (act === 'jump') {
  4787. if (jumpBox) jumpBox.classList.remove('hidden');
  4788. } else if (act.includes('address-list') || act.includes('address list')) {
  4789. if (addrBox) addrBox.classList.remove('hidden');
  4790. }
  4791. if (act === 'log') {
  4792. const logEl = document.getElementById('nat-modal-log');
  4793. if (logEl) logEl.checked = true;
  4794. toggleNATField('logprefix', true);
  4795. }
  4796. }
  4797. function handleNATActionChange() {
  4798. toggleNATActionFields();
  4799. checkNATActionChainCompatibility();
  4800. }
  4801. function toggleNATLogPrefix() {
  4802. const isLog = document.getElementById('nat-modal-log')?.checked;
  4803. toggleNATField('logprefix', !!isLog);
  4804. }
  4805. function openAddNATModal() {
  4806. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4807. switchNATRuleTab('general');
  4808. setFirewallDays('nat', '');
  4809. const badge = document.getElementById('nat-modal-badge');
  4810. if (badge) badge.innerText = 'New...';
  4811. document.getElementById('nat-modal-id').value = '';
  4812. document.getElementById('nat-modal-family').value = '4';
  4813. document.getElementById('nat-modal-enabled').checked = true;
  4814. document.getElementById('nat-modal-comment').value = '';
  4815. document.getElementById('nat-modal-chain').value = 'postrouting';
  4816. populateChainDropdown('nat', 'postrouting');
  4817. handleNATChainChange();
  4818. document.getElementById('nat-modal-action').value = 'masquerade';
  4819. document.getElementById('nat-modal-toaddr').value = '';
  4820. document.getElementById('nat-modal-toport').value = '';
  4821. document.getElementById('nat-modal-log').checked = false;
  4822. populateInterfaceSelect('nat-val-iniface');
  4823. populateInterfaceSelect('nat-val-outiface');
  4824. populateAddressListSelect('nat-val-srclist');
  4825. populateAddressListSelect('nat-val-dstlist');
  4826. populateGeoIPSelect('nat-val-srcgeo');
  4827. populateGeoIPSelect('nat-val-dstgeo');
  4828. const allFieldKeys = [
  4829. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4830. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4831. 'routingmark', 'conntype',
  4832. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4833. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4834. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4835. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4836. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4837. ];
  4838. allFieldKeys.forEach(k => toggleNATField(k, false));
  4839. resetNATCounterDisplay();
  4840. toggleNATActionFields();
  4841. document.getElementById('nat-modal').classList.remove('hidden');
  4842. }
  4843. function openEditNATModal(id) {
  4844. id = decodeURIComponent(id);
  4845. const r = (state.natRules || []).find(rule => rule.id === id);
  4846. if (!r) return;
  4847. setFirewallDays('nat', r.days || '');
  4848. switchNATRuleTab('general');
  4849. const badge = document.getElementById('nat-modal-badge');
  4850. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4851. document.getElementById('nat-modal-id').value = r.id;
  4852. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4853. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4854. document.getElementById('nat-modal-comment').value = r.comment || '';
  4855. const natChain = nativeNATChain(r.chain || 'postrouting');
  4856. document.getElementById('nat-modal-chain').value = natChain;
  4857. populateChainDropdown('nat', natChain);
  4858. handleNATChainChange();
  4859. setFirewallActionSelection('nat', r.action || 'accept');
  4860. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4861. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4862. document.getElementById('nat-modal-log').checked = !!r.log;
  4863. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4864. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4865. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4866. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4867. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4868. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4869. setNATFieldVal('src', r.src_address, true);
  4870. setNATFieldVal('dst', r.dst_address, true);
  4871. setNATFieldVal('srclist', r.src_address_list, true);
  4872. setNATFieldVal('dstlist', r.dst_address_list, true);
  4873. setNATFieldVal('srcgeo', r.src_geoip, true);
  4874. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4875. if (r.protocol && r.protocol !== 'all') {
  4876. setNATFieldVal('proto', r.protocol, true);
  4877. } else {
  4878. toggleNATField('proto', false);
  4879. }
  4880. setNATFieldVal('sport', r.src_port, true);
  4881. setNATFieldVal('dport', r.dst_port, true);
  4882. setNATFieldVal('anyport', r.any_port, true);
  4883. setNATFieldVal('iniface', r.in_interface, true);
  4884. setNATFieldVal('outiface', r.out_interface, true);
  4885. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4886. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4887. setNATFieldVal('pktmark', r.packet_mark, true);
  4888. setNATFieldVal('connmark', r.connection_mark, true);
  4889. setNATFieldVal('routingmark', r.routing_mark, true);
  4890. setNATFieldVal('conntype', r.connection_type, false);
  4891. // Advanced tab fields
  4892. setNATFieldVal('layer7', r.layer7_protocol, false);
  4893. setNATFieldVal('content', r.content, false);
  4894. setNATFieldVal('connbytes', r.connection_bytes, false);
  4895. setNATFieldVal('connrate', r.connection_rate, false);
  4896. setNATFieldVal('pcc', r.pcc, false);
  4897. setNATFieldVal('srcmac', r.src_mac_address, true);
  4898. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4899. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4900. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4901. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4902. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4903. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4904. setNATFieldVal('priority', r.priority, false);
  4905. setNATFieldVal('dscp', r.dscp, false);
  4906. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4907. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4908. setNATFieldVal('pktsize', r.packet_size, false);
  4909. setNATFieldVal('random', r.random, false);
  4910. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4911. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4912. setNATFieldVal('ttl', r.ttl, false);
  4913. // Extra tab fields
  4914. setNATFieldVal('time', r.time, false);
  4915. if (r.days) {
  4916. toggleNATField('days', true);
  4917. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4918. const chk = document.getElementById(`nat-day-${d}`);
  4919. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4920. });
  4921. } else {
  4922. toggleNATField('days', false);
  4923. }
  4924. setNATFieldVal('limit', r.limit, false);
  4925. setNATFieldVal('dstlimit', r.dst_limit, false);
  4926. setNATFieldVal('psd', r.psd, false);
  4927. // Action fields
  4928. if (r.jump_target) {
  4929. const jtEl = document.getElementById('nat-modal-jumptarget');
  4930. if (jtEl) jtEl.value = r.jump_target;
  4931. }
  4932. if (r.address_list) {
  4933. const alEl = document.getElementById('nat-modal-action-addrlist');
  4934. if (alEl) alEl.value = r.address_list;
  4935. }
  4936. if (r.address_list_timeout) {
  4937. const toEl = document.getElementById('nat-modal-action-timeout');
  4938. if (toEl) toEl.value = r.address_list_timeout;
  4939. }
  4940. setNATFieldVal('logprefix', r.log_prefix, false);
  4941. // Statistics
  4942. const bEl = document.getElementById('nat-stat-bytes');
  4943. const pEl = document.getElementById('nat-stat-packets');
  4944. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4945. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4946. state.natLastBytes = r.bytes || 0;
  4947. state.natLastPackets = r.packets || 0;
  4948. state.natLastTimestamp = Date.now();
  4949. state.natStatRateHistory = new Array(30).fill(0);
  4950. state.natStatPktHistory = new Array(30).fill(0);
  4951. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4952. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4953. toggleNATActionFields();
  4954. document.getElementById('nat-modal').classList.remove('hidden');
  4955. }
  4956. function closeNATModal() {
  4957. stopNATStatPolling();
  4958. document.getElementById('nat-modal').classList.add('hidden');
  4959. }
  4960. function copyNATRule() {
  4961. document.getElementById('nat-modal-id').value = '';
  4962. const badge = document.getElementById('nat-modal-badge');
  4963. if (badge) badge.innerText = 'New...';
  4964. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4965. }
  4966. function resetNATCounterDisplay() {
  4967. state.natStatRateHistory = new Array(30).fill(0);
  4968. state.natStatPktHistory = new Array(30).fill(0);
  4969. state.natLastBytes = 0;
  4970. state.natLastPackets = 0;
  4971. state.natLastTimestamp = Date.now();
  4972. const bEl = document.getElementById('nat-stat-bytes');
  4973. const pEl = document.getElementById('nat-stat-packets');
  4974. const rEl = document.getElementById('nat-stat-rate');
  4975. const prEl = document.getElementById('nat-stat-pktrate');
  4976. if (bEl) bEl.value = '0 B';
  4977. if (pEl) pEl.value = '0';
  4978. if (rEl) rEl.value = '0 bps';
  4979. if (prEl) prEl.value = '0 p/s';
  4980. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4981. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4982. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4983. }
  4984. async function applyNATRule(closeAfter = false) {
  4985. const id = document.getElementById('nat-modal-id').value;
  4986. if (!reviewLegacyFirewallSettings('nat', id)) return;
  4987. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4988. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  4989. const chainLower = nativeNATChain(chain).toLowerCase();
  4990. const action = document.getElementById('nat-modal-action').value;
  4991. const comment = document.getElementById('nat-modal-comment').value.trim();
  4992. const enabled = document.getElementById('nat-modal-enabled').checked;
  4993. const src = getNATFieldVal('src', true);
  4994. const dst = getNATFieldVal('dst', true);
  4995. const srclist = getNATFieldVal('srclist', true);
  4996. const dstlist = getNATFieldVal('dstlist', true);
  4997. const srcgeo = getNATFieldVal('srcgeo', true);
  4998. const dstgeo = getNATFieldVal('dstgeo', true);
  4999. const proto = getNATFieldVal('proto', true);
  5000. const sport = getNATFieldVal('sport', true);
  5001. const dport = getNATFieldVal('dport', true);
  5002. const anyport = getNATFieldVal('anyport', true);
  5003. let iniface = getNATFieldVal('iniface', true);
  5004. let outiface = getNATFieldVal('outiface', true);
  5005. let inifacelist = getNATFieldVal('inifacelist', true);
  5006. let outifacelist = getNATFieldVal('outifacelist', true);
  5007. if (chainLower === 'prerouting' || chainLower === 'input') {
  5008. outiface = '';
  5009. outifacelist = '';
  5010. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5011. iniface = '';
  5012. inifacelist = '';
  5013. }
  5014. const pktmark = getNATFieldVal('pktmark', true);
  5015. const connmark = getNATFieldVal('connmark', true);
  5016. const routingmark = getNATFieldVal('routingmark', true);
  5017. const conntype = getNATFieldVal('conntype', false);
  5018. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5019. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5020. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5021. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5022. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5023. switchNATRuleTab('general');
  5024. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5025. return;
  5026. }
  5027. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5028. switchNATRuleTab('general');
  5029. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5030. return;
  5031. }
  5032. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5033. switchNATRuleTab('general');
  5034. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5035. return;
  5036. }
  5037. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  5038. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5039. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5040. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  5041. }
  5042. const payload = {
  5043. ip_version: Number(document.getElementById('nat-modal-family').value),
  5044. id,
  5045. chain,
  5046. action,
  5047. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5048. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5049. protocol: proto || 'all',
  5050. src_address: src,
  5051. dst_address: dst,
  5052. src_port: sport,
  5053. dst_port: dport,
  5054. any_port: anyport,
  5055. in_interface: iniface,
  5056. out_interface: outiface,
  5057. in_interface_list: inifacelist,
  5058. out_interface_list: outifacelist,
  5059. packet_mark: pktmark,
  5060. connection_mark: connmark,
  5061. routing_mark: routingmark,
  5062. connection_type: conntype,
  5063. src_address_list: srclist,
  5064. dst_address_list: dstlist,
  5065. src_geoip: srcgeo,
  5066. dst_geoip: dstgeo,
  5067. comment,
  5068. disabled: !enabled,
  5069. // Advanced tab
  5070. content: getNATFieldVal('content', false),
  5071. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5072. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5073. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5074. ipsec_policy: getNATFieldVal('ipsec', false),
  5075. dscp: getNATFieldVal('dscp', false),
  5076. tcp_mss: getNATFieldVal('tcpmss', false),
  5077. tos: document.getElementById('nat-val-tos')?.value || '',
  5078. packet_size: getNATFieldVal('pktsize', false),
  5079. random: getNATFieldVal('random', false),
  5080. icmp_options: getNATFieldVal('icmpoptions', false),
  5081. ttl: getNATFieldVal('ttl', false),
  5082. days: selectedDays,
  5083. // Extra tab
  5084. time: getNATFieldVal('time', false),
  5085. limit: getNATFieldVal('limit', false),
  5086. // Action tab
  5087. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5088. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5089. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5090. log: document.getElementById('nat-modal-log')?.checked || false,
  5091. log_prefix: getNATFieldVal('logprefix', false)
  5092. };
  5093. try {
  5094. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5095. method: 'POST',
  5096. headers: { 'Content-Type': 'application/json' },
  5097. body: JSON.stringify(payload)
  5098. });
  5099. if (res.ok) {
  5100. const data = await res.json();
  5101. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5102. loadFirewall(false);
  5103. if (closeAfter) {
  5104. closeNATModal();
  5105. } else {
  5106. if (data.id) {
  5107. document.getElementById('nat-modal-id').value = data.id;
  5108. const badge = document.getElementById('nat-modal-badge');
  5109. if (badge) badge.innerText = `#${data.id}`;
  5110. }
  5111. }
  5112. } else {
  5113. const err = await res.json();
  5114. showToast('Error', err.message || 'Failed to save rule', 'error');
  5115. }
  5116. } catch (err) {
  5117. showToast('Error', err.message, 'error');
  5118. }
  5119. }
  5120. function submitSaveNATRule(e) {
  5121. if (e && e.preventDefault) e.preventDefault();
  5122. return applyNATRule(true);
  5123. }
  5124. function startNATStatPolling() {
  5125. stopNATStatPolling();
  5126. pollNATRuleStats();
  5127. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5128. }
  5129. function stopNATStatPolling() {
  5130. if (state.natStatInterval) {
  5131. clearInterval(state.natStatInterval);
  5132. state.natStatInterval = null;
  5133. }
  5134. }
  5135. async function pollNATRuleStats() {
  5136. const id = document.getElementById('nat-modal-id')?.value;
  5137. if (!id) {
  5138. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5139. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5140. return;
  5141. }
  5142. try {
  5143. const res = await fetch(`${API_BASE}/firewall/nat`);
  5144. if (!res.ok) return;
  5145. const rules = await res.json();
  5146. const r = rules.find(x => x.id === id);
  5147. if (!r) return;
  5148. const now = Date.now();
  5149. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5150. state.natLastTimestamp = now;
  5151. const curBytes = r.bytes || 0;
  5152. const curPackets = r.packets || 0;
  5153. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5154. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5155. state.natLastBytes = curBytes;
  5156. state.natLastPackets = curPackets;
  5157. const rateBps = Math.round((deltaBytes * 8) / dt);
  5158. const ratePkt = Math.round(deltaPkts / dt);
  5159. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5160. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5161. state.natStatRateHistory.push(rateBps);
  5162. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5163. state.natStatPktHistory.push(ratePkt);
  5164. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5165. const bEl = document.getElementById('nat-stat-bytes');
  5166. const pEl = document.getElementById('nat-stat-packets');
  5167. const rEl = document.getElementById('nat-stat-rate');
  5168. const prEl = document.getElementById('nat-stat-pktrate');
  5169. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5170. if (pEl) pEl.value = curPackets.toLocaleString();
  5171. if (rEl) rEl.value = formatBps(rateBps);
  5172. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5173. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5174. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5175. } catch (e) {
  5176. console.error('Error polling NAT rule stats', e);
  5177. }
  5178. }
  5179. async function moveNATRule(id, dir) {
  5180. id = decodeURIComponent(id);
  5181. try {
  5182. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5183. method: 'POST',
  5184. headers: { 'Content-Type': 'application/json' },
  5185. body: JSON.stringify({ direction: dir })
  5186. });
  5187. if (!res.ok) throw new Error(await responseError(res));
  5188. await loadFirewall(false);
  5189. } catch (err) {
  5190. showToast('Error', err.message, 'error');
  5191. }
  5192. }
  5193. async function toggleNATRuleState(id, disabled) {
  5194. id = decodeURIComponent(id);
  5195. try {
  5196. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5197. method: 'POST',
  5198. headers: { 'Content-Type': 'application/json' },
  5199. body: JSON.stringify({ disabled })
  5200. });
  5201. if (!res.ok) throw new Error(await responseError(res));
  5202. await loadFirewall(false);
  5203. } catch (err) {
  5204. showToast('Error', err.message, 'error');
  5205. }
  5206. }
  5207. async function deleteNATRule(id) {
  5208. id = decodeURIComponent(id);
  5209. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5210. try {
  5211. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5212. if (!res.ok) throw new Error(await responseError(res));
  5213. {
  5214. showToast('Deleted', 'NAT rule removed', 'success');
  5215. loadFirewall(false);
  5216. }
  5217. } catch (err) {
  5218. showToast('Error', err.message, 'error');
  5219. }
  5220. }
  5221. // ----------------- Mangle Rules -----------------
  5222. function renderMangleRules() {
  5223. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5224. const tbody = document.getElementById('mangle-table-body');
  5225. const empty = document.getElementById('mangle-empty');
  5226. if (!tbody) return;
  5227. tbody.innerHTML = '';
  5228. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5229. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5230. if (rules.length === 0) {
  5231. empty?.classList.remove('hidden');
  5232. return;
  5233. }
  5234. empty?.classList.add('hidden');
  5235. rules.forEach((raw, idx) => {
  5236. const r = safeFirewallRow(raw);
  5237. const tr = document.createElement('tr');
  5238. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5239. let markVal = '<span class="text-slate-500">-</span>';
  5240. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5241. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5242. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5243. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5244. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5245. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5246. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5247. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5248. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5249. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5250. 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>`;
  5251. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5252. tr.innerHTML = `
  5253. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5254. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5255. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5256. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5257. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5258. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5259. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5260. <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>
  5261. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5262. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5263. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5264. </td>
  5265. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5266. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5267. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5268. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5269. <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>
  5270. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5271. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5272. </td>
  5273. `;
  5274. tbody.appendChild(tr);
  5275. });
  5276. }
  5277. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5278. function switchMangleRuleTab(tab) {
  5279. state.activeMangleRuleTab = tab;
  5280. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5281. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5282. btn.classList.add('text-slate-400', 'border-transparent');
  5283. });
  5284. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5285. if (activeBtn) {
  5286. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5287. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5288. }
  5289. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5290. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5291. if (activePane) activePane.classList.remove('hidden');
  5292. if (tab === 'statistics') {
  5293. startMangleStatPolling();
  5294. } else {
  5295. stopMangleStatPolling();
  5296. }
  5297. }
  5298. function toggleMangleField(fieldKey, expand) {
  5299. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5300. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5301. if (!plusBtn || !fieldBox) return;
  5302. if (expand) {
  5303. plusBtn.classList.add('hidden');
  5304. fieldBox.classList.remove('hidden');
  5305. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5306. if (valInput) valInput.focus();
  5307. } else {
  5308. fieldBox.classList.add('hidden');
  5309. plusBtn.classList.remove('hidden');
  5310. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5311. if (valInput) {
  5312. if (valInput.tagName === 'SELECT') {
  5313. valInput.selectedIndex = 0;
  5314. } else {
  5315. valInput.value = '';
  5316. }
  5317. }
  5318. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5319. if (invInput) invInput.checked = false;
  5320. if (fieldKey === 'cs') {
  5321. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5322. const el = document.getElementById(id);
  5323. if (el) el.checked = false;
  5324. });
  5325. }
  5326. if (fieldKey === 'natstate') {
  5327. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5328. const el = document.getElementById(id);
  5329. if (el) el.checked = false;
  5330. });
  5331. }
  5332. }
  5333. }
  5334. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5335. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5336. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5337. toggleMangleField(fieldKey, true);
  5338. let strVal = String(value);
  5339. if (hasInvert) {
  5340. const inv = strVal.startsWith('!');
  5341. if (inv) strVal = strVal.slice(1);
  5342. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5343. if (invEl) invEl.checked = inv;
  5344. else if (inv) strVal = '!'+strVal;
  5345. }
  5346. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5347. 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; }
  5348. } else {
  5349. toggleMangleField(fieldKey, false);
  5350. }
  5351. }
  5352. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5353. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5354. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5355. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5356. let v = valEl ? valEl.value.trim() : '';
  5357. if (!v) return '';
  5358. if (hasInvert) {
  5359. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5360. if (invEl && invEl.checked) {
  5361. v = '!' + v.replace(/^!/, '');
  5362. }
  5363. }
  5364. return v;
  5365. }
  5366. function toggleMaximizeMangleModal() {
  5367. const win = document.getElementById('mangle-modal-window');
  5368. if (!win) return;
  5369. if (win.classList.contains('max-w-[720px]')) {
  5370. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5371. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5372. } else {
  5373. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5374. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5375. }
  5376. }
  5377. function syncMangleChainFromSelect() {
  5378. const sel = document.getElementById('mangle-modal-chain-select');
  5379. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5380. const customInput = document.getElementById('mangle-modal-custom-input');
  5381. const chainInput = document.getElementById('mangle-modal-chain');
  5382. if (!sel || !chainInput) return;
  5383. if (sel.value === '__custom__') {
  5384. if (customWrap) customWrap.classList.remove('hidden');
  5385. if (customInput) {
  5386. customInput.value = '';
  5387. customInput.focus();
  5388. }
  5389. chainInput.value = '';
  5390. } else {
  5391. if (customWrap) customWrap.classList.add('hidden');
  5392. chainInput.value = sel.value;
  5393. }
  5394. handleMangleChainChange();
  5395. }
  5396. function syncMangleCustomChainInput() {
  5397. const customInput = document.getElementById('mangle-modal-custom-input');
  5398. const chainInput = document.getElementById('mangle-modal-chain');
  5399. if (customInput && chainInput) {
  5400. chainInput.value = customInput.value.trim();
  5401. }
  5402. handleMangleChainChange();
  5403. }
  5404. function handleMangleChainChange() {
  5405. const chainInput = document.getElementById('mangle-modal-chain');
  5406. const rawChain = (chainInput?.value || 'prerouting').trim();
  5407. const chain = rawChain.toLowerCase();
  5408. const sel = document.getElementById('mangle-modal-chain-select');
  5409. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5410. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5411. sel.value = chain;
  5412. }
  5413. }
  5414. const hintEl = document.getElementById('mangle-chain-hint');
  5415. if (hintEl) {
  5416. if (chain === 'prerouting') {
  5417. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5418. } else if (chain === 'input') {
  5419. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5420. } else if (chain === 'forward') {
  5421. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5422. } else if (chain === 'output') {
  5423. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5424. } else if (chain === 'postrouting') {
  5425. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5426. } else {
  5427. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5428. }
  5429. }
  5430. const rowIn = document.getElementById('mangle-row-iniface');
  5431. const rowInList = document.getElementById('mangle-row-inifacelist');
  5432. const rowOut = document.getElementById('mangle-row-outiface');
  5433. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5434. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5435. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5436. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5437. if (chain === 'prerouting' || chain === 'input') {
  5438. if (rowIn) rowIn.classList.remove('hidden');
  5439. if (rowInList) rowInList.classList.remove('hidden');
  5440. if (rowOut) rowOut.classList.add('hidden');
  5441. if (rowOutList) rowOutList.classList.add('hidden');
  5442. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5443. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5444. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5445. } else if (chain === 'output' || chain === 'postrouting') {
  5446. if (rowIn) rowIn.classList.add('hidden');
  5447. if (rowInList) rowInList.classList.add('hidden');
  5448. if (rowOut) rowOut.classList.remove('hidden');
  5449. if (rowOutList) rowOutList.classList.remove('hidden');
  5450. if (rowInBridge) rowInBridge.classList.add('hidden');
  5451. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5452. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5453. } else {
  5454. if (rowIn) rowIn.classList.remove('hidden');
  5455. if (rowInList) rowInList.classList.remove('hidden');
  5456. if (rowOut) rowOut.classList.remove('hidden');
  5457. if (rowOutList) rowOutList.classList.remove('hidden');
  5458. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5459. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5460. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5461. }
  5462. checkMangleActionChainCompatibility();
  5463. toggleMangleActionFields();
  5464. }
  5465. function checkMangleActionChainCompatibility() {
  5466. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5467. const chain = rawChain.toLowerCase();
  5468. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5469. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5470. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5471. if (!warnBox || !warnMsg) return;
  5472. let msg = '';
  5473. if (action === 'set-priority' && chain !== 'postrouting') {
  5474. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5475. }
  5476. if (msg) {
  5477. warnMsg.textContent = msg;
  5478. warnBox.classList.remove('hidden');
  5479. } else {
  5480. warnBox.classList.add('hidden');
  5481. }
  5482. }
  5483. function toggleMangleActionFields() {
  5484. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5485. // Hide all dynamic rows first
  5486. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5487. const el = document.getElementById(`mangle-row-${id}`);
  5488. if (el) el.classList.add('hidden');
  5489. });
  5490. const jumpBox = document.getElementById('mangle-action-jump-box');
  5491. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5492. if (jumpBox) jumpBox.classList.add('hidden');
  5493. if (addrBox) addrBox.classList.add('hidden');
  5494. // Activate matching rows
  5495. if (act === 'mark-connection') {
  5496. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5497. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5498. } else if (act === 'mark-routing') {
  5499. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5500. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5501. } else if (act === 'mark-packet') {
  5502. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5503. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5504. } else if (act === 'change-mss') {
  5505. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5506. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5507. } else if (act === 'change-dscp') {
  5508. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5509. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5510. } else if (act === 'change-ttl') {
  5511. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5512. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5513. } else if (act === 'set-priority') {
  5514. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5515. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5516. } else if (act === 'route') {
  5517. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5518. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5519. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5520. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5521. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5522. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5523. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5524. } else if (act === 'jump') {
  5525. if (jumpBox) jumpBox.classList.remove('hidden');
  5526. } else if (act.includes('address-list') || act.includes('address list')) {
  5527. if (addrBox) addrBox.classList.remove('hidden');
  5528. }
  5529. if (act === 'log') {
  5530. const logEl = document.getElementById('mangle-modal-log');
  5531. if (logEl) logEl.checked = true;
  5532. toggleMangleField('logprefix', true);
  5533. }
  5534. checkMangleActionChainCompatibility();
  5535. }
  5536. function toggleMangleLogPrefix() {
  5537. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5538. toggleMangleField('logprefix', !!isLog);
  5539. }
  5540. const allMangleFieldKeys = [
  5541. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5542. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5543. 'routingmark', 'conntype', 'cs', 'natstate',
  5544. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5545. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5546. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5547. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5548. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5549. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5550. ];
  5551. function openAddMangleModal() {
  5552. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5553. switchMangleRuleTab('general');
  5554. const badge = document.getElementById('mangle-modal-badge');
  5555. if (badge) badge.innerText = 'New...';
  5556. document.getElementById('mangle-modal-id').value = '';
  5557. document.getElementById('mangle-modal-family').value = '4';
  5558. document.getElementById('mangle-modal-enabled').checked = true;
  5559. document.getElementById('mangle-modal-comment').value = '';
  5560. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5561. populateChainDropdown('mangle', 'prerouting');
  5562. handleMangleChainChange();
  5563. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5564. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5565. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5566. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5567. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5568. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5569. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5570. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5571. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5572. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5573. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5574. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5575. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5576. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5577. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5578. populateInterfaceSelect('mangle-val-iniface');
  5579. populateInterfaceSelect('mangle-val-outiface');
  5580. populateAddressListSelect('mangle-val-srclist');
  5581. populateAddressListSelect('mangle-val-dstlist');
  5582. populateGeoIPSelect('mangle-val-srcgeo');
  5583. populateGeoIPSelect('mangle-val-dstgeo');
  5584. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5585. resetMangleCounterDisplay();
  5586. toggleMangleActionFields();
  5587. document.getElementById('mangle-modal').classList.remove('hidden');
  5588. }
  5589. function openEditMangleModal(id) {
  5590. id = decodeURIComponent(id);
  5591. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5592. if (!r) return;
  5593. switchMangleRuleTab('general');
  5594. const badge = document.getElementById('mangle-modal-badge');
  5595. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5596. document.getElementById('mangle-modal-id').value = r.id;
  5597. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5598. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5599. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5600. const mangleChain = r.chain || 'prerouting';
  5601. document.getElementById('mangle-modal-chain').value = mangleChain;
  5602. populateChainDropdown('mangle', mangleChain);
  5603. handleMangleChainChange();
  5604. setFirewallActionSelection('mangle', r.action || 'accept');
  5605. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5606. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5607. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5608. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5609. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5610. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5611. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5612. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5613. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5614. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5615. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5616. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5617. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5618. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5619. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5620. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5621. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5622. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5623. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5624. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5625. setMangleFieldVal('src', r.src_address, true);
  5626. setMangleFieldVal('dst', r.dst_address, true);
  5627. setMangleFieldVal('srclist', r.src_address_list, true);
  5628. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5629. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5630. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5631. if (r.protocol && r.protocol !== 'all') {
  5632. setMangleFieldVal('proto', r.protocol, true);
  5633. } else {
  5634. toggleMangleField('proto', false);
  5635. }
  5636. setMangleFieldVal('sport', r.src_port, true);
  5637. setMangleFieldVal('dport', r.dst_port, true);
  5638. setMangleFieldVal('anyport', r.any_port, true);
  5639. setMangleFieldVal('iniface', r.in_interface, true);
  5640. setMangleFieldVal('outiface', r.out_interface, true);
  5641. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5642. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5643. setMangleFieldVal('pktmark', r.packet_mark, true);
  5644. setMangleFieldVal('connmark', r.connection_mark, true);
  5645. setMangleFieldVal('routingmark', r.routing_mark, true);
  5646. setMangleFieldVal('conntype', r.connection_type, false);
  5647. // Connection State
  5648. const states = r.connection_state || [];
  5649. if (states.length > 0) {
  5650. toggleMangleField('cs', true);
  5651. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5652. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5653. if (el) el.checked = states.includes(s);
  5654. });
  5655. } else {
  5656. toggleMangleField('cs', false);
  5657. }
  5658. // Connection NAT State
  5659. const natStates = r.connection_nat_state || [];
  5660. if (natStates.length > 0) {
  5661. toggleMangleField('natstate', true);
  5662. ['srcnat', 'dstnat'].forEach(s => {
  5663. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5664. if (el) el.checked = natStates.includes(s);
  5665. });
  5666. } else {
  5667. toggleMangleField('natstate', false);
  5668. }
  5669. // Advanced tab fields
  5670. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5671. setMangleFieldVal('content', r.content, false);
  5672. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5673. setMangleFieldVal('connrate', r.connection_rate, false);
  5674. setMangleFieldVal('pcc', r.pcc, false);
  5675. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5676. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5677. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5678. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5679. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5680. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5681. setMangleFieldVal('tlshost', r.tls_host, false);
  5682. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5683. setMangleFieldVal('priority', r.priority, false);
  5684. setMangleFieldVal('dscp', r.dscp, false);
  5685. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5686. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5687. setMangleFieldVal('pktsize', r.packet_size, false);
  5688. setMangleFieldVal('random', r.random, false);
  5689. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5690. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5691. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5692. setMangleFieldVal('ttl', r.ttl, false);
  5693. // Extra tab fields
  5694. setMangleFieldVal('nth', r.nth, false);
  5695. setMangleFieldVal('connlimit', r.connection_limit, false);
  5696. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5697. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5698. setMangleFieldVal('hotspot', r.hotspot, false);
  5699. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5700. setMangleFieldVal('limit', r.limit, false);
  5701. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5702. setMangleFieldVal('time', r.time, false);
  5703. setMangleFieldVal('psd', r.psd, false);
  5704. // Action fields
  5705. if (r.jump_target) {
  5706. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5707. if (jtEl) jtEl.value = r.jump_target;
  5708. }
  5709. if (r.address_list) {
  5710. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5711. if (alEl) alEl.value = r.address_list;
  5712. }
  5713. if (r.address_list_timeout) {
  5714. const toEl = document.getElementById('mangle-modal-action-timeout');
  5715. if (toEl) toEl.value = r.address_list_timeout;
  5716. }
  5717. setMangleFieldVal('logprefix', r.log_prefix, false);
  5718. // Statistics
  5719. const bEl = document.getElementById('mangle-stat-bytes');
  5720. const pEl = document.getElementById('mangle-stat-packets');
  5721. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5722. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5723. state.mangleLastBytes = r.bytes || 0;
  5724. state.mangleLastPackets = r.packets || 0;
  5725. state.mangleLastTimestamp = Date.now();
  5726. state.mangleStatRateHistory = new Array(30).fill(0);
  5727. state.mangleStatPktHistory = new Array(30).fill(0);
  5728. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5729. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5730. toggleMangleActionFields();
  5731. document.getElementById('mangle-modal').classList.remove('hidden');
  5732. }
  5733. function closeMangleModal() {
  5734. stopMangleStatPolling();
  5735. document.getElementById('mangle-modal').classList.add('hidden');
  5736. }
  5737. function copyMangleRule() {
  5738. document.getElementById('mangle-modal-id').value = '';
  5739. const badge = document.getElementById('mangle-modal-badge');
  5740. if (badge) badge.innerText = 'New...';
  5741. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5742. }
  5743. function resetMangleCounterDisplay() {
  5744. state.mangleStatRateHistory = new Array(30).fill(0);
  5745. state.mangleStatPktHistory = new Array(30).fill(0);
  5746. state.mangleLastBytes = 0;
  5747. state.mangleLastPackets = 0;
  5748. state.mangleLastTimestamp = Date.now();
  5749. const bEl = document.getElementById('mangle-stat-bytes');
  5750. const pEl = document.getElementById('mangle-stat-packets');
  5751. const rEl = document.getElementById('mangle-stat-rate');
  5752. const prEl = document.getElementById('mangle-stat-pktrate');
  5753. if (bEl) bEl.value = '0 B';
  5754. if (pEl) pEl.value = '0';
  5755. if (rEl) rEl.value = '0 bps';
  5756. if (prEl) prEl.value = '0 p/s';
  5757. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5758. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5759. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5760. }
  5761. async function applyMangleRule(closeAfter = false) {
  5762. const id = document.getElementById('mangle-modal-id').value;
  5763. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5764. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5765. const chainLower = chain.toLowerCase();
  5766. const action = document.getElementById('mangle-modal-action').value;
  5767. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5768. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5769. const src = getMangleFieldVal('src', true);
  5770. const dst = getMangleFieldVal('dst', true);
  5771. const srclist = getMangleFieldVal('srclist', true);
  5772. const dstlist = getMangleFieldVal('dstlist', true);
  5773. const srcgeo = getMangleFieldVal('srcgeo', true);
  5774. const dstgeo = getMangleFieldVal('dstgeo', true);
  5775. const proto = getMangleFieldVal('proto', true);
  5776. const sport = getMangleFieldVal('sport', true);
  5777. const dport = getMangleFieldVal('dport', true);
  5778. const anyport = getMangleFieldVal('anyport', true);
  5779. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5780. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5781. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5782. }
  5783. let iniface = getMangleFieldVal('iniface', true);
  5784. let outiface = getMangleFieldVal('outiface', true);
  5785. let inifacelist = getMangleFieldVal('inifacelist', true);
  5786. let outifacelist = getMangleFieldVal('outifacelist', true);
  5787. if (chainLower === 'prerouting' || chainLower === 'input') {
  5788. outiface = '';
  5789. outifacelist = '';
  5790. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5791. iniface = '';
  5792. inifacelist = '';
  5793. }
  5794. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5795. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5796. switchMangleRuleTab('general');
  5797. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5798. return;
  5799. }
  5800. const pktmark = getMangleFieldVal('pktmark', true);
  5801. const connmark = getMangleFieldVal('connmark', true);
  5802. const routingmark = getMangleFieldVal('routingmark', true);
  5803. const conntype = getMangleFieldVal('conntype', false);
  5804. const states = [];
  5805. const csBox = document.getElementById('mangle-field-cs');
  5806. if (csBox && !csBox.classList.contains('hidden')) {
  5807. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5808. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5809. });
  5810. }
  5811. const natStates = [];
  5812. const natBox = document.getElementById('mangle-field-natstate');
  5813. if (natBox && !natBox.classList.contains('hidden')) {
  5814. ['srcnat', 'dstnat'].forEach(s => {
  5815. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5816. });
  5817. }
  5818. const payload = {
  5819. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5820. id,
  5821. chain,
  5822. action,
  5823. protocol: proto || 'all',
  5824. src_address: src,
  5825. dst_address: dst,
  5826. src_port: sport,
  5827. dst_port: dport,
  5828. any_port: anyport,
  5829. in_interface: iniface,
  5830. out_interface: outiface,
  5831. in_interface_list: inifacelist,
  5832. out_interface_list: outifacelist,
  5833. packet_mark: pktmark,
  5834. connection_mark: connmark,
  5835. routing_mark: routingmark,
  5836. connection_type: conntype,
  5837. connection_state: states,
  5838. connection_nat_state: natStates,
  5839. src_address_list: srclist,
  5840. dst_address_list: dstlist,
  5841. src_geoip: srcgeo,
  5842. dst_geoip: dstgeo,
  5843. comment,
  5844. disabled: !enabled,
  5845. // Advanced tab
  5846. content: getMangleFieldVal('content', false),
  5847. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5848. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5849. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5850. ipsec_policy: getMangleFieldVal('ipsec', false),
  5851. dscp: getMangleFieldVal('dscp', false),
  5852. tcp_mss: getMangleFieldVal('tcpmss', false),
  5853. tos: document.getElementById('mangle-val-tos')?.value || '',
  5854. packet_size: getMangleFieldVal('pktsize', false),
  5855. random: getMangleFieldVal('random', false),
  5856. tcp_flags: getMangleFieldVal('tcpflags', false),
  5857. icmp_options: getMangleFieldVal('icmpoptions', false),
  5858. ttl: getMangleFieldVal('ttl', false),
  5859. // Extra tab
  5860. nth: getMangleFieldVal('nth', false),
  5861. connection_limit: getMangleFieldVal('connlimit', false),
  5862. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5863. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5864. ip_fragment: getMangleFieldVal('ipfragment', false),
  5865. limit: getMangleFieldVal('limit', false),
  5866. time: getMangleFieldVal('time', false),
  5867. // Action tab
  5868. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5869. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5870. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5871. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5872. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5873. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5874. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5875. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5876. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5877. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5878. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5879. log: document.getElementById('mangle-modal-log')?.checked || false,
  5880. log_prefix: getMangleFieldVal('logprefix', false)
  5881. };
  5882. try {
  5883. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5884. method: 'POST',
  5885. headers: { 'Content-Type': 'application/json' },
  5886. body: JSON.stringify(payload)
  5887. });
  5888. if (res.ok) {
  5889. const data = await res.json();
  5890. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5891. loadFirewall(false);
  5892. if (closeAfter) {
  5893. closeMangleModal();
  5894. } else {
  5895. if (data.id) {
  5896. document.getElementById('mangle-modal-id').value = data.id;
  5897. const badge = document.getElementById('mangle-modal-badge');
  5898. if (badge) badge.innerText = `#${data.id}`;
  5899. }
  5900. }
  5901. } else {
  5902. const err = await res.json();
  5903. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5904. }
  5905. } catch (err) {
  5906. showToast('Error', err.message, 'error');
  5907. }
  5908. }
  5909. function submitSaveMangleRule(e) {
  5910. if (e && e.preventDefault) e.preventDefault();
  5911. return applyMangleRule(true);
  5912. }
  5913. function startMangleStatPolling() {
  5914. stopMangleStatPolling();
  5915. pollMangleRuleStats();
  5916. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5917. }
  5918. function stopMangleStatPolling() {
  5919. if (state.mangleStatInterval) {
  5920. clearInterval(state.mangleStatInterval);
  5921. state.mangleStatInterval = null;
  5922. }
  5923. }
  5924. async function pollMangleRuleStats() {
  5925. const id = document.getElementById('mangle-modal-id')?.value;
  5926. if (!id) {
  5927. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5928. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5929. return;
  5930. }
  5931. try {
  5932. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5933. if (!res.ok) return;
  5934. const rules = await res.json();
  5935. const r = rules.find(x => x.id === id);
  5936. if (!r) return;
  5937. const now = Date.now();
  5938. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5939. state.mangleLastTimestamp = now;
  5940. const curBytes = r.bytes || 0;
  5941. const curPackets = r.packets || 0;
  5942. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5943. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5944. state.mangleLastBytes = curBytes;
  5945. state.mangleLastPackets = curPackets;
  5946. const rateBps = Math.round((deltaBytes * 8) / dt);
  5947. const ratePkt = Math.round(deltaPkts / dt);
  5948. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5949. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5950. state.mangleStatRateHistory.push(rateBps);
  5951. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5952. state.mangleStatPktHistory.push(ratePkt);
  5953. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5954. const bEl = document.getElementById('mangle-stat-bytes');
  5955. const pEl = document.getElementById('mangle-stat-packets');
  5956. const rEl = document.getElementById('mangle-stat-rate');
  5957. const prEl = document.getElementById('mangle-stat-pktrate');
  5958. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5959. if (pEl) pEl.value = curPackets.toLocaleString();
  5960. if (rEl) rEl.value = formatBps(rateBps);
  5961. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5962. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5963. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5964. } catch (e) {
  5965. console.error('Error polling Mangle rule stats', e);
  5966. }
  5967. }
  5968. async function moveMangleRule(id, dir) {
  5969. id = decodeURIComponent(id);
  5970. try {
  5971. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5972. method: 'POST',
  5973. headers: { 'Content-Type': 'application/json' },
  5974. body: JSON.stringify({ direction: dir })
  5975. });
  5976. if (!res.ok) throw new Error(await responseError(res));
  5977. await loadFirewall(false);
  5978. } catch (err) {
  5979. showToast('Error', err.message, 'error');
  5980. }
  5981. }
  5982. async function toggleMangleRuleState(id, disabled) {
  5983. id = decodeURIComponent(id);
  5984. try {
  5985. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5986. method: 'POST',
  5987. headers: { 'Content-Type': 'application/json' },
  5988. body: JSON.stringify({ disabled })
  5989. });
  5990. if (!res.ok) throw new Error(await responseError(res));
  5991. await loadFirewall(false);
  5992. } catch (err) {
  5993. showToast('Error', err.message, 'error');
  5994. }
  5995. }
  5996. async function deleteMangleRule(id) {
  5997. id = decodeURIComponent(id);
  5998. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5999. try {
  6000. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6001. if (!res.ok) throw new Error(await responseError(res));
  6002. {
  6003. showToast('Deleted', 'Mangle rule removed', 'success');
  6004. loadFirewall(false);
  6005. }
  6006. } catch (err) {
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. }
  6010. // ----------------- Address Lists -----------------
  6011. function renderAddressLists() {
  6012. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6013. const tbody = document.getElementById('addrlist-table-body');
  6014. const empty = document.getElementById('addrlist-empty');
  6015. if (!tbody) return;
  6016. tbody.innerHTML = '';
  6017. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6018. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6019. // Update filter select
  6020. const sel = document.getElementById('addrlist-filter-name');
  6021. if (sel) {
  6022. const cur = sel.value;
  6023. sel.innerHTML = '<option value="">All Lists</option>';
  6024. const set = new Set((state.addressLists || []).map(a => a.name));
  6025. set.forEach(n => {
  6026. const opt = document.createElement('option');
  6027. opt.value = n;
  6028. opt.innerText = n;
  6029. if (n === cur) opt.selected = true;
  6030. sel.appendChild(opt);
  6031. });
  6032. }
  6033. if (entries.length === 0) {
  6034. empty?.classList.remove('hidden');
  6035. return;
  6036. }
  6037. empty?.classList.add('hidden');
  6038. entries.forEach((raw, idx) => {
  6039. const e = safeFirewallRow(raw);
  6040. const tr = document.createElement('tr');
  6041. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6042. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6043. tr.innerHTML = `
  6044. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6045. <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>
  6046. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6047. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6048. <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>
  6049. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6050. ${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>
  6051. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6052. `}
  6053. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6054. </td>
  6055. `;
  6056. tbody.appendChild(tr);
  6057. });
  6058. populateCommonAddrListDatalist();
  6059. }
  6060. function openAddAddrListModal() {
  6061. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6062. document.getElementById('addrlist-modal-id').value = '';
  6063. document.getElementById('addrlist-modal-name').value = '';
  6064. document.getElementById('addrlist-modal-addr').value = '';
  6065. document.getElementById('addrlist-modal-comment').value = '';
  6066. document.getElementById('addrlist-modal-disabled').checked = false;
  6067. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6068. if (submitBtn) submitBtn.innerText = 'Add to List';
  6069. document.getElementById('addrlist-modal').classList.remove('hidden');
  6070. }
  6071. function openEditAddrListModal(id) {
  6072. id = decodeURIComponent(id);
  6073. const e = (state.addressLists || []).find(item => item.id === id);
  6074. if (!e) return;
  6075. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6076. document.getElementById('addrlist-modal-id').value = e.id;
  6077. document.getElementById('addrlist-modal-name').value = e.name;
  6078. document.getElementById('addrlist-modal-addr').value = e.address;
  6079. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6080. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6081. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6082. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6083. document.getElementById('addrlist-modal').classList.remove('hidden');
  6084. }
  6085. function closeAddrListModal() {
  6086. document.getElementById('addrlist-modal').classList.add('hidden');
  6087. }
  6088. async function submitSaveAddrList(e) {
  6089. e.preventDefault();
  6090. const id = document.getElementById('addrlist-modal-id').value;
  6091. const name = document.getElementById('addrlist-modal-name').value.trim();
  6092. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6093. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6094. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6095. try {
  6096. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6097. method: 'POST',
  6098. headers: { 'Content-Type': 'application/json' },
  6099. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6100. });
  6101. if (res.ok) {
  6102. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6103. closeAddrListModal();
  6104. loadFirewall(false);
  6105. } else {
  6106. const err = await res.json();
  6107. showToast('Error', err.message || 'Failed to save address list', 'error');
  6108. }
  6109. } catch (err) {
  6110. showToast('Error', err.message, 'error');
  6111. }
  6112. }
  6113. async function toggleAddrListState(id, disabled) {
  6114. id = decodeURIComponent(id);
  6115. try {
  6116. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6117. method: 'POST',
  6118. headers: { 'Content-Type': 'application/json' },
  6119. body: JSON.stringify({ disabled })
  6120. });
  6121. if (res.ok) {
  6122. loadFirewall(false);
  6123. }
  6124. } catch (err) {
  6125. showToast('Error', err.message, 'error');
  6126. }
  6127. }
  6128. async function deleteAddrList(id) {
  6129. id = decodeURIComponent(id);
  6130. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6131. try {
  6132. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6133. if (res.ok) {
  6134. showToast('Deleted', 'Address list item removed', 'info');
  6135. loadFirewall(false);
  6136. }
  6137. } catch (err) {
  6138. showToast('Error', err.message, 'error');
  6139. }
  6140. }
  6141. // ----------------- Geo-Location IP Management -----------------
  6142. async function loadGeoIP() {
  6143. try {
  6144. const [statusRes, countriesRes] = await Promise.all([
  6145. fetch(`${API_BASE}/firewall/geoip/status`),
  6146. fetch(`${API_BASE}/firewall/geoip/countries`)
  6147. ]);
  6148. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6149. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6150. updateGeoHeader();
  6151. renderGeoCountries();
  6152. } catch (err) {
  6153. console.error('Failed to load GeoIP:', err);
  6154. }
  6155. }
  6156. function getGeoUsageMap() {
  6157. const usage = {};
  6158. const checkRule = (r, type) => {
  6159. ['src_geoip', 'dst_geoip'].forEach(field => {
  6160. let val = (r && r[field]) || '';
  6161. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6162. if (code) {
  6163. if (!usage[code]) usage[code] = [];
  6164. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6165. if (!usage[code].includes(label)) usage[code].push(label);
  6166. }
  6167. });
  6168. };
  6169. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6170. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6171. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6172. return usage;
  6173. }
  6174. function updateGeoHeader() {
  6175. const s = state.geoStatus || {};
  6176. const statusBadge = document.getElementById('geo-status-badge');
  6177. if (statusBadge) {
  6178. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6179. statusBadge.className = s.auto_update
  6180. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6181. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6182. }
  6183. const intervalLabel = document.getElementById('geo-interval-label');
  6184. if (intervalLabel) {
  6185. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6186. }
  6187. const usageMap = getGeoUsageMap();
  6188. const inUseCount = Object.keys(usageMap).length;
  6189. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6190. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6191. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6192. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6193. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6194. if (lastSyncEl) {
  6195. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6196. const d = new Date(s.last_updated);
  6197. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6198. } else {
  6199. lastSyncEl.innerText = 'Never (Sync Pending)';
  6200. }
  6201. }
  6202. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6203. if (nextSyncEl) {
  6204. if (s.next_update && !s.next_update.startsWith('0001')) {
  6205. const d = new Date(s.next_update);
  6206. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6207. } else {
  6208. nextSyncEl.innerText = '-';
  6209. }
  6210. }
  6211. const badge = document.getElementById('fw-badge-geo');
  6212. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6213. }
  6214. function renderGeoCountries() {
  6215. const tbody = document.getElementById('geo-table-body');
  6216. const empty = document.getElementById('geo-empty');
  6217. if (!tbody) return;
  6218. tbody.innerHTML = '';
  6219. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6220. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6221. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6222. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6223. const usageMap = getGeoUsageMap();
  6224. const countries = (state.geoCountries || []).filter(c => {
  6225. const isUsed = !!usageMap[c.code];
  6226. if (inUseOnly && !isUsed) return false;
  6227. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6228. if (continent && c.continent !== continent) return false;
  6229. if (q) {
  6230. const matchCode = c.code.toLowerCase().includes(q);
  6231. const matchName = c.name.toLowerCase().includes(q);
  6232. if (!matchCode && !matchName) return false;
  6233. }
  6234. return true;
  6235. });
  6236. if (countries.length === 0) {
  6237. empty?.classList.remove('hidden');
  6238. return;
  6239. }
  6240. empty?.classList.add('hidden');
  6241. countries.forEach(c => {
  6242. const tr = document.createElement('tr');
  6243. const isUsed = !!usageMap[c.code];
  6244. const rulesUsing = usageMap[c.code] || [];
  6245. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6246. let statusHtml = '';
  6247. if (isUsed) {
  6248. 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>`;
  6249. } else if (c.subnet_count > 0) {
  6250. 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>';
  6251. } else {
  6252. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6253. }
  6254. tr.innerHTML = `
  6255. <td class="py-2.5 px-3 text-center">
  6256. <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'}">
  6257. ${c.code}
  6258. </span>
  6259. </td>
  6260. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6261. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6262. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6263. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6264. </td>
  6265. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6266. <td class="py-2.5 px-3">
  6267. ${statusHtml}
  6268. </td>
  6269. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6270. <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>
  6271. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6272. </td>
  6273. `;
  6274. tbody.appendChild(tr);
  6275. });
  6276. }
  6277. function quickFilterGeo(preset) {
  6278. const searchInput = document.getElementById('geo-search-input');
  6279. const continentSel = document.getElementById('geo-continent-filter');
  6280. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6281. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6282. if (searchInput) searchInput.value = '';
  6283. if (continentSel) continentSel.value = '';
  6284. if (inUseCheck) inUseCheck.checked = false;
  6285. if (cachedCheck) cachedCheck.checked = false;
  6286. if (preset === 'GR') {
  6287. if (searchInput) searchInput.value = 'Greece';
  6288. } else if (preset === 'Europe') {
  6289. if (continentSel) continentSel.value = 'Europe';
  6290. } else if (preset === 'HIGHRISK') {
  6291. if (searchInput) searchInput.value = 'China';
  6292. }
  6293. renderGeoCountries();
  6294. }
  6295. async function toggleGeoCountry(code, enabled) {
  6296. try {
  6297. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6298. method: 'POST',
  6299. headers: { 'Content-Type': 'application/json' },
  6300. body: JSON.stringify({ enabled })
  6301. });
  6302. if (res.ok) {
  6303. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6304. loadGeoIP();
  6305. } else {
  6306. const err = await res.json();
  6307. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6308. }
  6309. } catch (err) {
  6310. showToast('Error', err.message, 'error');
  6311. }
  6312. }
  6313. async function updateGeoCountry(code) {
  6314. try {
  6315. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6316. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6317. if (res.ok) {
  6318. const data = await res.json();
  6319. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6320. loadGeoIP();
  6321. } else {
  6322. const err = await res.json();
  6323. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6324. }
  6325. } catch (err) {
  6326. showToast('Error', err.message, 'error');
  6327. }
  6328. }
  6329. async function triggerGeoUpdateNow() {
  6330. const spinner = document.getElementById('geo-update-spinner');
  6331. if (spinner) spinner.classList.remove('hidden');
  6332. try {
  6333. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6334. if (res.ok) {
  6335. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6336. setTimeout(() => {
  6337. loadGeoIP();
  6338. if (spinner) spinner.classList.add('hidden');
  6339. }, 2500);
  6340. } else {
  6341. const err = await res.json();
  6342. showToast('Notice', err.message || 'Update in progress', 'info');
  6343. if (spinner) spinner.classList.add('hidden');
  6344. }
  6345. } catch (err) {
  6346. showToast('Error', err.message, 'error');
  6347. if (spinner) spinner.classList.add('hidden');
  6348. }
  6349. }
  6350. async function applyGeoPreset(preset) {
  6351. try {
  6352. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6353. method: 'POST',
  6354. headers: { 'Content-Type': 'application/json' },
  6355. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6356. });
  6357. if (res.ok) {
  6358. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6359. loadGeoIP();
  6360. }
  6361. } catch (err) {
  6362. showToast('Error', err.message, 'error');
  6363. }
  6364. }
  6365. function openGeoIntervalModal() {
  6366. const s = state.geoStatus || {};
  6367. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6368. const sel = document.getElementById('geo-cfg-interval');
  6369. const customBox = document.getElementById('geo-cfg-custom-box');
  6370. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6371. const curHours = s.interval_hours || 24;
  6372. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6373. if (matchOption) {
  6374. sel.value = String(curHours);
  6375. customBox.classList.add('hidden');
  6376. } else {
  6377. sel.value = 'custom';
  6378. customHoursInput.value = curHours;
  6379. customBox.classList.remove('hidden');
  6380. }
  6381. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6382. }
  6383. function closeGeoIntervalModal() {
  6384. document.getElementById('geo-interval-modal').classList.add('hidden');
  6385. }
  6386. function toggleCustomGeoInterval() {
  6387. const val = document.getElementById('geo-cfg-interval').value;
  6388. const customBox = document.getElementById('geo-cfg-custom-box');
  6389. if (val === 'custom') {
  6390. customBox.classList.remove('hidden');
  6391. } else {
  6392. customBox.classList.add('hidden');
  6393. }
  6394. }
  6395. async function submitGeoIntervalSettings(e) {
  6396. e.preventDefault();
  6397. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6398. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6399. let hours = 24;
  6400. if (intervalVal === 'custom') {
  6401. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6402. } else {
  6403. hours = parseInt(intervalVal, 10) || 24;
  6404. }
  6405. try {
  6406. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6407. method: 'POST',
  6408. headers: { 'Content-Type': 'application/json' },
  6409. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6410. });
  6411. if (res.ok) {
  6412. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6413. closeGeoIntervalModal();
  6414. loadGeoIP();
  6415. } else {
  6416. const err = await res.json();
  6417. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6418. }
  6419. } catch (err) {
  6420. showToast('Error', err.message, 'error');
  6421. }
  6422. }
  6423. async function viewGeoSubnets(code, name) {
  6424. if (!name) {
  6425. const found = (state.geoCountries || []).find(x => x.code === code);
  6426. name = found ? found.name : code;
  6427. }
  6428. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6429. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6430. const listEl = document.getElementById('geo-subnets-list');
  6431. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6432. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6433. try {
  6434. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6435. if (res.ok) {
  6436. const data = await res.json();
  6437. const subnets = data.subnets || [];
  6438. if (subnets.length === 0) {
  6439. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6440. } else {
  6441. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6442. }
  6443. } else {
  6444. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6445. }
  6446. } catch (err) {
  6447. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6448. }
  6449. }
  6450. function closeGeoSubnetsModal() {
  6451. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6452. }
  6453. // ----------------- Active Connections Tracking -----------------
  6454. async function loadConnections() {
  6455. try {
  6456. const res = await fetch(`${API_BASE}/firewall/connections`);
  6457. const data = await res.json();
  6458. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6459. state.connections = Array.isArray(data) ? data : [];
  6460. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6461. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6462. renderConnections();
  6463. } catch (err) {
  6464. console.error('Failed to load connections:', err);
  6465. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6466. }
  6467. }
  6468. function renderConnections() {
  6469. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6470. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6471. const tbody = document.getElementById('conns-table-body');
  6472. const empty = document.getElementById('conns-empty');
  6473. if (!tbody) return;
  6474. tbody.innerHTML = '';
  6475. const conns = (state.connections || []).filter(c => {
  6476. if (protoFilter && c.protocol !== protoFilter) return false;
  6477. if (search) {
  6478. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6479. if (!line.includes(search)) return false;
  6480. }
  6481. return true;
  6482. });
  6483. if (conns.length === 0) {
  6484. empty?.classList.remove('hidden');
  6485. return;
  6486. }
  6487. empty?.classList.add('hidden');
  6488. conns.slice(0, 150).forEach(c => {
  6489. const tr = document.createElement('tr');
  6490. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6491. let stateColor = 'text-slate-400';
  6492. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6493. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6494. tr.innerHTML = `
  6495. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6496. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6497. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6498. <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>
  6499. <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>
  6500. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6501. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6502. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6503. <td class="py-2.5 px-3 text-right font-sans">
  6504. ${['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>` : ''}
  6505. </td>
  6506. `;
  6507. tbody.appendChild(tr);
  6508. });
  6509. }
  6510. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6511. try {
  6512. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6513. method: 'POST',
  6514. headers: { 'Content-Type': 'application/json' },
  6515. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6516. });
  6517. if (res.ok) {
  6518. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6519. loadConnections();
  6520. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6521. } catch (err) {
  6522. showToast('Error', err.message, 'error');
  6523. }
  6524. }
  6525. async function resetFirewallCounters() {
  6526. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6527. try {
  6528. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6529. if (res.ok) {
  6530. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6531. loadFirewall(false);
  6532. }
  6533. } catch (err) {
  6534. showToast('Error', err.message, 'error');
  6535. }
  6536. }
  6537. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6538. function switchRoutesSubTab(tab) {
  6539. state.routesSubTab = tab;
  6540. const tabs = ['routes', 'rules', 'tables'];
  6541. tabs.forEach(t => {
  6542. const panel = document.getElementById(`routes-subtab-${t}`);
  6543. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6544. if (panel) {
  6545. if (t === tab) panel.classList.remove('hidden');
  6546. else panel.classList.add('hidden');
  6547. }
  6548. if (btn) {
  6549. if (t === tab) {
  6550. 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';
  6551. } else {
  6552. 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';
  6553. }
  6554. }
  6555. });
  6556. setTimeout(initTableSorting, 50);
  6557. }
  6558. async function loadRoutes() {
  6559. try {
  6560. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6561. fetch(`${API_BASE}/routes`),
  6562. fetch(`${API_BASE}/routing/rules`),
  6563. fetch(`${API_BASE}/routing/tables`)
  6564. ]);
  6565. if (routesRes.ok) state.routes = await routesRes.json();
  6566. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6567. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6568. const bRoutes = document.getElementById('routes-badge-routes');
  6569. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6570. const showSystem = document.getElementById('prule-show-system')?.checked;
  6571. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6572. const bRules = document.getElementById('routes-badge-rules');
  6573. if (bRules) bRules.innerText = userRules.length;
  6574. const bTables = document.getElementById('routes-badge-tables');
  6575. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6576. const bRoutesCount = document.getElementById('badge-routes-count');
  6577. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6578. renderRoutesList();
  6579. renderPolicyRules();
  6580. renderRoutingTables();
  6581. } catch (err) {
  6582. console.error('Failed to load routing:', err);
  6583. }
  6584. }
  6585. function getRouteProtocolBadge(proto) {
  6586. const p = (proto || 'static').toLowerCase();
  6587. switch (p) {
  6588. case 'bgp':
  6589. 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>`;
  6590. case 'ibgp':
  6591. 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>`;
  6592. case 'ospf':
  6593. 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>`;
  6594. case 'rip':
  6595. 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>`;
  6596. case 'static':
  6597. 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>`;
  6598. case 'connected':
  6599. 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>`;
  6600. case 'dhcp':
  6601. 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>`;
  6602. case 'multicast':
  6603. 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>`;
  6604. default:
  6605. 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>`;
  6606. }
  6607. }
  6608. function renderRoutesList() {
  6609. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6610. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6611. const tbody = document.getElementById('routes-table-body');
  6612. const empty = document.getElementById('routes-empty');
  6613. if (!tbody) return;
  6614. // Update table filter select
  6615. const sel = document.getElementById('routes-filter-table');
  6616. if (sel) {
  6617. const cur = sel.value;
  6618. sel.innerHTML = '<option value="">All Tables</option>';
  6619. (state.routingTables || []).forEach(t => {
  6620. const opt = document.createElement('option');
  6621. opt.value = t.name;
  6622. opt.innerText = t.name;
  6623. if (t.name === cur) opt.selected = true;
  6624. sel.appendChild(opt);
  6625. });
  6626. }
  6627. const routes = (state.routes || []).filter(r => {
  6628. if (tableFilter && r.routing_table !== tableFilter) return false;
  6629. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6630. if (typeFilter === 'multicast' && !r.multicast) return false;
  6631. if (typeFilter === 'static' && !r.static) return false;
  6632. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6633. if (typeFilter === 'connected' && !r.connect) return false;
  6634. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6635. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6636. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6637. return true;
  6638. });
  6639. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6640. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6641. let summaryText = `${routes.length} Routes`;
  6642. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6643. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6644. const badgeEl = document.getElementById('routes-count-badge');
  6645. if (badgeEl) badgeEl.innerText = summaryText;
  6646. if (routes.length === 0) {
  6647. empty?.classList.remove('hidden');
  6648. tbody.innerHTML = '';
  6649. return;
  6650. }
  6651. empty?.classList.add('hidden');
  6652. 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(';');
  6653. if (tbody.dataset.sig === sig) {
  6654. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6655. }
  6656. tbody.dataset.sig = sig;
  6657. tbody.innerHTML = '';
  6658. routes.forEach(r => {
  6659. const tr = document.createElement('tr');
  6660. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6661. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6662. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6663. let flags = '';
  6664. if (r.dynamic) flags += 'D';
  6665. if (r.active) flags += 'A';
  6666. if (r.connect) flags += 'C';
  6667. if (r.static) flags += 'S';
  6668. if (r.ecmp) flags += 'E';
  6669. if (r.multicast) flags += 'M';
  6670. if (r.disabled) flags += 'X';
  6671. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6672. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6673. if (r.check_gateway === 'internet') {
  6674. if (r.health_status === 'online') {
  6675. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6676. healthCell = `
  6677. <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)">
  6678. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6679. <span>Internet OK (${ms}ms)</span>
  6680. </span>
  6681. `;
  6682. } else if (r.health_status === 'offline') {
  6683. healthCell = `
  6684. <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.">
  6685. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6686. <span>Internet Down</span>
  6687. </span>
  6688. `;
  6689. } else {
  6690. healthCell = `
  6691. <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">
  6692. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6693. <span>Checking...</span>
  6694. </span>
  6695. `;
  6696. }
  6697. } else if (r.check_gateway === 'ping') {
  6698. if (r.health_status === 'online') {
  6699. healthCell = `
  6700. <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">
  6701. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6702. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6703. </span>
  6704. `;
  6705. } else if (r.health_status === 'offline') {
  6706. healthCell = `
  6707. <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">
  6708. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6709. <span>Gateway Dead</span>
  6710. </span>
  6711. `;
  6712. }
  6713. }
  6714. const flagDescriptions = [];
  6715. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6716. if (r.active) flagDescriptions.push('Active (A)');
  6717. if (r.connect) flagDescriptions.push('Connected (C)');
  6718. if (r.static) flagDescriptions.push('Static (S)');
  6719. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6720. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6721. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6722. tr.innerHTML = `
  6723. <td class="py-2.5 px-3 text-center">
  6724. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6725. 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')
  6726. }" title="Flags: ${flagDescriptions.join(', ')}">
  6727. ${flags || '-'}
  6728. </span>
  6729. </td>
  6730. <td class="py-2.5 px-3">
  6731. <div class="flex items-center gap-1.5 flex-wrap">
  6732. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6733. ${r.ecmp ? `
  6734. <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)">
  6735. <span>⚡ ECMP</span>
  6736. </span>
  6737. ` : ''}
  6738. ${r.multicast ? `
  6739. <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">
  6740. <span>IGMP</span>
  6741. </span>
  6742. ` : ''}
  6743. </div>
  6744. </td>
  6745. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6746. <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>
  6747. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6748. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6749. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6750. <td class="py-2.5 px-3">${healthCell}</td>
  6751. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6752. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6753. ${r.static ? `
  6754. <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>
  6755. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6756. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6757. ` : `
  6758. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6759. `}
  6760. </td>
  6761. `;
  6762. tbody.appendChild(tr);
  6763. });
  6764. }
  6765. function openAddRouteModal() {
  6766. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6767. document.getElementById('route-modal-id').value = '';
  6768. document.getElementById('route-modal-old-dst').value = '';
  6769. document.getElementById('route-modal-old-gw').value = '';
  6770. document.getElementById('route-modal-old-distance').value = '';
  6771. document.getElementById('route-modal-old-table').value = '';
  6772. document.getElementById('route-modal-old-iface').value = '';
  6773. const dstInput = document.getElementById('route-modal-dst');
  6774. const gwInput = document.getElementById('route-modal-gw');
  6775. const distInput = document.getElementById('route-modal-distance');
  6776. const ifaceSelect = document.getElementById('route-modal-iface');
  6777. const tableSelect = document.getElementById('route-modal-table');
  6778. const commentInput = document.getElementById('route-modal-comment');
  6779. const disCheck = document.getElementById('route-modal-disabled');
  6780. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6781. dstInput.disabled = false;
  6782. dstInput.value = '0.0.0.0/0';
  6783. gwInput.disabled = false;
  6784. gwInput.value = '';
  6785. distInput.disabled = false;
  6786. distInput.value = '1';
  6787. ifaceSelect.disabled = false;
  6788. tableSelect.disabled = false;
  6789. commentInput.disabled = false;
  6790. commentInput.value = '';
  6791. disCheck.disabled = false;
  6792. disCheck.checked = false;
  6793. if (saveBtn) saveBtn.classList.remove('hidden');
  6794. const checkGw = document.getElementById('route-modal-check-gw');
  6795. if (checkGw) checkGw.value = 'internet';
  6796. const checkTarget = document.getElementById('route-modal-check-target');
  6797. if (checkTarget) checkTarget.value = '1.1.1.1';
  6798. const checkInterval = document.getElementById('route-modal-check-interval');
  6799. if (checkInterval) checkInterval.value = '5';
  6800. const checkThresh = document.getElementById('route-modal-check-threshold');
  6801. if (checkThresh) checkThresh.value = '3';
  6802. toggleRouteCheckModeUI();
  6803. populateInterfaceSelect('route-modal-iface');
  6804. // Populate tables
  6805. tableSelect.innerHTML = '';
  6806. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6807. const opt = document.createElement('option');
  6808. opt.value = t.name;
  6809. opt.innerText = t.name;
  6810. if (t.name === 'main') opt.selected = true;
  6811. tableSelect.appendChild(opt);
  6812. });
  6813. document.getElementById('route-modal').classList.remove('hidden');
  6814. }
  6815. function openEditRouteModal(id) {
  6816. const r = (state.routes || []).find(route => route.id === id);
  6817. if (!r) return;
  6818. const isStatic = !!r.static;
  6819. document.getElementById('route-modal-title').innerText = isStatic
  6820. ? `Edit Route: ${r.dst_address}`
  6821. : `Route Properties (Read Only): ${r.dst_address}`;
  6822. document.getElementById('route-modal-id').value = r.id;
  6823. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6824. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6825. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6826. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6827. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6828. const dstInput = document.getElementById('route-modal-dst');
  6829. const gwInput = document.getElementById('route-modal-gw');
  6830. const distInput = document.getElementById('route-modal-distance');
  6831. const ifaceSelect = document.getElementById('route-modal-iface');
  6832. const tableSelect = document.getElementById('route-modal-table');
  6833. const commentInput = document.getElementById('route-modal-comment');
  6834. const disCheck = document.getElementById('route-modal-disabled');
  6835. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6836. dstInput.value = r.dst_address;
  6837. gwInput.value = r.gateway || '';
  6838. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6839. commentInput.value = r.comment || '';
  6840. disCheck.checked = !!r.disabled;
  6841. const checkGw = document.getElementById('route-modal-check-gw');
  6842. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6843. const checkTarget = document.getElementById('route-modal-check-target');
  6844. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6845. const checkInterval = document.getElementById('route-modal-check-interval');
  6846. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6847. const checkThresh = document.getElementById('route-modal-check-threshold');
  6848. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6849. toggleRouteCheckModeUI();
  6850. dstInput.disabled = !isStatic;
  6851. gwInput.disabled = !isStatic;
  6852. distInput.disabled = !isStatic;
  6853. ifaceSelect.disabled = !isStatic;
  6854. tableSelect.disabled = !isStatic;
  6855. commentInput.disabled = !isStatic;
  6856. disCheck.disabled = !isStatic;
  6857. if (checkGw) checkGw.disabled = !isStatic;
  6858. if (checkTarget) checkTarget.disabled = !isStatic;
  6859. if (checkInterval) checkInterval.disabled = !isStatic;
  6860. if (checkThresh) checkThresh.disabled = !isStatic;
  6861. if (saveBtn) {
  6862. if (isStatic) {
  6863. saveBtn.classList.remove('hidden');
  6864. } else {
  6865. saveBtn.classList.add('hidden');
  6866. }
  6867. }
  6868. populateInterfaceSelect('route-modal-iface', r.interface);
  6869. tableSelect.innerHTML = '';
  6870. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6871. const opt = document.createElement('option');
  6872. opt.value = t.name;
  6873. opt.innerText = t.name;
  6874. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6875. tableSelect.appendChild(opt);
  6876. });
  6877. document.getElementById('route-modal').classList.remove('hidden');
  6878. }
  6879. function closeRouteModal() {
  6880. document.getElementById('route-modal').classList.add('hidden');
  6881. }
  6882. function setRouteCheckTarget(ip) {
  6883. const inp = document.getElementById('route-modal-check-target');
  6884. if (inp) inp.value = ip;
  6885. }
  6886. function toggleRouteCheckModeUI() {
  6887. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6888. const targetRow = document.getElementById('route-row-check-target');
  6889. const paramsRow = document.getElementById('route-row-check-params');
  6890. if (mode === 'none') {
  6891. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6892. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6893. } else if (mode === 'ping') {
  6894. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6895. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6896. } else { // internet
  6897. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6898. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6899. }
  6900. }
  6901. async function submitSaveRoute(e) {
  6902. e.preventDefault();
  6903. const id = document.getElementById('route-modal-id').value;
  6904. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6905. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6906. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6907. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6908. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6909. const dst = document.getElementById('route-modal-dst').value.trim();
  6910. const gw = document.getElementById('route-modal-gw').value.trim();
  6911. const table = document.getElementById('route-modal-table').value;
  6912. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6913. const iface = document.getElementById('route-modal-iface').value;
  6914. const comment = document.getElementById('route-modal-comment').value.trim();
  6915. const disabled = document.getElementById('route-modal-disabled').checked;
  6916. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6917. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6918. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6919. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6920. if (!dst) {
  6921. showToast('Error', 'Destination address is required', 'error');
  6922. return;
  6923. }
  6924. if (!gw && !iface) {
  6925. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6926. return;
  6927. }
  6928. const payload = {
  6929. id,
  6930. old_dst_address: oldDst,
  6931. old_gateway: oldGw,
  6932. old_routing_table: oldTable,
  6933. old_interface: oldIface,
  6934. dst_address: dst,
  6935. gateway: gw || iface,
  6936. routing_table: table,
  6937. distance,
  6938. interface: iface,
  6939. comment,
  6940. disabled,
  6941. check_gateway,
  6942. check_target,
  6943. check_interval,
  6944. check_threshold
  6945. };
  6946. if (oldDistStr !== undefined && oldDistStr !== '') {
  6947. payload.old_distance = parseInt(oldDistStr, 10);
  6948. }
  6949. try {
  6950. const res = await fetch(`${API_BASE}/routes`, {
  6951. method: 'POST',
  6952. headers: { 'Content-Type': 'application/json' },
  6953. body: JSON.stringify(payload)
  6954. });
  6955. if (res.ok) {
  6956. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6957. closeRouteModal();
  6958. loadRoutes();
  6959. } else {
  6960. const err = await res.json();
  6961. showToast('Error', err.message || 'Failed to save route', 'error');
  6962. }
  6963. } catch (err) {
  6964. showToast('Error', err.message, 'error');
  6965. }
  6966. }
  6967. async function toggleRouteState(id, disabled) {
  6968. try {
  6969. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6970. method: 'POST',
  6971. headers: { 'Content-Type': 'application/json' },
  6972. body: JSON.stringify({ disabled })
  6973. });
  6974. if (res.ok) loadRoutes();
  6975. } catch (err) {
  6976. showToast('Error', err.message, 'error');
  6977. }
  6978. }
  6979. async function deleteRoute(id) {
  6980. if (!confirm('Are you sure you want to delete this route?')) return;
  6981. try {
  6982. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6983. if (res.ok) {
  6984. showToast('Deleted', 'Route removed', 'success');
  6985. loadRoutes();
  6986. }
  6987. } catch (err) {
  6988. showToast('Error', err.message, 'error');
  6989. }
  6990. }
  6991. // ----------------- Policy Rules (/ip route rule) -----------------
  6992. function renderPolicyRules() {
  6993. const tbody = document.getElementById('rules-table-body');
  6994. const empty = document.getElementById('rules-empty');
  6995. if (!tbody) return;
  6996. const showSystem = document.getElementById('prule-show-system')?.checked;
  6997. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6998. const countBadge = document.getElementById('rules-count-badge');
  6999. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7000. const bRules = document.getElementById('routes-badge-rules');
  7001. if (bRules) bRules.innerText = filtered.length;
  7002. if (filtered.length === 0) {
  7003. empty?.classList.remove('hidden');
  7004. tbody.innerHTML = '';
  7005. return;
  7006. }
  7007. empty?.classList.add('hidden');
  7008. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7009. if (tbody.dataset.sig === sig) return;
  7010. tbody.dataset.sig = sig;
  7011. tbody.innerHTML = '';
  7012. filtered.forEach(pr => {
  7013. const isSys = pr.is_default || pr.is_system;
  7014. const tr = document.createElement('tr');
  7015. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7016. tr.innerHTML = `
  7017. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7018. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7019. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7020. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7021. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7022. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7023. <td class="py-2.5 px-3 text-right font-sans">
  7024. ${!pr.is_default ? `
  7025. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7026. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7027. </td>
  7028. `;
  7029. tbody.appendChild(tr);
  7030. });
  7031. }
  7032. function openAddPolicyRuleModal() {
  7033. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7034. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7035. document.getElementById('prule-modal-mark').value = '';
  7036. document.getElementById('prule-modal-src').value = '';
  7037. document.getElementById('prule-modal-dst').value = '';
  7038. const sel = document.getElementById('prule-modal-table');
  7039. sel.innerHTML = '';
  7040. (state.routingTables || []).forEach(t => {
  7041. const opt = document.createElement('option');
  7042. opt.value = t.name;
  7043. opt.innerText = t.name;
  7044. sel.appendChild(opt);
  7045. });
  7046. document.getElementById('prule-modal').classList.remove('hidden');
  7047. }
  7048. function closePolicyRuleModal() {
  7049. document.getElementById('prule-modal').classList.add('hidden');
  7050. }
  7051. async function submitSavePolicyRule(e) {
  7052. e.preventDefault();
  7053. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7054. const mark = document.getElementById('prule-modal-mark').value.trim();
  7055. const src = document.getElementById('prule-modal-src').value.trim();
  7056. const dst = document.getElementById('prule-modal-dst').value.trim();
  7057. const table = document.getElementById('prule-modal-table').value;
  7058. const action = document.getElementById('prule-modal-action').value;
  7059. try {
  7060. const res = await fetch(`${API_BASE}/routing/rules`, {
  7061. method: 'POST',
  7062. headers: { 'Content-Type': 'application/json' },
  7063. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7064. });
  7065. if (res.ok) {
  7066. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7067. closePolicyRuleModal();
  7068. loadRoutes();
  7069. } else {
  7070. const err = await res.json();
  7071. showToast('Error', err.message, 'error');
  7072. }
  7073. } catch (err) {
  7074. showToast('Error', err.message, 'error');
  7075. }
  7076. }
  7077. async function deletePolicyRule(id) {
  7078. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7079. try {
  7080. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7081. if (res.ok) {
  7082. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7083. loadRoutes();
  7084. }
  7085. } catch (err) {
  7086. showToast('Error', err.message, 'error');
  7087. }
  7088. }
  7089. // ----------------- Routing Tables -----------------
  7090. function renderRoutingTables() {
  7091. const tbody = document.getElementById('tables-table-body');
  7092. if (!tbody) return;
  7093. const tables = state.routingTables || [];
  7094. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7095. if (tbody.dataset.sig === sig) return;
  7096. tbody.dataset.sig = sig;
  7097. tbody.innerHTML = '';
  7098. (state.routingTables || []).forEach(t => {
  7099. const tr = document.createElement('tr');
  7100. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7101. tr.innerHTML = `
  7102. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7103. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7104. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7105. `;
  7106. tbody.appendChild(tr);
  7107. });
  7108. }
  7109. function openAddTableModal() {
  7110. document.getElementById('table-modal-name').value = '';
  7111. document.getElementById('table-modal-id').value = '';
  7112. document.getElementById('table-modal-comment').value = '';
  7113. document.getElementById('table-modal').classList.remove('hidden');
  7114. }
  7115. function closeTableModal() {
  7116. document.getElementById('table-modal').classList.add('hidden');
  7117. }
  7118. async function submitSaveTable(e) {
  7119. e.preventDefault();
  7120. const name = document.getElementById('table-modal-name').value.trim();
  7121. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7122. const comment = document.getElementById('table-modal-comment').value.trim();
  7123. try {
  7124. const res = await fetch(`${API_BASE}/routing/tables`, {
  7125. method: 'POST',
  7126. headers: { 'Content-Type': 'application/json' },
  7127. body: JSON.stringify({ name, table_id: id, comment })
  7128. });
  7129. if (res.ok) {
  7130. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7131. closeTableModal();
  7132. loadRoutes();
  7133. } else {
  7134. const err = await res.json();
  7135. showToast('Error', err.message, 'error');
  7136. }
  7137. } catch (err) {
  7138. showToast('Error', err.message, 'error');
  7139. }
  7140. }
  7141. async function loadDebianConfig() {
  7142. const view = document.getElementById('debian-config-view');
  7143. view.innerText = 'Generating live configuration...';
  7144. try {
  7145. const res = await fetch(`${API_BASE}/debian/config`);
  7146. const data = await res.json();
  7147. view.innerText = data.content || '# Empty config';
  7148. } catch (err) {
  7149. view.innerText = 'Failed to generate Debian network config.';
  7150. }
  7151. }
  7152. async function saveDebianConfig() {
  7153. try {
  7154. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7155. const data = await res.json();
  7156. if (res.ok) {
  7157. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7158. loadDebianConfig();
  7159. }
  7160. } catch (err) {
  7161. showToast('Error', err.message, 'error');
  7162. }
  7163. }
  7164. function showToast(title, message, type = 'info') {
  7165. const container = document.getElementById('toast-container');
  7166. const toast = document.createElement('div');
  7167. const borderColors = {
  7168. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7169. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7170. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7171. };
  7172. 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}`;
  7173. toast.innerHTML = `
  7174. <div class="flex-1">
  7175. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7176. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7177. </div>
  7178. `;
  7179. container.appendChild(toast);
  7180. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7181. setTimeout(() => {
  7182. toast.classList.add('opacity-0', 'translate-y-2');
  7183. setTimeout(() => toast.remove(), 300);
  7184. }, 4000);
  7185. }
  7186. function formatTraffic(bytesPerSec) {
  7187. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7188. const kb = bytesPerSec / 1024;
  7189. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7190. const mb = kb / 1024;
  7191. return `${mb.toFixed(2)} MB/s`;
  7192. }
  7193. function toggleSidebar() {
  7194. const sb = document.getElementById('sidebar');
  7195. sb.classList.toggle('-translate-x-full');
  7196. }
  7197. // ======================== EoIP (Ethernet over IP) ========================
  7198. async function loadEoIP(populate = true) {
  7199. try {
  7200. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7201. const data = await res.json();
  7202. state.eoipTunnels = Array.isArray(data) ? data : [];
  7203. const badge = document.getElementById('eoip-count-badge');
  7204. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7205. const sideBadge = document.getElementById('badge-eoip-count');
  7206. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7207. renderEoIPTunnels();
  7208. } catch (err) {
  7209. console.error('Failed to load EoIP:', err);
  7210. }
  7211. }
  7212. function renderEoIPTunnels() {
  7213. const tbody = document.getElementById('eoip-table-body');
  7214. const empty = document.getElementById('eoip-empty');
  7215. if (!tbody) return;
  7216. tbody.innerHTML = '';
  7217. const tunnels = state.eoipTunnels || [];
  7218. if (tunnels.length === 0) {
  7219. empty?.classList.remove('hidden');
  7220. return;
  7221. }
  7222. empty?.classList.add('hidden');
  7223. tunnels.forEach(t => {
  7224. const tr = document.createElement('tr');
  7225. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7226. tr.innerHTML = `
  7227. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7228. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7229. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7230. <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>
  7231. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7232. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7233. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7234. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7235. <td class="py-2.5 px-3 font-mono text-[11px]">
  7236. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7237. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7238. </td>
  7239. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7240. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7241. <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>
  7242. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7243. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7244. </td>
  7245. `;
  7246. tbody.appendChild(tr);
  7247. });
  7248. }
  7249. function openAddEoIPModal() {
  7250. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7251. document.getElementById('eoip-modal-id').value = '';
  7252. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7253. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7254. document.getElementById('eoip-modal-remote').value = '';
  7255. document.getElementById('eoip-modal-ip').value = '';
  7256. document.getElementById('eoip-modal-local').value = '';
  7257. document.getElementById('eoip-modal-mac').value = '';
  7258. document.getElementById('eoip-modal-mtu').value = '1500';
  7259. document.getElementById('eoip-modal-comment').value = '';
  7260. document.getElementById('eoip-modal-clampmss').checked = true;
  7261. document.getElementById('eoip-modal-disabled').checked = false;
  7262. document.getElementById('eoip-modal').classList.remove('hidden');
  7263. }
  7264. function openEditEoIPModal(id) {
  7265. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7266. if (!t) return;
  7267. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7268. document.getElementById('eoip-modal-id').value = t.id;
  7269. document.getElementById('eoip-modal-name').value = t.name;
  7270. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7271. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7272. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7273. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7274. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7275. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7276. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7277. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7278. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7279. document.getElementById('eoip-modal').classList.remove('hidden');
  7280. }
  7281. function closeEoIPModal() {
  7282. document.getElementById('eoip-modal').classList.add('hidden');
  7283. }
  7284. async function submitSaveEoIP(e) {
  7285. e.preventDefault();
  7286. const id = document.getElementById('eoip-modal-id').value;
  7287. const name = document.getElementById('eoip-modal-name').value.trim();
  7288. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7289. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7290. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7291. const local = document.getElementById('eoip-modal-local').value.trim();
  7292. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7293. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7294. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7295. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7296. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7297. try {
  7298. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7299. method: 'POST',
  7300. headers: { 'Content-Type': 'application/json' },
  7301. body: JSON.stringify({
  7302. id,
  7303. name,
  7304. tunnel_id: tunnelId,
  7305. remote_address: remote,
  7306. ip_address: ipAddress,
  7307. local_address: local,
  7308. mac_address: mac,
  7309. mtu,
  7310. clamp_mss: clampMss,
  7311. comment,
  7312. disabled
  7313. })
  7314. });
  7315. if (res.ok) {
  7316. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7317. closeEoIPModal();
  7318. loadEoIP(false);
  7319. fetchData(false);
  7320. } else {
  7321. const err = await res.json();
  7322. showToast('Error', err.message, 'error');
  7323. }
  7324. } catch (err) {
  7325. showToast('Error', err.message, 'error');
  7326. }
  7327. }
  7328. async function toggleEoIPState(id, disabled) {
  7329. try {
  7330. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7331. method: 'POST',
  7332. headers: { 'Content-Type': 'application/json' },
  7333. body: JSON.stringify({ disabled })
  7334. });
  7335. if (res.ok) {
  7336. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7337. loadEoIP(false);
  7338. fetchData(false);
  7339. }
  7340. } catch (err) {
  7341. showToast('Error', err.message, 'error');
  7342. }
  7343. }
  7344. async function deleteEoIP(id) {
  7345. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7346. try {
  7347. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7348. if (res.ok) {
  7349. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7350. loadEoIP(false);
  7351. fetchData(false);
  7352. }
  7353. } catch (err) {
  7354. showToast('Error', err.message, 'error');
  7355. }
  7356. }
  7357. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7358. const aeroRateSamples = new Map();
  7359. const aeroLiveRates = new Map();
  7360. async function loadAeroTUN(populate = true) {
  7361. try {
  7362. const [tunnelsRes, statsRes] = await Promise.all([
  7363. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7364. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7365. ]);
  7366. if (tunnelsRes.ok) {
  7367. const data = await tunnelsRes.json();
  7368. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7369. const now = Date.now();
  7370. for (const t of state.aerotunTunnels) {
  7371. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7372. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7373. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7374. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7375. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7376. }
  7377. }
  7378. if (statsRes.ok) {
  7379. state.aerotunStats = await statsRes.json();
  7380. }
  7381. const countBadge = document.getElementById('aerotun-count-badge');
  7382. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7383. const sideBadge = document.getElementById('badge-aerotun-count');
  7384. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7385. renderAeroTUN();
  7386. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7387. } catch (err) {
  7388. console.error('Failed to load AeroTUN:', err);
  7389. }
  7390. }
  7391. function renderAeroTUN() {
  7392. const tbody = document.getElementById('aerotun-table-body');
  7393. const empty = document.getElementById('aerotun-empty');
  7394. // Update summary cards
  7395. const stats = state.aerotunStats || {};
  7396. const tunnels = state.aerotunTunnels || [];
  7397. const statActive = document.getElementById('aerotun-stat-active');
  7398. if (statActive) {
  7399. const activeCount = tunnels.filter(t => t.connected).length;
  7400. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7401. }
  7402. const statSaved = document.getElementById('aerotun-stat-saved');
  7403. if (statSaved) {
  7404. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7405. }
  7406. const statRatio = document.getElementById('aerotun-stat-ratio');
  7407. if (statRatio) {
  7408. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7409. }
  7410. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7411. if (statTraffic) {
  7412. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7413. }
  7414. if (!tbody) return;
  7415. tbody.innerHTML = '';
  7416. if (tunnels.length === 0) {
  7417. empty?.classList.remove('hidden');
  7418. return;
  7419. }
  7420. empty?.classList.add('hidden');
  7421. tunnels.forEach(t => {
  7422. const tr = document.createElement('tr');
  7423. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7424. const modeBadge = t.mode === 'server'
  7425. ? `<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>`
  7426. : `<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>`;
  7427. const endpointInfo = t.mode === 'server'
  7428. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7429. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7430. const compBadge = t.compression
  7431. ? `<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>`
  7432. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7433. const activePeer = t.connected && t.active_peer_endpoint
  7434. ? `<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>`
  7435. : `<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>`;
  7436. const rawRx = formatBytes(t.rx_bytes || 0);
  7437. const rawTx = formatBytes(t.tx_bytes || 0);
  7438. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7439. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7440. const rate = aeroLiveRates.get(t.id);
  7441. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7442. tr.innerHTML = `
  7443. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7444. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7445. <span>${escapeHtml(t.name)}</span>
  7446. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7447. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7448. </td>
  7449. <td class="py-2.5 px-3">${modeBadge}</td>
  7450. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7451. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7452. <td class="py-2.5 px-3">${compBadge}</td>
  7453. <td class="py-2.5 px-3">${activePeer}</td>
  7454. <td class="py-2.5 px-3 font-mono text-[11px]">
  7455. <span class="text-emerald-400">↓ ${rawRx}</span>
  7456. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7457. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7458. </td>
  7459. <td class="py-2.5 px-3 font-mono text-[11px]">
  7460. <span class="text-slate-400">↓ ${wireRx}</span>
  7461. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7462. </td>
  7463. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7464. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7465. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7466. ${t.running
  7467. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7468. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7469. }
  7470. <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>
  7471. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7472. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7473. </td>
  7474. `;
  7475. tbody.appendChild(tr);
  7476. });
  7477. }
  7478. async function openAeroTUNHealth(encodedID) {
  7479. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7480. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7481. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7482. document.getElementById('aerotun-compare-host').value=underlay;
  7483. document.getElementById('aerotun-compare-result').textContent='';
  7484. document.getElementById('aerotun-health-result').textContent = '';
  7485. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7486. await refreshAeroTUNHealth();
  7487. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7488. }
  7489. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7490. async function refreshAeroTUNHealth() {
  7491. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7492. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7493. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7494. try {
  7495. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7496. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7497. const d=t.drop_breakdown;
  7498. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7499. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7500. if(!events.length){node.textContent='No events recorded yet.';return}
  7501. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7502. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7503. }
  7504. async function runAeroTUNHealthCheck() {
  7505. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7506. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7507. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7508. finally {button.disabled=false}
  7509. }
  7510. let aeroCompareRunning=false, aeroCompareCancel=false;
  7511. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7512. async function runAeroTUNComparison() {
  7513. if(aeroCompareRunning)return;
  7514. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7515. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7516. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7517. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7518. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7519. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7520. const results=[];
  7521. try {
  7522. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7523. if(aeroCompareCancel)break;
  7524. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7525. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7526. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7527. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7528. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7529. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7530. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7531. }
  7532. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7533. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7534. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7535. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7536. }
  7537. let aeroModalGeneration = 0;
  7538. let aeroIdentityDraft = '';
  7539. let aeroSaving = false;
  7540. let aeroPSKRequest = 0;
  7541. function discardAeroIdentityDraft(id) {
  7542. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7543. }
  7544. async function generateAeroTUNIdentity() {
  7545. const generation = aeroModalGeneration;
  7546. const retry = document.getElementById('aerotun-retry-identity');
  7547. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7548. retry.classList.add('hidden');
  7549. document.getElementById('aerotun-modal-public').value = '';
  7550. try {
  7551. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7552. if (!res.ok) throw new Error(await responseError(res));
  7553. const draft = await res.json();
  7554. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7555. aeroIdentityDraft = draft.draft_id;
  7556. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7557. updateAeroTUNSetupHint();
  7558. } catch (err) {
  7559. if (generation !== aeroModalGeneration) return;
  7560. retry.classList.remove('hidden');
  7561. updateAeroTUNSetupHint();
  7562. showToast('Identity Generation Failed', err.message, 'error');
  7563. }
  7564. }
  7565. function onAeroTUNModeChange() {
  7566. const mode = document.getElementById('aerotun-modal-mode').value;
  7567. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7568. const portInput = document.getElementById('aerotun-modal-port');
  7569. if (mode === 'server') {
  7570. if (!portInput.value) portInput.value = '51830';
  7571. endpointInput.placeholder = 'Optional / learned roaming peer';
  7572. } else {
  7573. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7574. if (!portInput.value) portInput.value = '';
  7575. }
  7576. }
  7577. function onAeroTUNPeerChange() {
  7578. const peer = document.getElementById('aerotun-modal-peer');
  7579. const allowed = document.getElementById('aerotun-modal-allowed');
  7580. const previous = peer.dataset.allowedDefault || '';
  7581. const host = peer.value.trim().split('/')[0];
  7582. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7583. if (allowed.value.trim() === previous) allowed.value = next;
  7584. peer.dataset.allowedDefault = next;
  7585. }
  7586. async function generateAeroTUNKey(automatic = false) {
  7587. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7588. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7589. try {
  7590. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7591. if (!res.ok) throw new Error(await responseError(res));
  7592. const data = await res.json();
  7593. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7594. input.value = data.key;
  7595. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7596. } catch (err) {
  7597. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7598. }
  7599. }
  7600. function updateAeroTUNSetupHint() {
  7601. const version = document.getElementById('aerotun-modal-protocol').value;
  7602. const key = document.getElementById('aerotun-modal-public').value;
  7603. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7604. const hint = document.getElementById('aerotun-setup-hint');
  7605. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7606. if (!hint) return;
  7607. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7608. }
  7609. async function copyAeroTUNPublicKey() {
  7610. const input = document.getElementById('aerotun-modal-public');
  7611. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7612. try {
  7613. await navigator.clipboard.writeText(input.value);
  7614. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7615. } catch {
  7616. input.focus(); input.select();
  7617. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7618. }
  7619. }
  7620. async function copyAeroTUNPSK() {
  7621. const input = document.getElementById('aerotun-modal-psk');
  7622. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7623. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7624. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7625. }
  7626. function openAddAeroTUNModal() {
  7627. if (aeroSaving) return;
  7628. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7629. const tunnels = state.aerotunTunnels || [];
  7630. const usedNames = new Set(tunnels.map(t => t.name));
  7631. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7632. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  7633. if (index >= 256) index = 0;
  7634. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7635. document.getElementById('aerotun-modal-id').value = '';
  7636. document.getElementById('aerotun-modal-protocol').value='3';
  7637. document.getElementById('aerotun-modal-public').value='';
  7638. document.getElementById('aerotun-modal-peerkey').value='';
  7639. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7640. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7641. document.getElementById('aerotun-modal-mode').value = 'server';
  7642. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7643. document.getElementById('aerotun-modal-endpoint').value = '';
  7644. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7645. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7646. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7647. document.getElementById('aerotun-modal-psk').value = '';
  7648. document.getElementById('aerotun-modal-mtu').value = '1420';
  7649. document.getElementById('aerotun-modal-comment').value = '';
  7650. document.getElementById('aerotun-modal-compression').checked = false;
  7651. document.getElementById('aerotun-modal-defroute').checked = false;
  7652. document.getElementById('aerotun-modal-disabled').checked = true;
  7653. document.getElementById('aerotun-modal-psk').type = 'password';
  7654. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  7655. onAeroTUNModeChange();
  7656. updateAeroTUNSetupHint();
  7657. document.getElementById('aerotun-modal').classList.remove('hidden');
  7658. generateAeroTUNKey(true);
  7659. generateAeroTUNIdentity();
  7660. }
  7661. function openEditAeroTUNModal(id) {
  7662. if (aeroSaving) return;
  7663. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7664. if (!t) return;
  7665. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7666. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  7667. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7668. document.getElementById('aerotun-modal-id').value = t.id;
  7669. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7670. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7671. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7672. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7673. document.getElementById('aerotun-modal-name').value = t.name;
  7674. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7675. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7676. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7677. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7678. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7679. const peerHost = (t.peer_address || '').split('/')[0];
  7680. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  7681. document.getElementById('aerotun-modal-psk').value = '';
  7682. document.getElementById('aerotun-modal-psk').type = 'password';
  7683. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7684. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  7685. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7686. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7687. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7688. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7689. onAeroTUNModeChange();
  7690. updateAeroTUNSetupHint();
  7691. document.getElementById('aerotun-modal').classList.remove('hidden');
  7692. }
  7693. function closeAeroTUNModal() {
  7694. if (aeroSaving) return;
  7695. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7696. document.getElementById('aerotun-modal-psk').value = '';
  7697. document.getElementById('aerotun-modal').classList.add('hidden');
  7698. }
  7699. async function submitSaveAeroTUN(e) {
  7700. e.preventDefault();
  7701. if (aeroSaving) return;
  7702. const id = document.getElementById('aerotun-modal-id').value;
  7703. const name = document.getElementById('aerotun-modal-name').value.trim();
  7704. const mode = document.getElementById('aerotun-modal-mode').value;
  7705. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7706. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7707. const local = document.getElementById('aerotun-modal-local').value.trim();
  7708. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7709. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7710. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  7711. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  7712. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7713. const compression = document.getElementById('aerotun-modal-compression').checked;
  7714. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7715. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7716. if (mode === 'client' && !endpoint) {
  7717. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7718. return;
  7719. }
  7720. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  7721. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  7722. return;
  7723. }
  7724. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  7725. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  7726. return;
  7727. }
  7728. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7729. if (version === 3 && !id && !aeroIdentityDraft) {
  7730. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  7731. return;
  7732. }
  7733. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  7734. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  7735. document.getElementById('aerotun-modal-allowed').focus();
  7736. return;
  7737. }
  7738. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7739. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  7740. return;
  7741. }
  7742. if (!psk && !id) {
  7743. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7744. return;
  7745. }
  7746. aeroSaving = true;
  7747. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  7748. if (submit) submit.disabled = true;
  7749. try {
  7750. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7751. method: 'POST',
  7752. headers: { 'Content-Type': 'application/json' },
  7753. body: JSON.stringify({
  7754. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7755. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  7756. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7757. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7758. id,
  7759. name,
  7760. mode,
  7761. listen_port: port,
  7762. remote_endpoint: endpoint,
  7763. local_address: local,
  7764. peer_address: peer,
  7765. psk,
  7766. mtu,
  7767. compression,
  7768. default_route: defaultRoute,
  7769. comment,
  7770. disabled
  7771. })
  7772. });
  7773. if (res.ok) {
  7774. await res.json();
  7775. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  7776. aeroIdentityDraft = '';
  7777. aeroSaving = false;
  7778. closeAeroTUNModal();
  7779. await loadAeroTUN(false);
  7780. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7781. fetchData(false);
  7782. } else {
  7783. const err = await responseError(res);
  7784. if (err.includes('configuration saved but tunnel failed to start')) {
  7785. aeroIdentityDraft = '';
  7786. aeroSaving = false;
  7787. closeAeroTUNModal();
  7788. await loadAeroTUN(false);
  7789. showToast('Saved, but not started', err, 'error');
  7790. } else showToast('Error Saving Tunnel', err, 'error');
  7791. }
  7792. } catch (err) {
  7793. showToast('Network Error', err.message, 'error');
  7794. } finally {
  7795. aeroSaving = false;
  7796. if (submit) submit.disabled = false;
  7797. }
  7798. }
  7799. async function startAeroTUNTunnel(id) {
  7800. try {
  7801. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7802. if (res.ok) {
  7803. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7804. loadAeroTUN(false);
  7805. fetchData(false);
  7806. } else {
  7807. const err = await res.text();
  7808. showToast('Failed to Start', err, 'error');
  7809. }
  7810. } catch (err) {
  7811. showToast('Error', err.message, 'error');
  7812. }
  7813. }
  7814. async function stopAeroTUNTunnel(id) {
  7815. try {
  7816. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7817. if (res.ok) {
  7818. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7819. loadAeroTUN(false);
  7820. fetchData(false);
  7821. } else {
  7822. const err = await res.text();
  7823. showToast('Failed to Stop', err, 'error');
  7824. }
  7825. } catch (err) {
  7826. showToast('Error', err.message, 'error');
  7827. }
  7828. }
  7829. async function toggleAeroTUNState(id, disabled) {
  7830. try {
  7831. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7832. method: 'POST',
  7833. headers: { 'Content-Type': 'application/json' },
  7834. body: JSON.stringify({ disabled })
  7835. });
  7836. if (res.ok) {
  7837. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7838. loadAeroTUN(false);
  7839. fetchData(false);
  7840. }
  7841. } catch (err) {
  7842. showToast('Error', err.message, 'error');
  7843. }
  7844. }
  7845. async function deleteAeroTUN(id) {
  7846. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7847. try {
  7848. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7849. if (res.ok) {
  7850. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7851. loadAeroTUN(false);
  7852. fetchData(false);
  7853. }
  7854. } catch (err) {
  7855. showToast('Error', err.message, 'error');
  7856. }
  7857. }
  7858. // ======================== PPP Central Hub & Servers ========================
  7859. function switchPPPSubTab(tab) {
  7860. state.pppSubTab = tab;
  7861. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7862. tabs.forEach(t => {
  7863. const panel = document.getElementById(`ppp-subtab-${t}`);
  7864. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7865. if (panel) {
  7866. if (t === tab) panel.classList.remove('hidden');
  7867. else panel.classList.add('hidden');
  7868. }
  7869. if (btn) {
  7870. if (t === tab) {
  7871. 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';
  7872. } else {
  7873. 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';
  7874. }
  7875. }
  7876. });
  7877. const addBtn = document.getElementById('ppp-primary-add-btn');
  7878. if (addBtn) {
  7879. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7880. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7881. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7882. else addBtn.innerHTML = '<span>Save Config</span>';
  7883. }
  7884. if (tab === 'active') loadPPPSessions();
  7885. }
  7886. function openCurrentPPPModal() {
  7887. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7888. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7889. else if (state.pppSubTab === 'active') loadPPPSessions();
  7890. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7891. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7892. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7893. }
  7894. async function loadPPP(populateDropdowns = true) {
  7895. await Promise.all([
  7896. loadPPPSecrets(),
  7897. loadPPPProfiles(),
  7898. loadPPPServers(),
  7899. loadPPPSessions()
  7900. ]);
  7901. }
  7902. async function loadPPPSecrets() {
  7903. try {
  7904. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7905. const data = await res.json();
  7906. state.pppSecrets = Array.isArray(data) ? data : [];
  7907. const b = document.getElementById('ppp-badge-secrets');
  7908. if (b) b.innerText = state.pppSecrets.length;
  7909. const b2 = document.getElementById('secrets-count-badge');
  7910. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7911. renderPPPSecrets();
  7912. } catch (err) {
  7913. console.error('Failed to load PPP secrets:', err);
  7914. }
  7915. }
  7916. function renderPPPSecrets() {
  7917. const tbody = document.getElementById('secrets-table-body');
  7918. const empty = document.getElementById('secrets-empty');
  7919. if (!tbody) return;
  7920. tbody.innerHTML = '';
  7921. const secrets = state.pppSecrets || [];
  7922. if (secrets.length === 0) {
  7923. empty?.classList.remove('hidden');
  7924. return;
  7925. }
  7926. empty?.classList.add('hidden');
  7927. secrets.forEach(s => {
  7928. const tr = document.createElement('tr');
  7929. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7930. tr.innerHTML = `
  7931. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7932. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7933. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7934. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7935. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7936. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7937. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7938. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7939. <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>
  7940. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7941. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7942. </td>
  7943. `;
  7944. tbody.appendChild(tr);
  7945. });
  7946. }
  7947. async function loadPPPProfiles() {
  7948. try {
  7949. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7950. const data = await res.json();
  7951. state.pppProfiles = Array.isArray(data) ? data : [];
  7952. const b = document.getElementById('ppp-badge-profiles');
  7953. if (b) b.innerText = state.pppProfiles.length;
  7954. const b2 = document.getElementById('profiles-count-badge');
  7955. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7956. // Populate profile selects across modals
  7957. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7958. selects.forEach(sid => {
  7959. const el = document.getElementById(sid);
  7960. if (!el) return;
  7961. const cur = el.value;
  7962. el.innerHTML = '';
  7963. state.pppProfiles.forEach(p => {
  7964. const opt = document.createElement('option');
  7965. opt.value = p.name;
  7966. opt.innerText = `${p.name} (${p.remote_address})`;
  7967. if (p.name === cur) opt.selected = true;
  7968. el.appendChild(opt);
  7969. });
  7970. });
  7971. renderPPPProfiles();
  7972. } catch (err) {
  7973. console.error('Failed to load PPP profiles:', err);
  7974. }
  7975. }
  7976. function renderPPPProfiles() {
  7977. const tbody = document.getElementById('profiles-table-body');
  7978. if (!tbody) return;
  7979. tbody.innerHTML = '';
  7980. (state.pppProfiles || []).forEach(p => {
  7981. const isDefault = p.name.startsWith('default');
  7982. const tr = document.createElement('tr');
  7983. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7984. tr.innerHTML = `
  7985. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7986. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7987. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7988. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7989. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7990. <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>
  7991. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7992. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7993. ${!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>`}
  7994. </td>
  7995. `;
  7996. tbody.appendChild(tr);
  7997. });
  7998. }
  7999. async function loadPPPServers() {
  8000. try {
  8001. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8002. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8003. fetch(`${API_BASE}/vpn/servers/pptp`),
  8004. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8005. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8006. ]);
  8007. if (pppoeRes.ok) {
  8008. state.pppoeServer = await pppoeRes.json();
  8009. const s = state.pppoeServer;
  8010. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8011. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  8012. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8013. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8014. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8015. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8016. const pill = document.getElementById('pppoe-server-status-pill');
  8017. if (pill) {
  8018. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8019. 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';
  8020. }
  8021. setDotBadge('ppp-badge-pppoe-state', s.running);
  8022. }
  8023. if (pptpRes.ok) {
  8024. state.pptpServer = await pptpRes.json();
  8025. const s = state.pptpServer;
  8026. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8027. document.getElementById('pptp-server-port').value = s.port || 1723;
  8028. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8029. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8030. const pill = document.getElementById('pptp-server-status-pill');
  8031. if (pill) {
  8032. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8033. 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';
  8034. }
  8035. setDotBadge('ppp-badge-pptp-state', s.running);
  8036. }
  8037. if (l2tpRes.ok) {
  8038. state.l2tpServer = await l2tpRes.json();
  8039. const s = state.l2tpServer;
  8040. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8041. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8042. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8043. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8044. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8045. const pill = document.getElementById('l2tp-server-status-pill');
  8046. if (pill) {
  8047. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8048. 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';
  8049. }
  8050. setDotBadge('ppp-badge-l2tp-state', s.running);
  8051. }
  8052. if (ipsecRes.ok) {
  8053. state.ipsecServer = await ipsecRes.json();
  8054. const s = state.ipsecServer;
  8055. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8056. if (modalEn) modalEn.checked = !!s.enabled;
  8057. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8058. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8059. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8060. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8061. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8062. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8063. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8064. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8065. const pill = document.getElementById('modal-ipsec-server-status');
  8066. if (pill) {
  8067. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8068. 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';
  8069. }
  8070. }
  8071. } catch (err) {
  8072. console.error('Failed to load VPN servers:', err);
  8073. }
  8074. }
  8075. async function loadPPPSessions() {
  8076. try {
  8077. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8078. const data = await res.json();
  8079. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8080. const b = document.getElementById('ppp-badge-active');
  8081. if (b) b.innerText = state.pppActiveSessions.length;
  8082. const sideB = document.getElementById('badge-ppp-sessions');
  8083. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8084. renderPPPSessions();
  8085. } catch (err) {
  8086. console.error('Failed to load active PPP sessions:', err);
  8087. }
  8088. }
  8089. function renderPPPSessions() {
  8090. const tbody = document.getElementById('active-ppp-table-body');
  8091. const empty = document.getElementById('active-ppp-empty');
  8092. if (!tbody) return;
  8093. tbody.innerHTML = '';
  8094. const list = state.pppActiveSessions || [];
  8095. if (list.length === 0) {
  8096. empty?.classList.remove('hidden');
  8097. return;
  8098. }
  8099. empty?.classList.add('hidden');
  8100. list.forEach(s => {
  8101. const tr = document.createElement('tr');
  8102. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8103. tr.innerHTML = `
  8104. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8105. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8106. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8107. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8108. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8109. <td class="py-2.5 px-3 text-[11px]">
  8110. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8111. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8112. </td>
  8113. <td class="py-2.5 px-3 text-right font-sans">
  8114. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8115. </td>
  8116. `;
  8117. tbody.appendChild(tr);
  8118. });
  8119. }
  8120. async function disconnectPPPSession(iface) {
  8121. if (!confirm(`Disconnect session ${iface}?`)) return;
  8122. try {
  8123. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8124. if (res.ok) {
  8125. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8126. loadPPPSessions();
  8127. }
  8128. } catch (err) {
  8129. showToast('Error', err.message, 'error');
  8130. }
  8131. }
  8132. // PPP Secret Modal handlers
  8133. function openAddPPPSecretModal() {
  8134. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8135. document.getElementById('secret-modal-id').value = '';
  8136. document.getElementById('secret-modal-name').value = '';
  8137. document.getElementById('secret-modal-password').value = '';
  8138. document.getElementById('secret-modal-service').value = 'any';
  8139. document.getElementById('secret-modal-profile').value = 'default';
  8140. document.getElementById('secret-modal-local').value = '';
  8141. document.getElementById('secret-modal-remote').value = '';
  8142. document.getElementById('secret-modal-comment').value = '';
  8143. document.getElementById('secret-modal-disabled').checked = false;
  8144. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8145. }
  8146. function openEditPPPSecretModal(id) {
  8147. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8148. if (!s) return;
  8149. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8150. document.getElementById('secret-modal-id').value = s.id;
  8151. document.getElementById('secret-modal-name').value = s.name;
  8152. document.getElementById('secret-modal-password').value = s.password;
  8153. document.getElementById('secret-modal-service').value = s.service || 'any';
  8154. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8155. document.getElementById('secret-modal-local').value = s.local_address || '';
  8156. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8157. document.getElementById('secret-modal-comment').value = s.comment || '';
  8158. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8159. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8160. }
  8161. function closePPPSecretModal() {
  8162. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8163. }
  8164. async function submitSavePPPSecret(e) {
  8165. e.preventDefault();
  8166. const id = document.getElementById('secret-modal-id').value;
  8167. const name = document.getElementById('secret-modal-name').value.trim();
  8168. const password = document.getElementById('secret-modal-password').value.trim();
  8169. const service = document.getElementById('secret-modal-service').value;
  8170. const profile = document.getElementById('secret-modal-profile').value;
  8171. const local = document.getElementById('secret-modal-local').value.trim();
  8172. const remote = document.getElementById('secret-modal-remote').value.trim();
  8173. const comment = document.getElementById('secret-modal-comment').value.trim();
  8174. const disabled = document.getElementById('secret-modal-disabled').checked;
  8175. try {
  8176. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8177. method: 'POST',
  8178. headers: { 'Content-Type': 'application/json' },
  8179. body: JSON.stringify({
  8180. id,
  8181. name,
  8182. password,
  8183. service,
  8184. profile,
  8185. local_address: local,
  8186. remote_address: remote,
  8187. comment,
  8188. disabled
  8189. })
  8190. });
  8191. if (res.ok) {
  8192. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8193. closePPPSecretModal();
  8194. loadPPPSecrets();
  8195. } else {
  8196. const err = await res.json();
  8197. showToast('Error', err.message, 'error');
  8198. }
  8199. } catch (err) {
  8200. showToast('Error', err.message, 'error');
  8201. }
  8202. }
  8203. async function togglePPPSecretState(id, disabled) {
  8204. try {
  8205. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8206. method: 'POST',
  8207. headers: { 'Content-Type': 'application/json' },
  8208. body: JSON.stringify({ disabled })
  8209. });
  8210. if (res.ok) {
  8211. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8212. loadPPPSecrets();
  8213. }
  8214. } catch (err) {
  8215. showToast('Error', err.message, 'error');
  8216. }
  8217. }
  8218. async function deletePPPSecret(id) {
  8219. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8220. try {
  8221. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8222. if (res.ok) {
  8223. showToast('Deleted', 'Secret account removed', 'success');
  8224. loadPPPSecrets();
  8225. }
  8226. } catch (err) {
  8227. showToast('Error', err.message, 'error');
  8228. }
  8229. }
  8230. // PPP Profile Modal handlers
  8231. function openAddPPPProfileModal() {
  8232. document.getElementById('profile-modal-name').value = '';
  8233. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8234. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8235. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8236. document.getElementById('profile-modal-encryption').value = 'required';
  8237. document.getElementById('profile-modal-onlyone').checked = true;
  8238. document.getElementById('profile-modal-comment').value = '';
  8239. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8240. }
  8241. function closePPPProfileModal() {
  8242. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8243. }
  8244. async function submitSavePPPProfile(e) {
  8245. e.preventDefault();
  8246. const name = document.getElementById('profile-modal-name').value.trim();
  8247. const local = document.getElementById('profile-modal-local').value.trim();
  8248. const remote = document.getElementById('profile-modal-remote').value.trim();
  8249. const dns = document.getElementById('profile-modal-dns').value.trim();
  8250. const enc = document.getElementById('profile-modal-encryption').value;
  8251. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8252. const comment = document.getElementById('profile-modal-comment').value.trim();
  8253. try {
  8254. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8255. method: 'POST',
  8256. headers: { 'Content-Type': 'application/json' },
  8257. body: JSON.stringify({
  8258. id: name,
  8259. name,
  8260. local_address: local,
  8261. remote_address: remote,
  8262. dns_servers: dns,
  8263. use_encryption: enc,
  8264. only_one: onlyone,
  8265. comment
  8266. })
  8267. });
  8268. if (res.ok) {
  8269. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8270. closePPPProfileModal();
  8271. loadPPPProfiles();
  8272. } else {
  8273. const err = await res.json();
  8274. showToast('Error', err.message, 'error');
  8275. }
  8276. } catch (err) {
  8277. showToast('Error', err.message, 'error');
  8278. }
  8279. }
  8280. async function deletePPPProfile(name) {
  8281. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8282. try {
  8283. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8284. if (res.ok) {
  8285. showToast('Deleted', 'Profile removed', 'success');
  8286. loadPPPProfiles();
  8287. } else {
  8288. const err = await res.json();
  8289. showToast('Error', err.message, 'error');
  8290. }
  8291. } catch (err) {
  8292. showToast('Error', err.message, 'error');
  8293. }
  8294. }
  8295. // Server Config submissions
  8296. async function savePPPoEServerConfig(e) {
  8297. e.preventDefault();
  8298. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8299. const name = document.getElementById('pppoe-server-name').value.trim();
  8300. const iface = document.getElementById('pppoe-server-iface').value;
  8301. const profile = document.getElementById('pppoe-server-profile').value;
  8302. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8303. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8304. try {
  8305. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8306. method: 'POST',
  8307. headers: { 'Content-Type': 'application/json' },
  8308. body: JSON.stringify({
  8309. enabled,
  8310. service_name: name,
  8311. interface: iface,
  8312. default_profile: profile,
  8313. max_mtu: mtu,
  8314. max_mru: mtu,
  8315. one_session_per_host: onesession
  8316. })
  8317. });
  8318. if (res.ok) {
  8319. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8320. loadPPPServers();
  8321. fetchData(false);
  8322. } else {
  8323. const err = await res.json();
  8324. showToast('Error', err.message, 'error');
  8325. }
  8326. } catch (err) {
  8327. showToast('Error', err.message, 'error');
  8328. }
  8329. }
  8330. async function savePPTPServerConfig(e) {
  8331. e.preventDefault();
  8332. const enabled = document.getElementById('pptp-server-enabled').checked;
  8333. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8334. const profile = document.getElementById('pptp-server-profile').value;
  8335. const mppe = document.getElementById('pptp-server-mppe').checked;
  8336. try {
  8337. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8338. method: 'POST',
  8339. headers: { 'Content-Type': 'application/json' },
  8340. body: JSON.stringify({
  8341. enabled,
  8342. port,
  8343. default_profile: profile,
  8344. require_mppe: mppe
  8345. })
  8346. });
  8347. if (res.ok) {
  8348. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8349. loadPPPServers();
  8350. fetchData(false);
  8351. } else {
  8352. const err = await res.json();
  8353. showToast('Error', err.message, 'error');
  8354. }
  8355. } catch (err) {
  8356. showToast('Error', err.message, 'error');
  8357. }
  8358. }
  8359. async function saveL2TPServerConfig(e) {
  8360. e.preventDefault();
  8361. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8362. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8363. const profile = document.getElementById('l2tp-server-profile').value;
  8364. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8365. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8366. try {
  8367. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8368. method: 'POST',
  8369. headers: { 'Content-Type': 'application/json' },
  8370. body: JSON.stringify({
  8371. enabled,
  8372. port,
  8373. default_profile: profile,
  8374. use_ipsec: useipsec,
  8375. ipsec_secret: psk
  8376. })
  8377. });
  8378. if (res.ok) {
  8379. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8380. loadPPPServers();
  8381. fetchData(false);
  8382. } else {
  8383. const err = await res.json();
  8384. showToast('Error', err.message, 'error');
  8385. }
  8386. } catch (err) {
  8387. showToast('Error', err.message, 'error');
  8388. }
  8389. }
  8390. // IPSec Server Modal
  8391. function openIPSecServerModal() {
  8392. loadPPPServers();
  8393. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8394. }
  8395. function closeIPSecServerModal() {
  8396. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8397. }
  8398. async function submitSaveIPSecServer(e) {
  8399. e.preventDefault();
  8400. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8401. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8402. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8403. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8404. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8405. try {
  8406. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8407. method: 'POST',
  8408. headers: { 'Content-Type': 'application/json' },
  8409. body: JSON.stringify({
  8410. enabled,
  8411. preshared_key: psk,
  8412. pool_address: pool,
  8413. dns_servers: dns,
  8414. local_subnet: subnet
  8415. })
  8416. });
  8417. if (res.ok) {
  8418. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8419. closeIPSecServerModal();
  8420. loadPPPServers();
  8421. fetchData(false);
  8422. } else {
  8423. const err = await res.json();
  8424. showToast('Error', err.message, 'error');
  8425. }
  8426. } catch (err) {
  8427. showToast('Error', err.message, 'error');
  8428. }
  8429. }
  8430. // WireGuard Client Config Viewer
  8431. let currentWGClientConf = '';
  8432. async function openWGClientConfModal(iface, clientIP) {
  8433. try {
  8434. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8435. method: 'POST',
  8436. headers: { 'Content-Type': 'application/json' },
  8437. body: JSON.stringify({
  8438. interface: iface,
  8439. address: clientIP || '10.10.0.2/32',
  8440. dns: '1.1.1.1, 8.8.8.8'
  8441. })
  8442. });
  8443. if (res.ok) {
  8444. const data = await res.json();
  8445. currentWGClientConf = data.config;
  8446. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8447. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8448. } else {
  8449. const err = await res.json();
  8450. showToast('Error', err.message, 'error');
  8451. }
  8452. } catch (err) {
  8453. showToast('Error', err.message, 'error');
  8454. }
  8455. }
  8456. function closeWGClientConfModal() {
  8457. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8458. }
  8459. function copyWGClientConf() {
  8460. if (!currentWGClientConf) return;
  8461. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8462. }
  8463. function downloadWGClientConf() {
  8464. if (!currentWGClientConf) return;
  8465. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8466. const a = document.createElement('a');
  8467. a.href = URL.createObjectURL(blob);
  8468. a.download = 'wireguard-client.conf';
  8469. document.body.appendChild(a);
  8470. a.click();
  8471. document.body.removeChild(a);
  8472. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8473. }
  8474. // =========================================================================
  8475. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8476. // =========================================================================
  8477. state.activeDynSubTab = 'bgp-peers';
  8478. state.activeBgpSubTab = 'bgp-peers';
  8479. state.activeOspfTab = 'instances';
  8480. state.bgpInstance = null;
  8481. state.bgpPeers = [];
  8482. state.bgpNets = [];
  8483. state.bgpRoutes = [];
  8484. state.ospfInstance = null;
  8485. state.ospfInstances = [];
  8486. state.ospfAreas = [];
  8487. state.ospfAreaRanges = [];
  8488. state.ospfTemplates = [];
  8489. state.ospfLiveInterfaces = [];
  8490. state.ospfStaticNbrs = [];
  8491. state.ospfNeighbors = [];
  8492. state.ospfLSA = [];
  8493. state.ospfRoutes = [];
  8494. state.selectedOspfRow = {
  8495. instances: null,
  8496. areas: null,
  8497. 'area-ranges': null,
  8498. templates: null,
  8499. interfaces: null,
  8500. 'static-nbrs': null,
  8501. neighbors: null,
  8502. lsa: null,
  8503. };
  8504. state.ospfSort = {
  8505. instances: { col: 'name', asc: true },
  8506. areas: { col: 'name', asc: true },
  8507. ranges: { col: 'area', asc: true },
  8508. templates: { col: 'interfaces', asc: true },
  8509. live_ifaces: { col: 'interface', asc: true },
  8510. snbrs: { col: 'address', asc: true },
  8511. neighbors: { col: 'address', asc: true },
  8512. lsa: { col: 'instance', asc: true },
  8513. };
  8514. function switchBgpSubTab(subTab) {
  8515. state.activeBgpSubTab = subTab;
  8516. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8517. tabs.forEach(t => {
  8518. const el = document.getElementById(`dyn-subtab-${t}`);
  8519. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8520. if (el) el.classList.toggle('hidden', t !== subTab);
  8521. if (btn) {
  8522. if (t === subTab) {
  8523. 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';
  8524. } else {
  8525. 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';
  8526. }
  8527. }
  8528. });
  8529. }
  8530. function switchOspfTab(tabName) {
  8531. state.activeOspfTab = tabName;
  8532. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8533. tabs.forEach(t => {
  8534. const pane = document.getElementById(`ospf-pane-${t}`);
  8535. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8536. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8537. if (btn) {
  8538. if (t === tabName) {
  8539. 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';
  8540. } else {
  8541. 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';
  8542. }
  8543. }
  8544. });
  8545. }
  8546. function switchOspfSubTab(tab) {
  8547. // Legacy alias
  8548. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8549. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8550. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8551. else switchOspfTab('instances');
  8552. }
  8553. function switchDynSubTab(subTab) {
  8554. if (subTab.startsWith('bgp')) {
  8555. if (state.activeTab !== 'bgp') navigate('bgp');
  8556. switchBgpSubTab(subTab);
  8557. } else if (subTab.startsWith('ospf')) {
  8558. if (state.activeTab !== 'ospf') navigate('ospf');
  8559. switchOspfTab('instances');
  8560. }
  8561. }
  8562. async function loadDynamicRouting(showToastMsg = false) {
  8563. try {
  8564. const fetchSafeJson = async (url) => {
  8565. try {
  8566. const r = await fetch(url);
  8567. return r.ok ? await r.json() : null;
  8568. } catch (e) {
  8569. return null;
  8570. }
  8571. };
  8572. const [
  8573. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8574. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8575. selectRules, commLists, asLists
  8576. ] = await Promise.all([
  8577. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8578. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8579. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8580. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8581. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8582. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8583. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8584. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8585. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8586. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8587. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8588. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8589. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8590. fetchSafeJson(`${API_BASE}/routing/filters`),
  8591. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  8592. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8593. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  8594. ]);
  8595. if (sum) state.dynSummary = sum;
  8596. if (bgpInst) state.bgpInstance = bgpInst;
  8597. if (bgpPeers) state.bgpPeers = bgpPeers;
  8598. if (bgpNets) state.bgpNets = bgpNets;
  8599. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8600. if (ospfInsts) state.ospfInstances = ospfInsts;
  8601. if (ospfAreas) state.ospfAreas = ospfAreas;
  8602. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8603. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8604. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8605. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8606. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8607. if (ospfLsa) state.ospfLSA = ospfLsa;
  8608. if (filters) state.routingFilters = filters;
  8609. if (selectRules) state.routingSelectRules = selectRules;
  8610. if (commLists) state.routingCommunityLists = commLists;
  8611. if (asLists) state.routingASLists = asLists;
  8612. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8613. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8614. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8615. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8616. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8617. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8618. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8619. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  8620. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  8621. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  8622. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  8623. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  8624. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  8625. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  8626. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  8627. } catch (err) {
  8628. console.error('Failed to load dynamic routing:', err);
  8629. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  8630. }
  8631. }
  8632. async function loadOspfAll() {
  8633. await loadDynamicRouting(true);
  8634. }
  8635. function renderBgpStatusPill() {
  8636. const pills = document.querySelectorAll('.bgp-live-status-pill');
  8637. pills.forEach(pill => {
  8638. const inst = state.bgpInstance;
  8639. if (!inst || !inst.enabled) {
  8640. 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';
  8641. pill.innerText = 'BGP DISABLED';
  8642. } else if (inst.running) {
  8643. 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';
  8644. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  8645. } else {
  8646. 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';
  8647. pill.innerText = 'BGP STARTING...';
  8648. }
  8649. });
  8650. }
  8651. function renderBgpPeers() {
  8652. const tbody = document.getElementById('bgp-peers-table-body');
  8653. if (!tbody) return;
  8654. const empty = document.getElementById('bgp-peers-empty');
  8655. const countBadge = document.getElementById('bgp-peers-count-badge');
  8656. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8657. const peers = state.bgpPeers || [];
  8658. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8659. if (navBadge) navBadge.innerText = peers.length;
  8660. if (peers.length === 0) {
  8661. tbody.innerHTML = '';
  8662. if (empty) empty.classList.remove('hidden');
  8663. return;
  8664. }
  8665. if (empty) empty.classList.add('hidden');
  8666. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8667. if (tbody.dataset.sig === sig) return;
  8668. tbody.dataset.sig = sig;
  8669. tbody.innerHTML = peers.map(p => {
  8670. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8671. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8672. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8673. let stateBadge = '';
  8674. if (p.disabled) {
  8675. 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>';
  8676. } else if (p.state === 'Established') {
  8677. 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>';
  8678. } else if (p.state === 'Connect' || p.state === 'Active') {
  8679. 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>`;
  8680. } else {
  8681. 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>`;
  8682. }
  8683. return `
  8684. <tr class="hover:bg-slate-800/40 transition">
  8685. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8686. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8687. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8688. <td class="py-2.5 px-3">
  8689. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8690. ${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>`}
  8691. </td>
  8692. <td class="py-2.5 px-3">${stateBadge}</td>
  8693. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8694. <td class="py-2.5 px-3 text-slate-300">
  8695. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8696. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8697. </td>
  8698. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8699. ${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> ` : ''}
  8700. ${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>` : ''}
  8701. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8702. </td>
  8703. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8704. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8705. <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'}">
  8706. ${p.disabled ? 'Enable' : 'Disable'}
  8707. </button>
  8708. <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">
  8709. Edit
  8710. </button>
  8711. <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">
  8712. Delete
  8713. </button>
  8714. </td>
  8715. </tr>
  8716. `;
  8717. }).join('');
  8718. }
  8719. function renderBgpNetworks() {
  8720. const tbody = document.getElementById('bgp-nets-table-body');
  8721. if (!tbody) return;
  8722. const empty = document.getElementById('bgp-nets-empty');
  8723. const countBadge = document.getElementById('bgp-nets-count-badge');
  8724. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8725. const nets = state.bgpNets || [];
  8726. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8727. if (navBadge) navBadge.innerText = nets.length;
  8728. if (nets.length === 0) {
  8729. tbody.innerHTML = '';
  8730. if (empty) empty.classList.remove('hidden');
  8731. return;
  8732. }
  8733. if (empty) empty.classList.add('hidden');
  8734. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8735. if (tbody.dataset.sig === sig) return;
  8736. tbody.dataset.sig = sig;
  8737. tbody.innerHTML = nets.map(n => `
  8738. <tr class="hover:bg-slate-800/40 transition">
  8739. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8740. <td class="py-2.5 px-3">
  8741. ${n.disabled
  8742. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8743. : '<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>'}
  8744. </td>
  8745. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8746. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8747. <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">
  8748. Delete
  8749. </button>
  8750. </td>
  8751. </tr>
  8752. `).join('');
  8753. }
  8754. function renderBgpRoutes() {
  8755. const tbody = document.getElementById('bgp-routes-table-body');
  8756. if (!tbody) return;
  8757. const empty = document.getElementById('bgp-routes-empty');
  8758. const countBadge = document.getElementById('bgp-routes-count-badge');
  8759. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8760. const routes = state.bgpRoutes || [];
  8761. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8762. if (navBadge) navBadge.innerText = routes.length;
  8763. if (routes.length === 0) {
  8764. tbody.innerHTML = '';
  8765. if (empty) empty.classList.remove('hidden');
  8766. return;
  8767. }
  8768. if (empty) empty.classList.add('hidden');
  8769. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8770. if (tbody.dataset.sig === sig) return;
  8771. tbody.dataset.sig = sig;
  8772. tbody.innerHTML = routes.map(r => `
  8773. <tr class="hover:bg-slate-800/40 transition">
  8774. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8775. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8776. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8777. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8778. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8779. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8780. </tr>
  8781. `).join('');
  8782. }
  8783. // =========================================================================
  8784. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8785. // =========================================================================
  8786. function sortOspfTable(tab, col) {
  8787. if (!state.ospfSort) state.ospfSort = {};
  8788. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8789. if (state.ospfSort[tab].col === col) {
  8790. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8791. } else {
  8792. state.ospfSort[tab].col = col;
  8793. state.ospfSort[tab].asc = true;
  8794. }
  8795. const asc = state.ospfSort[tab].asc;
  8796. let list = [];
  8797. if (tab === 'instances') list = state.ospfInstances || [];
  8798. else if (tab === 'areas') list = state.ospfAreas || [];
  8799. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8800. else if (tab === 'templates') list = state.ospfTemplates || [];
  8801. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8802. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8803. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8804. else if (tab === 'lsa') list = state.ospfLSA || [];
  8805. list.sort((a, b) => {
  8806. let valA = a[col] ?? '';
  8807. let valB = b[col] ?? '';
  8808. if (typeof valA === 'number' && typeof valB === 'number') {
  8809. return asc ? valA - valB : valB - valA;
  8810. }
  8811. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8812. });
  8813. if (tab === 'instances') renderOspfInstances();
  8814. else if (tab === 'areas') renderOspfAreas();
  8815. else if (tab === 'ranges') renderOspfAreaRanges();
  8816. else if (tab === 'templates') renderOspfTemplates();
  8817. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8818. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8819. else if (tab === 'neighbors') renderOspfNeighbors();
  8820. else if (tab === 'lsa') renderOspfLSA();
  8821. }
  8822. function selectOspfRow(tab, id) {
  8823. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8824. state.selectedOspfRow[tab] = id;
  8825. if (tab === 'instances') {
  8826. renderOspfInstances();
  8827. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8828. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8829. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8830. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8831. if (btnEn) btnEn.disabled = false;
  8832. if (btnDis) btnDis.disabled = false;
  8833. if (btnRem) btnRem.disabled = false;
  8834. if (btnCom) btnCom.disabled = false;
  8835. } else if (tab === 'areas') {
  8836. renderOspfAreas();
  8837. const btnEn = document.getElementById('btn-ospf-area-enable');
  8838. const btnDis = document.getElementById('btn-ospf-area-disable');
  8839. const btnRem = document.getElementById('btn-ospf-area-remove');
  8840. const btnCom = document.getElementById('btn-ospf-area-comment');
  8841. if (btnEn) btnEn.disabled = false;
  8842. if (btnDis) btnDis.disabled = false;
  8843. if (btnRem) btnRem.disabled = false;
  8844. if (btnCom) btnCom.disabled = false;
  8845. } else if (tab === 'ranges') {
  8846. renderOspfAreaRanges();
  8847. const btnEn = document.getElementById('btn-ospf-range-enable');
  8848. const btnDis = document.getElementById('btn-ospf-range-disable');
  8849. const btnRem = document.getElementById('btn-ospf-range-remove');
  8850. const btnCom = document.getElementById('btn-ospf-range-comment');
  8851. if (btnEn) btnEn.disabled = false;
  8852. if (btnDis) btnDis.disabled = false;
  8853. if (btnRem) btnRem.disabled = false;
  8854. if (btnCom) btnCom.disabled = false;
  8855. } else if (tab === 'templates') {
  8856. renderOspfTemplates();
  8857. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8858. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8859. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8860. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8861. if (btnEn) btnEn.disabled = false;
  8862. if (btnDis) btnDis.disabled = false;
  8863. if (btnRem) btnRem.disabled = false;
  8864. if (btnCom) btnCom.disabled = false;
  8865. } else if (tab === 'snbrs') {
  8866. renderOspfStaticNbrs();
  8867. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8868. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8869. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8870. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8871. if (btnEn) btnEn.disabled = false;
  8872. if (btnDis) btnDis.disabled = false;
  8873. if (btnRem) btnRem.disabled = false;
  8874. if (btnCom) btnCom.disabled = false;
  8875. }
  8876. }
  8877. // TAB 1: INSTANCES
  8878. function renderOspfInstances() {
  8879. const tbody = document.getElementById('ospf-instances-table-body');
  8880. if (!tbody) return;
  8881. const countEl = document.getElementById('ospf-instances-footer-count');
  8882. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8883. let list = state.ospfInstances || [];
  8884. if (filter) {
  8885. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8886. }
  8887. if (countEl) countEl.innerText = list.length;
  8888. const selId = state.selectedOspfRow?.instances;
  8889. tbody.innerHTML = list.map((inst, idx) => {
  8890. const isSel = inst.id === selId;
  8891. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8892. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8893. return `
  8894. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8895. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8896. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8897. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8898. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8899. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8900. </td>
  8901. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8902. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8903. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8904. </tr>
  8905. `;
  8906. }).join('');
  8907. }
  8908. // TAB 2: AREAS
  8909. function renderOspfAreas() {
  8910. const tbody = document.getElementById('ospf-areas-table-body');
  8911. if (!tbody) return;
  8912. const countEl = document.getElementById('ospf-areas-footer-count');
  8913. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8914. let list = state.ospfAreas || [];
  8915. if (filter) {
  8916. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8917. }
  8918. if (countEl) countEl.innerText = list.length;
  8919. const selId = state.selectedOspfRow?.areas;
  8920. tbody.innerHTML = list.map((a, idx) => {
  8921. const isSel = a.id === selId;
  8922. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8923. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8924. return `
  8925. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8926. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8927. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8928. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8929. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8930. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8931. </td>
  8932. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8933. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8934. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8935. </tr>
  8936. `;
  8937. }).join('');
  8938. }
  8939. // TAB 3: AREA RANGES
  8940. function renderOspfAreaRanges() {
  8941. const tbody = document.getElementById('ospf-ranges-table-body');
  8942. if (!tbody) return;
  8943. const countEl = document.getElementById('ospf-ranges-footer-count');
  8944. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8945. let list = state.ospfAreaRanges || [];
  8946. if (filter) {
  8947. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8948. }
  8949. if (countEl) countEl.innerText = list.length;
  8950. const selId = state.selectedOspfRow?.['area-ranges'];
  8951. tbody.innerHTML = list.map((r, idx) => {
  8952. const isSel = r.id === selId;
  8953. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8954. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8955. return `
  8956. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8957. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8958. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8959. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8960. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8961. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8962. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8963. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8964. </tr>
  8965. `;
  8966. }).join('');
  8967. }
  8968. // TAB 4: INTERFACE TEMPLATES
  8969. function renderOspfTemplates() {
  8970. const tbody = document.getElementById('ospf-templates-table-body');
  8971. if (!tbody) return;
  8972. const countEl = document.getElementById('ospf-templates-footer-count');
  8973. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8974. let list = state.ospfTemplates || [];
  8975. if (filter) {
  8976. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8977. }
  8978. if (countEl) countEl.innerText = list.length;
  8979. const selId = state.selectedOspfRow?.templates;
  8980. tbody.innerHTML = list.map((t, idx) => {
  8981. const isSel = t.id === selId;
  8982. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8983. const ifaces = t.interfaces || t.interface || 'all';
  8984. const nets = t.networks || t.network || '';
  8985. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8986. return `
  8987. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8988. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8989. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8990. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8991. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8992. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8993. </td>
  8994. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8995. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8996. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8997. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8998. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8999. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9000. </tr>
  9001. `;
  9002. }).join('');
  9003. }
  9004. // TAB 5: LIVE INTERFACES
  9005. function renderOspfLiveInterfaces() {
  9006. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9007. if (!tbody) return;
  9008. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9009. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9010. let list = state.ospfLiveInterfaces || [];
  9011. if (filter) {
  9012. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9013. }
  9014. if (countEl) countEl.innerText = list.length;
  9015. tbody.innerHTML = list.map(i => `
  9016. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9017. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9018. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9019. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9020. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9021. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9022. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9023. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9024. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9025. </tr>
  9026. `).join('');
  9027. }
  9028. // TAB 6: STATIC NEIGHBORS
  9029. function renderOspfStaticNbrs() {
  9030. const tbody = document.getElementById('ospf-snbrs-table-body');
  9031. if (!tbody) return;
  9032. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9033. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9034. let list = state.ospfStaticNbrs || [];
  9035. if (filter) {
  9036. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9037. }
  9038. if (countEl) countEl.innerText = list.length;
  9039. const selId = state.selectedOspfRow?.['static-nbrs'];
  9040. tbody.innerHTML = list.map((n, idx) => {
  9041. const isSel = n.id === selId;
  9042. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9043. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9044. return `
  9045. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9046. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9047. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9048. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9049. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9050. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9051. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9052. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9053. </tr>
  9054. `;
  9055. }).join('');
  9056. }
  9057. // TAB 7: LIVE NEIGHBORS
  9058. function renderOspfNeighbors() {
  9059. const tbody = document.getElementById('ospf-neighbors-table-body');
  9060. if (!tbody) return;
  9061. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9062. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9063. let list = state.ospfNeighbors || [];
  9064. if (filter) {
  9065. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9066. }
  9067. if (countEl) countEl.innerText = list.length;
  9068. tbody.innerHTML = list.map(n => `
  9069. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9070. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9071. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9072. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9073. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9074. </td>
  9075. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9076. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9077. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9078. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9079. </tr>
  9080. `).join('');
  9081. }
  9082. // TAB 8: LINK-STATE DATABASE (LSA)
  9083. function renderOspfLSA() {
  9084. const tbody = document.getElementById('ospf-lsa-table-body');
  9085. if (!tbody) return;
  9086. const countEl = document.getElementById('ospf-lsa-footer-count');
  9087. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9088. let list = state.ospfLSA || [];
  9089. if (filter) {
  9090. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9091. }
  9092. if (countEl) countEl.innerText = list.length;
  9093. tbody.innerHTML = list.map(l => `
  9094. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9095. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9096. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9097. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9098. </td>
  9099. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9100. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9101. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9102. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9103. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9104. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9105. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9106. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9107. </tr>
  9108. `).join('');
  9109. }
  9110. function renderOspfStatusPill() {
  9111. // Maintained for backward compatibility
  9112. const pill = document.getElementById('ospf-live-status-pill');
  9113. if (!pill) return;
  9114. 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';
  9115. pill.innerText = 'OSPF ACTIVE';
  9116. }
  9117. function renderOspfInterfaces() {
  9118. renderOspfTemplates();
  9119. }
  9120. function renderOspfRoutes() {
  9121. // Routes retained in background
  9122. }
  9123. // BGP Modals & Actions
  9124. function openBgpInstanceModal() {
  9125. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9126. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9127. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9128. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9129. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9130. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9131. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9132. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9133. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9134. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9135. }
  9136. function closeBgpInstanceModal() {
  9137. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9138. }
  9139. async function submitBgpInstance(e) {
  9140. e.preventDefault();
  9141. const payload = {
  9142. enabled: document.getElementById('modal-bgp-enabled').checked,
  9143. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9144. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9145. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9146. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9147. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9148. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9149. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9150. };
  9151. try {
  9152. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9153. method: 'POST',
  9154. headers: { 'Content-Type': 'application/json' },
  9155. body: JSON.stringify(payload)
  9156. });
  9157. if (res.ok) {
  9158. closeBgpInstanceModal();
  9159. showToast('Success', 'BGP instance configuration updated', 'success');
  9160. loadDynamicRouting();
  9161. } else {
  9162. const err = await res.json();
  9163. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9164. }
  9165. } catch (err) {
  9166. showToast('Error', err.message, 'error');
  9167. }
  9168. }
  9169. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9170. function switchBgpPeerModalTab(tab) {
  9171. const tabs = ['general', 'extra', 'attributes', 'filter'];
  9172. tabs.forEach(t => {
  9173. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9174. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9175. if (t === tab) {
  9176. if (pane) pane.classList.remove('hidden');
  9177. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9178. } else {
  9179. if (pane) pane.classList.add('hidden');
  9180. 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';
  9181. }
  9182. });
  9183. }
  9184. function addOutputNetworkRow(val = '') {
  9185. const container = document.getElementById('modal-bgp-output-networks-container');
  9186. if (!container) return;
  9187. const row = document.createElement('div');
  9188. row.className = 'flex items-center gap-2 output-net-row';
  9189. row.innerHTML = `
  9190. <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">
  9191. <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>
  9192. `;
  9193. container.appendChild(row);
  9194. }
  9195. function parseBgpTime(val) {
  9196. if (!val) return 0;
  9197. val = String(val).trim();
  9198. if (val.includes(':')) {
  9199. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9200. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9201. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9202. }
  9203. return parseInt(val, 10) || 0;
  9204. }
  9205. function formatBgpTime(secs) {
  9206. if (!secs || secs <= 0) return '00:00:00';
  9207. const h = Math.floor(secs / 3600);
  9208. const m = Math.floor((secs % 3600) / 60);
  9209. const s = secs % 60;
  9210. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  9211. }
  9212. function populateBgpRoutingTables() {
  9213. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9214. if (!sel) return;
  9215. const cur = sel.value || 'main';
  9216. sel.innerHTML = '<option value="main">main</option>';
  9217. (state.routingTables || []).forEach(t => {
  9218. if (t.name !== 'main') {
  9219. const opt = document.createElement('option');
  9220. opt.value = t.name;
  9221. opt.innerText = t.name;
  9222. sel.appendChild(opt);
  9223. }
  9224. });
  9225. sel.value = cur;
  9226. }
  9227. function openAddBgpPeerModal() {
  9228. document.getElementById('bgp-peer-form').reset();
  9229. document.getElementById('modal-bgp-peer-id').value = '';
  9230. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  9231. // General Tab
  9232. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9233. document.getElementById('modal-bgp-peer-comment').value = '';
  9234. document.getElementById('modal-bgp-peer-name').value = '';
  9235. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  9236. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  9237. document.getElementById('modal-bgp-peer-local-as').value = '';
  9238. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  9239. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  9240. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  9241. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  9242. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  9243. document.getElementById('modal-bgp-peer-router-id').value = '';
  9244. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9245. document.getElementById('modal-bgp-peer-remote-port').value = '';
  9246. document.getElementById('modal-bgp-peer-remote-as').value = '';
  9247. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  9248. document.getElementById('modal-bgp-peer-local-addr').value = '';
  9249. document.getElementById('modal-bgp-peer-local-port').value = '';
  9250. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9251. document.getElementById('modal-bgp-peer-password').value = '';
  9252. document.getElementById('modal-bgp-peer-multihop').checked = false;
  9253. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  9254. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  9255. document.getElementById('modal-bgp-peer-connect').checked = true;
  9256. document.getElementById('modal-bgp-peer-listen').checked = true;
  9257. // Extra Tab
  9258. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  9259. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  9260. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9261. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  9262. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  9263. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9264. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9265. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  9266. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9267. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  9268. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  9269. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  9270. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  9271. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  9272. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9273. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  9274. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  9275. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  9276. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  9277. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  9278. // Attributes Tab
  9279. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  9280. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  9281. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  9282. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  9283. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  9284. document.getElementById('modal-bgp-peer-as-override').checked = false;
  9285. // Filter Tab
  9286. populateFilterChainsDatalist();
  9287. document.getElementById('modal-bgp-peer-in-filter').value = '';
  9288. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  9289. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  9290. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  9291. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  9292. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  9293. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  9294. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  9295. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  9296. document.getElementById('modal-bgp-peer-out-filter').value = '';
  9297. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  9298. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  9299. populateBgpRoutingTables();
  9300. const container = document.getElementById('modal-bgp-output-networks-container');
  9301. if (container) {
  9302. container.innerHTML = '';
  9303. addOutputNetworkRow('');
  9304. }
  9305. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9306. if (removeBtn) removeBtn.classList.add('hidden');
  9307. switchBgpPeerModalTab('general');
  9308. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9309. }
  9310. function populateFilterChainsDatalist() {
  9311. const dl = document.getElementById('filter-chains-list');
  9312. if (!dl) return;
  9313. const chains = new Set();
  9314. (state.routingFilters || []).forEach(f => {
  9315. if (f.chain) chains.add(f.chain);
  9316. });
  9317. if (chains.size === 0) {
  9318. chains.add('awmn');
  9319. chains.add('bgp-in');
  9320. chains.add('bgp-out');
  9321. }
  9322. dl.innerHTML = '';
  9323. chains.forEach(c => {
  9324. const opt = document.createElement('option');
  9325. opt.value = c;
  9326. dl.appendChild(opt);
  9327. });
  9328. }
  9329. function openEditBgpPeerModal(id) {
  9330. const p = (state.bgpPeers || []).find(item => item.id === id);
  9331. if (!p) return;
  9332. populateBgpRoutingTables();
  9333. populateFilterChainsDatalist();
  9334. document.getElementById('modal-bgp-peer-id').value = p.id;
  9335. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9336. // General Tab
  9337. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9338. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9339. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9340. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  9341. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  9342. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9343. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  9344. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  9345. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  9346. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9347. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9348. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9349. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  9350. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9351. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9352. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9353. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9354. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9355. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  9356. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  9357. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  9358. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  9359. // Extra Tab
  9360. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  9361. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  9362. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9363. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  9364. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  9365. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  9366. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9367. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9368. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  9369. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9370. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  9371. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  9372. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  9373. 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;
  9374. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  9375. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9376. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  9377. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  9378. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  9379. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  9380. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  9381. // Attributes Tab
  9382. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  9383. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  9384. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  9385. 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;
  9386. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  9387. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  9388. // Filter Tab
  9389. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9390. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  9391. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  9392. 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 || '';
  9393. 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 || '';
  9394. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  9395. 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 || '';
  9396. 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 || '';
  9397. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  9398. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9399. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  9400. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  9401. // Output Networks
  9402. const container = document.getElementById('modal-bgp-output-networks-container');
  9403. if (container) {
  9404. container.innerHTML = '';
  9405. if (p.output_networks && p.output_networks.length > 0) {
  9406. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9407. } else {
  9408. addOutputNetworkRow('');
  9409. }
  9410. }
  9411. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9412. if (removeBtn) removeBtn.classList.remove('hidden');
  9413. switchBgpPeerModalTab('general');
  9414. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9415. }
  9416. function copyCurrentBgpPeer() {
  9417. document.getElementById('modal-bgp-peer-id').value = '';
  9418. const nameEl = document.getElementById('modal-bgp-peer-name');
  9419. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9420. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  9421. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9422. if (removeBtn) removeBtn.classList.add('hidden');
  9423. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9424. }
  9425. function removeCurrentBgpPeer() {
  9426. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9427. if (!id) return;
  9428. deleteBgpPeer(id);
  9429. closeBgpPeerModal();
  9430. }
  9431. function closeBgpPeerModal() {
  9432. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9433. }
  9434. function getBgpPeerFormData() {
  9435. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9436. const outputNetworks = [];
  9437. netInputs.forEach(inp => {
  9438. const v = inp.value.trim();
  9439. if (v) outputNetworks.push(v);
  9440. });
  9441. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9442. return {
  9443. id: document.getElementById('modal-bgp-peer-id').value,
  9444. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9445. enabled: enabled,
  9446. disabled: !enabled,
  9447. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9448. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  9449. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  9450. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9451. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  9452. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  9453. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9454. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9455. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9456. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  9457. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  9458. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  9459. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  9460. password: document.getElementById('modal-bgp-peer-password').value,
  9461. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  9462. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  9463. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  9464. connect: document.getElementById('modal-bgp-peer-connect').checked,
  9465. listen: document.getElementById('modal-bgp-peer-listen').checked,
  9466. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  9467. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  9468. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  9469. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  9470. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  9471. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  9472. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  9473. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  9474. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  9475. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  9476. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  9477. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  9478. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  9479. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  9480. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  9481. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  9482. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  9483. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  9484. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  9485. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  9486. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  9487. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  9488. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  9489. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  9490. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  9491. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  9492. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  9493. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  9494. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9495. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  9496. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  9497. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  9498. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  9499. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  9500. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  9501. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  9502. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  9503. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9504. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  9505. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  9506. output_networks: outputNetworks
  9507. };
  9508. }
  9509. async function submitBgpPeer(e) {
  9510. if (e) e.preventDefault();
  9511. const payload = getBgpPeerFormData();
  9512. try {
  9513. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9514. method: 'POST',
  9515. headers: { 'Content-Type': 'application/json' },
  9516. body: JSON.stringify(payload)
  9517. });
  9518. if (res.ok) {
  9519. closeBgpPeerModal();
  9520. showToast('Success', 'BGP Connection saved', 'success');
  9521. loadDynamicRouting();
  9522. } else {
  9523. const err = await res.json();
  9524. showToast('Error', err.error || 'Failed to save peer', 'error');
  9525. }
  9526. } catch (err) {
  9527. showToast('Error', err.message, 'error');
  9528. }
  9529. }
  9530. async function applyBgpPeerModal(e) {
  9531. if (e) e.preventDefault();
  9532. const payload = getBgpPeerFormData();
  9533. try {
  9534. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9535. method: 'POST',
  9536. headers: { 'Content-Type': 'application/json' },
  9537. body: JSON.stringify(payload)
  9538. });
  9539. if (res.ok) {
  9540. const data = await res.json();
  9541. if (data.peer && data.peer.id) {
  9542. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9543. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9544. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9545. }
  9546. showToast('Applied', 'BGP Connection applied', 'success');
  9547. loadDynamicRouting();
  9548. } else {
  9549. const err = await res.json();
  9550. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9551. }
  9552. } catch (err) {
  9553. showToast('Error', err.message, 'error');
  9554. }
  9555. }
  9556. async function deleteBgpPeer(id) {
  9557. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9558. try {
  9559. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9560. if (res.ok) {
  9561. showToast('Deleted', 'BGP peer removed', 'success');
  9562. loadDynamicRouting();
  9563. }
  9564. } catch (err) {
  9565. showToast('Error', err.message, 'error');
  9566. }
  9567. }
  9568. async function toggleBgpPeerState(id, disabled) {
  9569. try {
  9570. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9571. method: 'POST',
  9572. headers: { 'Content-Type': 'application/json' },
  9573. body: JSON.stringify({ disabled })
  9574. });
  9575. if (res.ok) {
  9576. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9577. loadDynamicRouting();
  9578. }
  9579. } catch (err) {
  9580. showToast('Error', err.message, 'error');
  9581. }
  9582. }
  9583. function openAddBgpNetworkModal() {
  9584. document.getElementById('bgp-network-form').reset();
  9585. document.getElementById('modal-bgp-net-id').value = '';
  9586. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9587. }
  9588. function closeBgpNetworkModal() {
  9589. document.getElementById('bgp-network-modal').classList.add('hidden');
  9590. }
  9591. async function submitBgpNetwork(e) {
  9592. e.preventDefault();
  9593. const payload = {
  9594. id: document.getElementById('modal-bgp-net-id').value,
  9595. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9596. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9597. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9598. };
  9599. try {
  9600. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9601. method: 'POST',
  9602. headers: { 'Content-Type': 'application/json' },
  9603. body: JSON.stringify(payload)
  9604. });
  9605. if (res.ok) {
  9606. closeBgpNetworkModal();
  9607. showToast('Success', 'BGP network advertisement saved', 'success');
  9608. loadDynamicRouting();
  9609. } else {
  9610. const err = await res.json();
  9611. showToast('Error', err.error || 'Failed to save network', 'error');
  9612. }
  9613. } catch (err) {
  9614. showToast('Error', err.message, 'error');
  9615. }
  9616. }
  9617. async function deleteBgpNetwork(id) {
  9618. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9619. try {
  9620. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9621. if (res.ok) {
  9622. showToast('Deleted', 'Network advertisement removed', 'success');
  9623. loadDynamicRouting();
  9624. }
  9625. } catch (err) {
  9626. showToast('Error', err.message, 'error');
  9627. }
  9628. }
  9629. // =========================================================================
  9630. // DEBTIK v7 OSPF MODALS & ACTIONS
  9631. // =========================================================================
  9632. // --- 1. OSPF INSTANCE ---
  9633. function openOspfInstanceModal(id = null) {
  9634. const isEdit = !!id;
  9635. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9636. id: '',
  9637. name: 'Default',
  9638. version: 2,
  9639. vrf: 'main',
  9640. router_id: '192.168.131.56',
  9641. routing_table: 'main',
  9642. enabled: true,
  9643. redistribute_connected: false,
  9644. redistribute_static: true,
  9645. redistribute_bgp: false,
  9646. comment: ''
  9647. };
  9648. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9649. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9650. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9651. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9652. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9653. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9654. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9655. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9656. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9657. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9658. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9659. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9660. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9661. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9662. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9663. }
  9664. function openEditOspfInstanceModal(id) {
  9665. openOspfInstanceModal(id);
  9666. }
  9667. function closeOspfInstanceModal() {
  9668. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9669. }
  9670. async function submitOspfInstance(e) {
  9671. if (e) e.preventDefault();
  9672. const payload = {
  9673. id: document.getElementById('modal-ospf-inst-id').value,
  9674. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9675. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9676. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9677. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9678. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9679. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9680. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9681. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9682. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9683. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9684. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9685. };
  9686. try {
  9687. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9688. method: 'POST',
  9689. headers: { 'Content-Type': 'application/json' },
  9690. body: JSON.stringify(payload)
  9691. });
  9692. if (res.ok) {
  9693. closeOspfInstanceModal();
  9694. showToast('Saved', 'OSPF instance updated', 'success');
  9695. loadDynamicRouting();
  9696. } else {
  9697. const err = await res.json();
  9698. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9699. }
  9700. } catch (err) {
  9701. showToast('Error', err.message, 'error');
  9702. }
  9703. }
  9704. function applyOspfInstanceForm() {
  9705. submitOspfInstance(null);
  9706. }
  9707. function copyOspfInstance() {
  9708. document.getElementById('modal-ospf-inst-id').value = '';
  9709. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9710. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9711. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9712. }
  9713. async function deleteCurrentOspfInstance() {
  9714. const id = document.getElementById('modal-ospf-inst-id').value;
  9715. if (!id) return;
  9716. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9717. try {
  9718. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9719. if (res.ok) {
  9720. closeOspfInstanceModal();
  9721. showToast('Removed', 'OSPF instance deleted', 'success');
  9722. loadDynamicRouting();
  9723. }
  9724. } catch (err) {
  9725. showToast('Error', err.message, 'error');
  9726. }
  9727. }
  9728. async function enableSelectedOspfInstance() {
  9729. const id = state.selectedOspfRow?.instances;
  9730. if (!id) return;
  9731. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9732. method: 'POST',
  9733. headers: { 'Content-Type': 'application/json' },
  9734. body: JSON.stringify({ disabled: false })
  9735. });
  9736. loadDynamicRouting();
  9737. }
  9738. async function disableSelectedOspfInstance() {
  9739. const id = state.selectedOspfRow?.instances;
  9740. if (!id) return;
  9741. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9742. method: 'POST',
  9743. headers: { 'Content-Type': 'application/json' },
  9744. body: JSON.stringify({ disabled: true })
  9745. });
  9746. loadDynamicRouting();
  9747. }
  9748. async function removeSelectedOspfInstance() {
  9749. const id = state.selectedOspfRow?.instances;
  9750. if (!id) return;
  9751. if (!confirm('Delete selected OSPF instance?')) return;
  9752. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9753. loadDynamicRouting();
  9754. }
  9755. async function promptCommentOspfInstance() {
  9756. const id = state.selectedOspfRow?.instances;
  9757. if (!id) return;
  9758. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9759. if (!inst) return;
  9760. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9761. if (comment === null) return;
  9762. inst.comment = comment;
  9763. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9764. method: 'POST',
  9765. headers: { 'Content-Type': 'application/json' },
  9766. body: JSON.stringify(inst)
  9767. });
  9768. loadDynamicRouting();
  9769. }
  9770. // --- 2. OSPF AREA ---
  9771. function populateOspfAreaDropdowns() {
  9772. const instSelect = document.getElementById('modal-ospf-area-instance');
  9773. if (instSelect) {
  9774. const cur = instSelect.value;
  9775. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9776. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9777. if (cur) instSelect.value = cur;
  9778. }
  9779. }
  9780. function openOspfAreaModal(id = null) {
  9781. const isEdit = !!id;
  9782. populateOspfAreaDropdowns();
  9783. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9784. id: '',
  9785. name: 'Default',
  9786. instance: 'Default',
  9787. area_id: '0.0.0.0',
  9788. area_type: 'default',
  9789. default_cost: 1,
  9790. no_summaries: false,
  9791. disabled: false,
  9792. comment: ''
  9793. };
  9794. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9795. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9796. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9797. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9798. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9799. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9800. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9801. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9802. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9803. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9804. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9805. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9806. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9807. }
  9808. function openEditOspfAreaModal(id) {
  9809. openOspfAreaModal(id);
  9810. }
  9811. function closeOspfAreaModal() {
  9812. document.getElementById('ospf-area-modal').classList.add('hidden');
  9813. }
  9814. async function submitOspfArea(e) {
  9815. if (e) e.preventDefault();
  9816. const payload = {
  9817. id: document.getElementById('modal-ospf-area-id').value,
  9818. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9819. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9820. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9821. area_type: document.getElementById('modal-ospf-area-type').value,
  9822. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9823. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9824. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9825. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9826. };
  9827. try {
  9828. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9829. method: 'POST',
  9830. headers: { 'Content-Type': 'application/json' },
  9831. body: JSON.stringify(payload)
  9832. });
  9833. if (res.ok) {
  9834. closeOspfAreaModal();
  9835. showToast('Saved', 'OSPF area saved', 'success');
  9836. loadDynamicRouting();
  9837. } else {
  9838. const err = await res.json();
  9839. showToast('Error', err.error || 'Failed to save area', 'error');
  9840. }
  9841. } catch (err) {
  9842. showToast('Error', err.message, 'error');
  9843. }
  9844. }
  9845. function applyOspfAreaForm() {
  9846. submitOspfArea(null);
  9847. }
  9848. function copyOspfArea() {
  9849. document.getElementById('modal-ospf-area-id').value = '';
  9850. document.getElementById('modal-ospf-area-name').value += '-copy';
  9851. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9852. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9853. }
  9854. async function deleteCurrentOspfArea() {
  9855. const id = document.getElementById('modal-ospf-area-id').value;
  9856. if (!id) return;
  9857. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9858. try {
  9859. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9860. if (res.ok) {
  9861. closeOspfAreaModal();
  9862. showToast('Removed', 'OSPF area deleted', 'success');
  9863. loadDynamicRouting();
  9864. }
  9865. } catch (err) {
  9866. showToast('Error', err.message, 'error');
  9867. }
  9868. }
  9869. async function enableSelectedOspfArea() {
  9870. const id = state.selectedOspfRow?.areas;
  9871. if (!id) return;
  9872. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9873. method: 'POST',
  9874. headers: { 'Content-Type': 'application/json' },
  9875. body: JSON.stringify({ disabled: false })
  9876. });
  9877. loadDynamicRouting();
  9878. }
  9879. async function disableSelectedOspfArea() {
  9880. const id = state.selectedOspfRow?.areas;
  9881. if (!id) return;
  9882. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9883. method: 'POST',
  9884. headers: { 'Content-Type': 'application/json' },
  9885. body: JSON.stringify({ disabled: true })
  9886. });
  9887. loadDynamicRouting();
  9888. }
  9889. async function removeSelectedOspfArea() {
  9890. const id = state.selectedOspfRow?.areas;
  9891. if (!id) return;
  9892. if (!confirm('Delete selected OSPF area?')) return;
  9893. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9894. loadDynamicRouting();
  9895. }
  9896. async function promptCommentOspfArea() {
  9897. const id = state.selectedOspfRow?.areas;
  9898. if (!id) return;
  9899. const area = (state.ospfAreas || []).find(a => a.id === id);
  9900. if (!area) return;
  9901. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9902. if (comment === null) return;
  9903. area.comment = comment;
  9904. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9905. method: 'POST',
  9906. headers: { 'Content-Type': 'application/json' },
  9907. body: JSON.stringify(area)
  9908. });
  9909. loadDynamicRouting();
  9910. }
  9911. // --- 3. OSPF AREA RANGE ---
  9912. function populateAreaRangeDropdowns() {
  9913. const select = document.getElementById('modal-ospf-range-area');
  9914. if (select) {
  9915. const cur = select.value;
  9916. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9917. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9918. if (cur) select.value = cur;
  9919. }
  9920. }
  9921. function openOspfAreaRangeModal(id = null) {
  9922. const isEdit = !!id;
  9923. populateAreaRangeDropdowns();
  9924. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9925. id: '',
  9926. area: 'Default',
  9927. prefix: '',
  9928. cost: 1,
  9929. advertise: true,
  9930. disabled: false,
  9931. comment: ''
  9932. };
  9933. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9934. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9935. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9936. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9937. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9938. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9939. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9940. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9941. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9942. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9943. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9944. }
  9945. function openEditOspfAreaRangeModal(id) {
  9946. openOspfAreaRangeModal(id);
  9947. }
  9948. function closeOspfAreaRangeModal() {
  9949. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9950. }
  9951. async function submitOspfAreaRange(e) {
  9952. if (e) e.preventDefault();
  9953. const payload = {
  9954. id: document.getElementById('modal-ospf-range-id').value,
  9955. area: document.getElementById('modal-ospf-range-area').value,
  9956. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9957. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9958. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9959. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9960. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9961. };
  9962. try {
  9963. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9964. method: 'POST',
  9965. headers: { 'Content-Type': 'application/json' },
  9966. body: JSON.stringify(payload)
  9967. });
  9968. if (res.ok) {
  9969. closeOspfAreaRangeModal();
  9970. showToast('Saved', 'Area range saved', 'success');
  9971. loadDynamicRouting();
  9972. } else {
  9973. const err = await res.json();
  9974. showToast('Error', err.error || 'Failed to save area range', 'error');
  9975. }
  9976. } catch (err) {
  9977. showToast('Error', err.message, 'error');
  9978. }
  9979. }
  9980. function applyOspfAreaRangeForm() {
  9981. submitOspfAreaRange(null);
  9982. }
  9983. async function deleteCurrentOspfAreaRange() {
  9984. const id = document.getElementById('modal-ospf-range-id').value;
  9985. if (!id) return;
  9986. if (!confirm('Delete this area range?')) return;
  9987. try {
  9988. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9989. closeOspfAreaRangeModal();
  9990. showToast('Removed', 'Area range removed', 'success');
  9991. loadDynamicRouting();
  9992. } catch (err) {
  9993. showToast('Error', err.message, 'error');
  9994. }
  9995. }
  9996. async function enableSelectedOspfAreaRange() {
  9997. const id = state.selectedOspfRow?.['area-ranges'];
  9998. if (!id) return;
  9999. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10000. if (!r) return;
  10001. r.disabled = false;
  10002. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10003. loadDynamicRouting();
  10004. }
  10005. async function disableSelectedOspfAreaRange() {
  10006. const id = state.selectedOspfRow?.['area-ranges'];
  10007. if (!id) return;
  10008. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10009. if (!r) return;
  10010. r.disabled = true;
  10011. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10012. loadDynamicRouting();
  10013. }
  10014. async function removeSelectedOspfAreaRange() {
  10015. const id = state.selectedOspfRow?.['area-ranges'];
  10016. if (!id) return;
  10017. if (!confirm('Delete selected area range?')) return;
  10018. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10019. loadDynamicRouting();
  10020. }
  10021. async function promptCommentOspfAreaRange() {
  10022. const id = state.selectedOspfRow?.['area-ranges'];
  10023. if (!id) return;
  10024. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10025. if (!r) return;
  10026. const comment = prompt('Enter comment for area range:', r.comment || '');
  10027. if (comment === null) return;
  10028. r.comment = comment;
  10029. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10030. loadDynamicRouting();
  10031. }
  10032. // --- 4. OSPF INTERFACE TEMPLATE ---
  10033. function switchOspfTemplateTab(tab) {
  10034. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10035. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10036. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10037. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10038. if (tab === 'general') {
  10039. if (tabGen) tabGen.classList.remove('hidden');
  10040. if (tabAuth) tabAuth.classList.add('hidden');
  10041. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10042. 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';
  10043. } else {
  10044. if (tabGen) tabGen.classList.add('hidden');
  10045. if (tabAuth) tabAuth.classList.remove('hidden');
  10046. 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';
  10047. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10048. }
  10049. }
  10050. function populateTemplateAreaDropdowns() {
  10051. const select = document.getElementById('modal-ospf-tmpl-area');
  10052. if (select) {
  10053. const cur = select.value;
  10054. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10055. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10056. if (cur) select.value = cur;
  10057. }
  10058. }
  10059. function openOspfTemplateModal(id = null) {
  10060. const isEdit = !!id;
  10061. populateTemplateAreaDropdowns();
  10062. switchOspfTemplateTab('general');
  10063. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10064. id: '',
  10065. interfaces: '',
  10066. area: 'Default',
  10067. networks: '',
  10068. network_type: 'broadcast',
  10069. cost: 1,
  10070. priority: 128,
  10071. passive: false,
  10072. hello_interval: 10,
  10073. dead_interval: 40,
  10074. auth: 'none',
  10075. auth_key: '',
  10076. disabled: false,
  10077. comment: ''
  10078. };
  10079. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10080. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10081. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10082. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10083. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10084. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10085. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10086. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10087. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10088. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10089. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10090. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10091. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10092. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10093. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10094. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10095. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10096. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10097. }
  10098. function openEditOspfTemplateModal(id) {
  10099. openOspfTemplateModal(id);
  10100. }
  10101. function closeOspfTemplateModal() {
  10102. document.getElementById('ospf-template-modal').classList.add('hidden');
  10103. }
  10104. async function submitOspfTemplate(e) {
  10105. if (e) e.preventDefault();
  10106. const payload = {
  10107. id: document.getElementById('modal-ospf-tmpl-id').value,
  10108. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10109. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10110. area: document.getElementById('modal-ospf-tmpl-area').value,
  10111. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10112. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10113. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10114. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10115. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10116. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10117. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10118. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10119. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10120. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10121. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10122. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10123. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10124. };
  10125. try {
  10126. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10127. method: 'POST',
  10128. headers: { 'Content-Type': 'application/json' },
  10129. body: JSON.stringify(payload)
  10130. });
  10131. if (res.ok) {
  10132. closeOspfTemplateModal();
  10133. showToast('Saved', 'Interface template saved', 'success');
  10134. loadDynamicRouting();
  10135. } else {
  10136. const err = await res.json();
  10137. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10138. }
  10139. } catch (err) {
  10140. showToast('Error', err.message, 'error');
  10141. }
  10142. }
  10143. function applyOspfTemplateForm() {
  10144. submitOspfTemplate(null);
  10145. }
  10146. function copyOspfTemplate() {
  10147. document.getElementById('modal-ospf-tmpl-id').value = '';
  10148. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10149. showToast('Copied', 'Duplicated as new template', 'info');
  10150. }
  10151. async function deleteCurrentOspfTemplate() {
  10152. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10153. if (!id) return;
  10154. if (!confirm('Delete this interface template?')) return;
  10155. try {
  10156. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10157. closeOspfTemplateModal();
  10158. showToast('Removed', 'Interface template deleted', 'success');
  10159. loadDynamicRouting();
  10160. } catch (err) {
  10161. showToast('Error', err.message, 'error');
  10162. }
  10163. }
  10164. async function enableSelectedOspfTemplate() {
  10165. const id = state.selectedOspfRow?.templates;
  10166. if (!id) return;
  10167. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10168. method: 'POST',
  10169. headers: { 'Content-Type': 'application/json' },
  10170. body: JSON.stringify({ disabled: false })
  10171. });
  10172. loadDynamicRouting();
  10173. }
  10174. async function disableSelectedOspfTemplate() {
  10175. const id = state.selectedOspfRow?.templates;
  10176. if (!id) return;
  10177. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10178. method: 'POST',
  10179. headers: { 'Content-Type': 'application/json' },
  10180. body: JSON.stringify({ disabled: true })
  10181. });
  10182. loadDynamicRouting();
  10183. }
  10184. async function removeSelectedOspfTemplate() {
  10185. const id = state.selectedOspfRow?.templates;
  10186. if (!id) return;
  10187. if (!confirm('Delete selected interface template?')) return;
  10188. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10189. loadDynamicRouting();
  10190. }
  10191. async function promptCommentOspfTemplate() {
  10192. const id = state.selectedOspfRow?.templates;
  10193. if (!id) return;
  10194. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10195. if (!tmpl) return;
  10196. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10197. if (comment === null) return;
  10198. tmpl.comment = comment;
  10199. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10200. method: 'POST',
  10201. headers: { 'Content-Type': 'application/json' },
  10202. body: JSON.stringify(tmpl)
  10203. });
  10204. loadDynamicRouting();
  10205. }
  10206. // --- 5. OSPF STATIC NEIGHBOR ---
  10207. function populateStaticNbrAreaDropdowns() {
  10208. const select = document.getElementById('modal-ospf-snbr-area');
  10209. if (select) {
  10210. const cur = select.value;
  10211. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10212. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10213. if (cur) select.value = cur;
  10214. }
  10215. }
  10216. function openOspfStaticNbrModal(id = null) {
  10217. const isEdit = !!id;
  10218. populateStaticNbrAreaDropdowns();
  10219. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10220. id: '',
  10221. address: '',
  10222. area: 'Default',
  10223. poll_interval: 120,
  10224. cost: 1,
  10225. disabled: false,
  10226. comment: ''
  10227. };
  10228. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10229. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10230. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10231. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10232. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10233. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10234. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10235. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10236. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10237. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10238. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10239. }
  10240. function openEditOspfStaticNbrModal(id) {
  10241. openOspfStaticNbrModal(id);
  10242. }
  10243. function closeOspfStaticNbrModal() {
  10244. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10245. }
  10246. async function submitOspfStaticNbr(e) {
  10247. if (e) e.preventDefault();
  10248. const payload = {
  10249. id: document.getElementById('modal-ospf-snbr-id').value,
  10250. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10251. area: document.getElementById('modal-ospf-snbr-area').value,
  10252. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10253. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10254. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10255. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10256. };
  10257. try {
  10258. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10259. method: 'POST',
  10260. headers: { 'Content-Type': 'application/json' },
  10261. body: JSON.stringify(payload)
  10262. });
  10263. if (res.ok) {
  10264. closeOspfStaticNbrModal();
  10265. showToast('Saved', 'Static neighbor saved', 'success');
  10266. loadDynamicRouting();
  10267. } else {
  10268. const err = await res.json();
  10269. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10270. }
  10271. } catch (err) {
  10272. showToast('Error', err.message, 'error');
  10273. }
  10274. }
  10275. function applyOspfStaticNbrForm() {
  10276. submitOspfStaticNbr(null);
  10277. }
  10278. async function deleteCurrentOspfStaticNbr() {
  10279. const id = document.getElementById('modal-ospf-snbr-id').value;
  10280. if (!id) return;
  10281. if (!confirm('Delete this static neighbor?')) return;
  10282. try {
  10283. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10284. closeOspfStaticNbrModal();
  10285. showToast('Removed', 'Static neighbor removed', 'success');
  10286. loadDynamicRouting();
  10287. } catch (err) {
  10288. showToast('Error', err.message, 'error');
  10289. }
  10290. }
  10291. async function enableSelectedOspfStaticNbr() {
  10292. const id = state.selectedOspfRow?.['static-nbrs'];
  10293. if (!id) return;
  10294. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10295. if (!n) return;
  10296. n.disabled = false;
  10297. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10298. loadDynamicRouting();
  10299. }
  10300. async function disableSelectedOspfStaticNbr() {
  10301. const id = state.selectedOspfRow?.['static-nbrs'];
  10302. if (!id) return;
  10303. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10304. if (!n) return;
  10305. n.disabled = true;
  10306. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10307. loadDynamicRouting();
  10308. }
  10309. async function removeSelectedOspfStaticNbr() {
  10310. const id = state.selectedOspfRow?.['static-nbrs'];
  10311. if (!id) return;
  10312. if (!confirm('Delete selected static neighbor?')) return;
  10313. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10314. loadDynamicRouting();
  10315. }
  10316. async function promptCommentOspfStaticNbr() {
  10317. const id = state.selectedOspfRow?.['static-nbrs'];
  10318. if (!id) return;
  10319. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10320. if (!n) return;
  10321. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10322. if (comment === null) return;
  10323. n.comment = comment;
  10324. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10325. loadDynamicRouting();
  10326. }
  10327. // Backward-compat aliases
  10328. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10329. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10330. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10331. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10332. function deleteOspfInterface(id) {
  10333. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10334. }
  10335. function toggleOspfInterfaceState(id, disabled) {
  10336. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10337. method: 'POST',
  10338. headers: { 'Content-Type': 'application/json' },
  10339. body: JSON.stringify({ disabled })
  10340. }).then(() => loadDynamicRouting());
  10341. }
  10342. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10343. function deleteOspfArea(id) {
  10344. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10345. }
  10346. // ============================================================================
  10347. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10348. // ============================================================================
  10349. function switchBridgeSubTab(tab) {
  10350. state.bridgeSubTab = tab;
  10351. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10352. tabs.forEach(t => {
  10353. const panel = document.getElementById(`bridge-subtab-${t}`);
  10354. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10355. if (panel) {
  10356. if (t === tab) panel.classList.remove('hidden');
  10357. else panel.classList.add('hidden');
  10358. }
  10359. if (btn) {
  10360. if (t === tab) {
  10361. 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';
  10362. } else {
  10363. 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';
  10364. }
  10365. }
  10366. });
  10367. const addBtn = document.getElementById('bridge-top-action-btn');
  10368. if (addBtn) {
  10369. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10370. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10371. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10372. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10373. }
  10374. if (tab === 'hosts') loadBridgeHosts();
  10375. setTimeout(initTableSorting, 50);
  10376. }
  10377. function openCurrentBridgeModal() {
  10378. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10379. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10380. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10381. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10382. }
  10383. async function loadBridge() {
  10384. try {
  10385. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  10386. fetch(`${API_BASE}/bridge/bridges`),
  10387. fetch(`${API_BASE}/bridge/ports`),
  10388. fetch(`${API_BASE}/bridge/vlans`),
  10389. fetch(`${API_BASE}/bridge/summary`),
  10390. fetch(`${API_BASE}/vpn/eoip`),
  10391. fetch(`${API_BASE}/vlans`)
  10392. ]);
  10393. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10394. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10395. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10396. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10397. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10398. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10399. // Badges & Stats
  10400. const bBridges = document.getElementById('bridge-badge-bridges');
  10401. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10402. const bPorts = document.getElementById('bridge-badge-ports');
  10403. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10404. const bVlans = document.getElementById('bridge-badge-vlans');
  10405. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10406. const bHosts = document.getElementById('bridge-badge-hosts');
  10407. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10408. const sBr = document.getElementById('bridge-stat-bridges');
  10409. if (sBr) sBr.innerText = (state.bridges || []).length;
  10410. const sPorts = document.getElementById('bridge-stat-ports');
  10411. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10412. const sHosts = document.getElementById('bridge-stat-hosts');
  10413. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10414. renderBridges();
  10415. renderBridgePorts();
  10416. renderBridgeVLANs();
  10417. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10418. } catch (err) {
  10419. console.error('Failed to load bridge subsystem:', err);
  10420. }
  10421. }
  10422. // ----------------- Bridges -----------------
  10423. function renderBridges() {
  10424. const tbody = document.getElementById('bridge-table-body');
  10425. const empty = document.getElementById('bridge-empty-bridges');
  10426. const countBadge = document.getElementById('bridge-count-badge');
  10427. if (!tbody) return;
  10428. tbody.innerHTML = '';
  10429. const bridges = state.bridges || [];
  10430. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10431. if (bridges.length === 0) {
  10432. empty?.classList.remove('hidden');
  10433. return;
  10434. }
  10435. empty?.classList.add('hidden');
  10436. bridges.forEach((b, idx) => {
  10437. const tr = document.createElement('tr');
  10438. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10439. // Format IP addresses pill list
  10440. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10441. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10442. ipsHtml = b.ip_addresses.map(ip => `
  10443. <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">
  10444. <span>${ip}</span>
  10445. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10446. </span>
  10447. `).join(' ');
  10448. }
  10449. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10450. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10451. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10452. tr.innerHTML = `
  10453. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10454. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10455. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10456. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10457. </td>
  10458. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10459. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10460. <td class="py-2.5 px-3">
  10461. <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>
  10462. </td>
  10463. <td class="py-2.5 px-3 text-center">
  10464. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10465. </td>
  10466. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10467. <td class="py-2.5 px-3">
  10468. <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>
  10469. </td>
  10470. <td class="py-2.5 px-3">
  10471. <div class="flex items-center gap-1.5 flex-wrap">
  10472. ${ipsHtml}
  10473. <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>
  10474. </div>
  10475. </td>
  10476. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10477. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10478. </td>
  10479. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10480. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10481. <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>
  10482. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10483. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10484. </td>
  10485. `;
  10486. tbody.appendChild(tr);
  10487. });
  10488. }
  10489. function openAddBridgeModal() {
  10490. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10491. document.getElementById('bridge-modal-id').value = '';
  10492. document.getElementById('bridge-modal-name').value = 'bridge1';
  10493. document.getElementById('bridge-modal-name').disabled = false;
  10494. document.getElementById('bridge-modal-mtu').value = '1500';
  10495. document.getElementById('bridge-modal-mac').value = '';
  10496. document.getElementById('bridge-modal-stp').value = 'stp';
  10497. document.getElementById('bridge-modal-priority').value = '32768';
  10498. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10499. document.getElementById('bridge-modal-pvid').value = '1';
  10500. document.getElementById('bridge-modal-fastforward').checked = true;
  10501. document.getElementById('bridge-modal-comment').value = '';
  10502. document.getElementById('bridge-modal-disabled').checked = false;
  10503. toggleBridgeModalVlanFiltering();
  10504. document.getElementById('bridge-modal').classList.remove('hidden');
  10505. }
  10506. function openEditBridgeModal(id) {
  10507. const b = (state.bridges || []).find(x => x.id === id);
  10508. if (!b) return;
  10509. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10510. document.getElementById('bridge-modal-id').value = b.id;
  10511. document.getElementById('bridge-modal-name').value = b.name;
  10512. document.getElementById('bridge-modal-name').disabled = true;
  10513. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10514. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10515. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10516. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10517. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10518. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10519. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10520. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10521. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10522. toggleBridgeModalVlanFiltering();
  10523. document.getElementById('bridge-modal').classList.remove('hidden');
  10524. }
  10525. function closeBridgeModal() {
  10526. document.getElementById('bridge-modal').classList.add('hidden');
  10527. }
  10528. function toggleBridgeModalVlanFiltering() {
  10529. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10530. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10531. if (pvidBox) {
  10532. if (chk) pvidBox.classList.remove('opacity-40');
  10533. else pvidBox.classList.add('opacity-40');
  10534. }
  10535. }
  10536. async function submitSaveBridge(e) {
  10537. e.preventDefault();
  10538. const id = document.getElementById('bridge-modal-id').value;
  10539. const name = document.getElementById('bridge-modal-name').value.trim();
  10540. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10541. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10542. const stp = document.getElementById('bridge-modal-stp').value;
  10543. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10544. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10545. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10546. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10547. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10548. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10549. try {
  10550. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10551. method: 'POST',
  10552. headers: { 'Content-Type': 'application/json' },
  10553. body: JSON.stringify({
  10554. id,
  10555. name,
  10556. mtu,
  10557. mac_address: mac,
  10558. stp,
  10559. priority,
  10560. vlan_filtering: vlanFiltering,
  10561. pvid,
  10562. fast_forward: fastForward,
  10563. comment,
  10564. disabled
  10565. })
  10566. });
  10567. if (res.ok) {
  10568. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10569. closeBridgeModal();
  10570. loadBridge();
  10571. fetchData(false);
  10572. } else {
  10573. const err = await res.json();
  10574. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10575. }
  10576. } catch (err) {
  10577. showToast('Error', err.message, 'error');
  10578. }
  10579. }
  10580. async function toggleBridgeState(id, disabled) {
  10581. try {
  10582. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10583. method: 'POST',
  10584. headers: { 'Content-Type': 'application/json' },
  10585. body: JSON.stringify({ disabled })
  10586. });
  10587. if (res.ok) {
  10588. loadBridge();
  10589. fetchData(false);
  10590. }
  10591. } catch (err) {
  10592. showToast('Error', err.message, 'error');
  10593. }
  10594. }
  10595. async function deleteBridge(id) {
  10596. const b = (state.bridges || []).find(x => x.id === id);
  10597. const name = b ? b.name : id;
  10598. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10599. try {
  10600. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10601. if (res.ok) {
  10602. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10603. loadBridge();
  10604. fetchData(false);
  10605. } else {
  10606. const err = await res.json();
  10607. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10608. }
  10609. } catch (err) {
  10610. showToast('Error', err.message, 'error');
  10611. }
  10612. }
  10613. // ----------------- Bridge IP Assignments -----------------
  10614. function openAddBridgeIPModal(id, name) {
  10615. document.getElementById('bridge-ip-modal-id').value = id;
  10616. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10617. document.getElementById('bridge-ip-modal-cidr').value = '';
  10618. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10619. }
  10620. function closeBridgeIPModal() {
  10621. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10622. }
  10623. async function submitAddBridgeIP(e) {
  10624. e.preventDefault();
  10625. const id = document.getElementById('bridge-ip-modal-id').value;
  10626. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10627. try {
  10628. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10629. method: 'POST',
  10630. headers: { 'Content-Type': 'application/json' },
  10631. body: JSON.stringify({ ip })
  10632. });
  10633. if (res.ok) {
  10634. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10635. closeBridgeIPModal();
  10636. loadBridge();
  10637. fetchData(false);
  10638. } else {
  10639. const err = await res.json();
  10640. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10641. }
  10642. } catch (err) {
  10643. showToast('Error', err.message, 'error');
  10644. }
  10645. }
  10646. async function deleteBridgeIP(id, ip) {
  10647. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10648. try {
  10649. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10650. method: 'DELETE',
  10651. headers: { 'Content-Type': 'application/json' },
  10652. body: JSON.stringify({ ip })
  10653. });
  10654. if (res.ok) {
  10655. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10656. loadBridge();
  10657. fetchData(false);
  10658. }
  10659. } catch (err) {
  10660. showToast('Error', err.message, 'error');
  10661. }
  10662. }
  10663. // ----------------- Bridge Ports -----------------
  10664. function renderBridgePorts() {
  10665. const tbody = document.getElementById('bridge-ports-table-body');
  10666. const empty = document.getElementById('bridge-empty-ports');
  10667. const countBadge = document.getElementById('bridge-ports-count-badge');
  10668. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10669. if (!tbody) return;
  10670. tbody.innerHTML = '';
  10671. // Update filter select
  10672. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10673. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10674. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10675. if (ports.length === 0) {
  10676. empty?.classList.remove('hidden');
  10677. return;
  10678. }
  10679. empty?.classList.add('hidden');
  10680. ports.forEach((p, idx) => {
  10681. const tr = document.createElement('tr');
  10682. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10683. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10684. tr.innerHTML = `
  10685. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10686. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10687. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10688. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10689. </td>
  10690. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10691. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10692. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10693. <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>
  10694. <td class="py-2.5 px-3">
  10695. ${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>'}
  10696. </td>
  10697. <td class="py-2.5 px-3">
  10698. <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>
  10699. </td>
  10700. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10701. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10702. <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>
  10703. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10704. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10705. </td>
  10706. `;
  10707. tbody.appendChild(tr);
  10708. });
  10709. }
  10710. function openAddBridgePortModal() {
  10711. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10712. document.getElementById('bridge-port-modal-id').value = '';
  10713. populateBridgeSelect('bridge-port-modal-bridge');
  10714. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10715. document.getElementById('bridge-port-modal-pvid').value = '1';
  10716. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10717. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10718. document.getElementById('bridge-port-modal-horizon').value = '0';
  10719. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10720. document.getElementById('bridge-port-modal-priority').value = '128';
  10721. document.getElementById('bridge-port-modal-learn').checked = true;
  10722. document.getElementById('bridge-port-modal-comment').value = '';
  10723. document.getElementById('bridge-port-modal-disabled').checked = false;
  10724. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10725. }
  10726. function openEditBridgePortModal(id) {
  10727. const p = (state.bridgePorts || []).find(x => x.id === id);
  10728. if (!p) return;
  10729. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10730. document.getElementById('bridge-port-modal-id').value = p.id;
  10731. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10732. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10733. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10734. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10735. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10736. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10737. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10738. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10739. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10740. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10741. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10742. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10743. }
  10744. function closeBridgePortModal() {
  10745. document.getElementById('bridge-port-modal').classList.add('hidden');
  10746. }
  10747. async function submitSaveBridgePort(e) {
  10748. e.preventDefault();
  10749. const id = document.getElementById('bridge-port-modal-id').value;
  10750. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10751. const iface = document.getElementById('bridge-port-modal-interface').value;
  10752. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10753. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10754. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10755. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10756. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10757. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10758. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10759. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10760. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10761. try {
  10762. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10763. method: 'POST',
  10764. headers: { 'Content-Type': 'application/json' },
  10765. body: JSON.stringify({
  10766. id,
  10767. bridge,
  10768. interface: iface,
  10769. pvid,
  10770. frame_types: frameTypes,
  10771. ingress_filtering: ingressFiltering,
  10772. horizon,
  10773. path_cost: pathCost,
  10774. priority,
  10775. learn,
  10776. comment,
  10777. disabled
  10778. })
  10779. });
  10780. if (res.ok) {
  10781. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10782. closeBridgePortModal();
  10783. loadBridge();
  10784. fetchData(false);
  10785. } else {
  10786. const err = await res.json();
  10787. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10788. }
  10789. } catch (err) {
  10790. showToast('Error', err.message, 'error');
  10791. }
  10792. }
  10793. async function toggleBridgePortState(id, disabled) {
  10794. try {
  10795. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10796. method: 'POST',
  10797. headers: { 'Content-Type': 'application/json' },
  10798. body: JSON.stringify({ disabled })
  10799. });
  10800. if (res.ok) {
  10801. loadBridge();
  10802. fetchData(false);
  10803. }
  10804. } catch (err) {
  10805. showToast('Error', err.message, 'error');
  10806. }
  10807. }
  10808. async function deleteBridgePort(id) {
  10809. const p = (state.bridgePorts || []).find(x => x.id === id);
  10810. const iface = p ? p.interface : id;
  10811. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10812. try {
  10813. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10814. if (res.ok) {
  10815. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10816. loadBridge();
  10817. fetchData(false);
  10818. }
  10819. } catch (err) {
  10820. showToast('Error', err.message, 'error');
  10821. }
  10822. }
  10823. // ----------------- Bridge VLANs -----------------
  10824. function renderBridgeVLANs() {
  10825. const tbody = document.getElementById('bridge-vlans-table-body');
  10826. const empty = document.getElementById('bridge-empty-vlans');
  10827. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10828. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10829. if (!tbody) return;
  10830. tbody.innerHTML = '';
  10831. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10832. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10833. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10834. if (vlans.length === 0) {
  10835. empty?.classList.remove('hidden');
  10836. return;
  10837. }
  10838. empty?.classList.add('hidden');
  10839. vlans.forEach((v, idx) => {
  10840. const tr = document.createElement('tr');
  10841. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10842. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10843. ? 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(' ')
  10844. : '<span class="text-slate-600">none</span>';
  10845. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10846. ? 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(' ')
  10847. : '<span class="text-slate-600">none</span>';
  10848. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10849. tr.innerHTML = `
  10850. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10851. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10852. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10853. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10854. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10855. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10856. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10857. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10858. <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>
  10859. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10860. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10861. </td>
  10862. `;
  10863. tbody.appendChild(tr);
  10864. });
  10865. }
  10866. function openAddBridgeVLANModal() {
  10867. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10868. document.getElementById('bridge-vlan-modal-id').value = '';
  10869. populateBridgeSelect('bridge-vlan-modal-bridge');
  10870. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10871. document.getElementById('bridge-vlan-modal-comment').value = '';
  10872. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10873. updateBridgeVlanPortCheckboxes();
  10874. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10875. }
  10876. function openEditBridgeVLANModal(id) {
  10877. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10878. if (!v) return;
  10879. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10880. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10881. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10882. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10883. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10884. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10885. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10886. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10887. }
  10888. function closeBridgeVlanModal() {
  10889. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10890. }
  10891. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10892. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10893. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10894. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10895. if (!taggedBox || !untaggedBox) return;
  10896. // Ports belonging to the selected bridge
  10897. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10898. if (memberPorts.length === 0) {
  10899. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10900. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10901. return;
  10902. }
  10903. taggedBox.innerHTML = memberPorts.map(p => `
  10904. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10905. <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">
  10906. <span>${p.interface}</span>
  10907. </label>
  10908. `).join('');
  10909. untaggedBox.innerHTML = memberPorts.map(p => `
  10910. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10911. <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">
  10912. <span>${p.interface}</span>
  10913. </label>
  10914. `).join('');
  10915. }
  10916. async function submitSaveBridgeVLAN(e) {
  10917. e.preventDefault();
  10918. const id = document.getElementById('bridge-vlan-modal-id').value;
  10919. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10920. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10921. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10922. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10923. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10924. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10925. try {
  10926. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10927. method: 'POST',
  10928. headers: { 'Content-Type': 'application/json' },
  10929. body: JSON.stringify({
  10930. id,
  10931. bridge,
  10932. vlan_ids: vlanIDs,
  10933. tagged,
  10934. untagged,
  10935. comment,
  10936. disabled
  10937. })
  10938. });
  10939. if (res.ok) {
  10940. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10941. closeBridgeVlanModal();
  10942. loadBridge();
  10943. } else {
  10944. const err = await res.json();
  10945. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10946. }
  10947. } catch (err) {
  10948. showToast('Error', err.message, 'error');
  10949. }
  10950. }
  10951. async function toggleBridgeVLANState(id, disabled) {
  10952. try {
  10953. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10954. method: 'POST',
  10955. headers: { 'Content-Type': 'application/json' },
  10956. body: JSON.stringify({ disabled })
  10957. });
  10958. if (res.ok) loadBridge();
  10959. } catch (err) {
  10960. showToast('Error', err.message, 'error');
  10961. }
  10962. }
  10963. async function deleteBridgeVLAN(id) {
  10964. if (!confirm('Delete this bridge VLAN entry?')) return;
  10965. try {
  10966. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10967. if (res.ok) {
  10968. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10969. loadBridge();
  10970. }
  10971. } catch (err) {
  10972. showToast('Error', err.message, 'error');
  10973. }
  10974. }
  10975. // ----------------- Hosts / MAC Table -----------------
  10976. async function loadBridgeHosts() {
  10977. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10978. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10979. try {
  10980. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10981. const res = await fetch(url);
  10982. if (res.ok) {
  10983. state.bridgeHosts = await res.json();
  10984. renderBridgeHosts();
  10985. }
  10986. } catch (err) {
  10987. console.error('Failed to load bridge hosts:', err);
  10988. }
  10989. }
  10990. function renderBridgeHosts() {
  10991. const tbody = document.getElementById('bridge-hosts-table-body');
  10992. const empty = document.getElementById('bridge-empty-hosts');
  10993. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10994. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10995. if (!tbody) return;
  10996. tbody.innerHTML = '';
  10997. const hosts = (state.bridgeHosts || []).filter(h => {
  10998. if (!search) return true;
  10999. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11000. });
  11001. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11002. if (hosts.length === 0) {
  11003. empty?.classList.remove('hidden');
  11004. return;
  11005. }
  11006. empty?.classList.add('hidden');
  11007. hosts.forEach(h => {
  11008. const tr = document.createElement('tr');
  11009. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11010. let flagBadges = '';
  11011. 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>';
  11012. 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>';
  11013. 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>';
  11014. tr.innerHTML = `
  11015. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11016. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11017. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11018. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11019. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11020. <td class="py-2.5 px-3">${flagBadges}</td>
  11021. `;
  11022. tbody.appendChild(tr);
  11023. });
  11024. }
  11025. async function flushBridgeHosts() {
  11026. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11027. if (!selBridge) {
  11028. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11029. return;
  11030. }
  11031. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11032. try {
  11033. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11034. method: 'POST',
  11035. headers: { 'Content-Type': 'application/json' },
  11036. body: JSON.stringify({ bridge: selBridge })
  11037. });
  11038. if (res.ok) {
  11039. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11040. loadBridgeHosts();
  11041. }
  11042. } catch (err) {
  11043. showToast('Error', err.message, 'error');
  11044. }
  11045. }
  11046. // ----------------- Helpers -----------------
  11047. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11048. const sel = document.getElementById(selectId);
  11049. if (!sel) return;
  11050. const prevVal = currentVal || sel.value;
  11051. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11052. (state.bridges || []).forEach(b => {
  11053. const opt = document.createElement('option');
  11054. opt.value = b.name;
  11055. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11056. if (b.name === prevVal) opt.selected = true;
  11057. sel.appendChild(opt);
  11058. });
  11059. }
  11060. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11061. const sel = document.getElementById(selectId);
  11062. if (!sel) return;
  11063. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11064. // 1. Physical Interfaces
  11065. const grpPhys = document.createElement('optgroup');
  11066. grpPhys.label = 'Physical Interfaces';
  11067. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11068. const opt = document.createElement('option');
  11069. opt.value = i.name;
  11070. opt.innerText = `${i.name} (${i.role || i.type})`;
  11071. if (i.name === currentVal) opt.selected = true;
  11072. grpPhys.appendChild(opt);
  11073. });
  11074. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11075. // 2. VLAN Sub-interfaces
  11076. const grpVlans = document.createElement('optgroup');
  11077. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11078. (state.vlans || []).forEach(v => {
  11079. const opt = document.createElement('option');
  11080. opt.value = v.name;
  11081. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11082. if (v.name === currentVal) opt.selected = true;
  11083. grpVlans.appendChild(opt);
  11084. });
  11085. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11086. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11087. const grpEoip = document.createElement('optgroup');
  11088. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11089. (state.eoipTunnels || []).forEach(t => {
  11090. const opt = document.createElement('option');
  11091. opt.value = t.name;
  11092. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11093. if (t.name === currentVal) opt.selected = true;
  11094. grpEoip.appendChild(opt);
  11095. });
  11096. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11097. }
  11098. // -------------------------------------------------------------
  11099. // DebTik Routing Filters Management (/routing filter)
  11100. // -------------------------------------------------------------
  11101. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11102. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11103. if (!state.rfSort) state.rfSort = {};
  11104. function switchRoutingFilterTab(tab) {
  11105. state.activeRoutingFilterTab = tab;
  11106. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  11107. tabs.forEach(t => {
  11108. const btn = document.getElementById(`tab-rf-${t}`);
  11109. const content = document.getElementById(`tab-content-rf-${t}`);
  11110. if (btn) {
  11111. if (t === tab) {
  11112. 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';
  11113. } else {
  11114. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11115. }
  11116. }
  11117. if (content) {
  11118. if (t === tab) content.classList.remove('hidden');
  11119. else content.classList.add('hidden');
  11120. }
  11121. });
  11122. const chainContainer = document.getElementById('rf-chain-filter-container');
  11123. if (chainContainer) {
  11124. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  11125. else chainContainer.classList.add('hidden');
  11126. }
  11127. renderRoutingFilters();
  11128. }
  11129. function selectFilterRow(tab, id) {
  11130. if (state.selectedFilterRow[tab] === id) {
  11131. delete state.selectedFilterRow[tab];
  11132. } else {
  11133. state.selectedFilterRow[tab] = id;
  11134. }
  11135. if (tab === 'rules') renderRoutingFilterRules();
  11136. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  11137. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11138. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11139. }
  11140. function openRoutingFilterNewModal() {
  11141. const tab = state.activeRoutingFilterTab || 'rules';
  11142. if (tab === 'rules') openAddRoutingFilterModal();
  11143. else if (tab === 'select-rules') openAddSelectRuleModal();
  11144. else if (tab === 'community-lists') openAddCommunityListModal();
  11145. else if (tab === 'as-lists') openAddASListModal();
  11146. }
  11147. function toggleSelectedRoutingFilter(disabled) {
  11148. const tab = state.activeRoutingFilterTab || 'rules';
  11149. const id = state.selectedFilterRow[tab];
  11150. if (!id) {
  11151. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11152. return;
  11153. }
  11154. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11155. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  11156. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11157. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11158. }
  11159. function removeSelectedRoutingFilter() {
  11160. const tab = state.activeRoutingFilterTab || 'rules';
  11161. const id = state.selectedFilterRow[tab];
  11162. if (!id) {
  11163. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11164. return;
  11165. }
  11166. if (tab === 'rules') deleteRoutingFilter(id);
  11167. else if (tab === 'select-rules') deleteSelectRule(id);
  11168. else if (tab === 'community-lists') deleteCommunityList(id);
  11169. else if (tab === 'as-lists') deleteASList(id);
  11170. }
  11171. function searchRoutingFilters(q) {
  11172. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11173. renderRoutingFilters();
  11174. }
  11175. function sortFilterTable(tab, col) {
  11176. if (!state.rfSort) state.rfSort = {};
  11177. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11178. if (state.rfSort[tab].col === col) {
  11179. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11180. } else {
  11181. state.rfSort[tab].col = col;
  11182. state.rfSort[tab].asc = true;
  11183. }
  11184. const asc = state.rfSort[tab].asc;
  11185. let list = [];
  11186. if (tab === 'rules') list = state.routingFilters || [];
  11187. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  11188. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11189. else if (tab === 'as-lists') list = state.routingASLists || [];
  11190. list.sort((a, b) => {
  11191. let valA = a[col] ?? '';
  11192. let valB = b[col] ?? '';
  11193. if (col === 'flags') {
  11194. valA = a.disabled ? 'X' : 'A';
  11195. valB = b.disabled ? 'X' : 'A';
  11196. }
  11197. if (typeof valA === 'number' && typeof valB === 'number') {
  11198. return asc ? valA - valB : valB - valA;
  11199. }
  11200. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11201. });
  11202. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11203. allCols.forEach(c => {
  11204. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11205. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11206. });
  11207. if (tab === 'rules') renderRoutingFilterRules();
  11208. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  11209. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11210. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11211. }
  11212. function renderRoutingFilters() {
  11213. const navBadge = document.getElementById('badge-filters-count');
  11214. const allRules = state.routingFilters || [];
  11215. if (navBadge) navBadge.innerText = allRules.length;
  11216. // Populate chain filter select options and datalist
  11217. const chainSelect = document.getElementById('routing-filter-chain-select');
  11218. const chainDatalist = document.getElementById('dl-routing-chains');
  11219. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11220. if (chainSelect) {
  11221. const currentVal = state.filterChainSelected || 'all';
  11222. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11223. uniqueChains.map(ch => {
  11224. const count = allRules.filter(r => r.chain === ch).length;
  11225. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11226. }).join('');
  11227. chainSelect.value = currentVal;
  11228. }
  11229. if (chainDatalist) {
  11230. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11231. }
  11232. renderRoutingFilterRules();
  11233. renderRoutingFilterSelectRules();
  11234. renderRoutingFilterCommunityLists();
  11235. renderRoutingFilterASLists();
  11236. }
  11237. function filterRoutingFiltersByChain(chain) {
  11238. state.filterChainSelected = chain;
  11239. renderRoutingFilters();
  11240. }
  11241. // -------------------------------------------------------------
  11242. // TAB 1: RULES (/routing filter rule)
  11243. // -------------------------------------------------------------
  11244. function renderRoutingFilterRules() {
  11245. const tbody = document.getElementById('routing-filter-rules-tbody');
  11246. if (!tbody) return;
  11247. const empty = document.getElementById('rf-rules-empty');
  11248. const statusCount = document.getElementById('rf-status-count');
  11249. let list = (state.routingFilters || []).slice();
  11250. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11251. list = list.filter(r => r.chain === state.filterChainSelected);
  11252. }
  11253. const q = state.rfSearchQuery;
  11254. if (q) {
  11255. list = list.filter(r =>
  11256. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11257. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11258. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11259. (r.comment && r.comment.toLowerCase().includes(q))
  11260. );
  11261. }
  11262. if (!state.rfSort?.['rules']) {
  11263. list.sort((a, b) => {
  11264. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11265. return (a.rule_order || 0) - (b.rule_order || 0);
  11266. });
  11267. }
  11268. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11269. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11270. }
  11271. if (list.length === 0) {
  11272. tbody.innerHTML = '';
  11273. if (empty) empty.classList.remove('hidden');
  11274. return;
  11275. }
  11276. if (empty) empty.classList.add('hidden');
  11277. tbody.innerHTML = list.map(r => {
  11278. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11279. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11280. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11281. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11282. let ruleDisplay = '';
  11283. if (r.rule && r.rule.trim() !== '') {
  11284. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11285. } else {
  11286. let conds = [];
  11287. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11288. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11289. let act = r.action || 'accept';
  11290. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11291. }
  11292. return `
  11293. <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'}">
  11294. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11295. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11296. <td class="py-2 px-3">
  11297. <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>
  11298. </td>
  11299. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11300. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11301. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11302. <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>
  11303. <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>
  11304. <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'}">
  11305. ${r.disabled ? 'Enable' : 'Disable'}
  11306. </button>
  11307. <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">
  11308. Edit
  11309. </button>
  11310. <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">
  11311. ✕
  11312. </button>
  11313. </td>
  11314. </tr>
  11315. `;
  11316. }).join('');
  11317. }
  11318. // -------------------------------------------------------------
  11319. // TAB 2: SELECT RULES (/routing filter select-rule)
  11320. // -------------------------------------------------------------
  11321. function renderRoutingFilterSelectRules() {
  11322. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  11323. if (!tbody) return;
  11324. const empty = document.getElementById('rf-select-rules-empty');
  11325. const statusCount = document.getElementById('rf-status-count');
  11326. let list = (state.routingSelectRules || []).slice();
  11327. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11328. list = list.filter(r => r.chain === state.filterChainSelected);
  11329. }
  11330. const q = state.rfSearchQuery;
  11331. if (q) {
  11332. list = list.filter(r =>
  11333. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11334. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11335. (r.comment && r.comment.toLowerCase().includes(q))
  11336. );
  11337. }
  11338. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  11339. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11340. }
  11341. if (list.length === 0) {
  11342. tbody.innerHTML = '';
  11343. if (empty) empty.classList.remove('hidden');
  11344. return;
  11345. }
  11346. if (empty) empty.classList.add('hidden');
  11347. tbody.innerHTML = list.map(r => {
  11348. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  11349. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11350. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11351. return `
  11352. <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'}">
  11353. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11354. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11355. <td class="py-2 px-3">
  11356. <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>
  11357. </td>
  11358. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  11359. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11360. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11361. <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'}">
  11362. ${r.disabled ? 'Enable' : 'Disable'}
  11363. </button>
  11364. <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">
  11365. Edit
  11366. </button>
  11367. <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">
  11368. ✕
  11369. </button>
  11370. </td>
  11371. </tr>
  11372. `;
  11373. }).join('');
  11374. }
  11375. // -------------------------------------------------------------
  11376. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  11377. // -------------------------------------------------------------
  11378. function renderRoutingFilterCommunityLists() {
  11379. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11380. if (!tbody) return;
  11381. const empty = document.getElementById('rf-comm-lists-empty');
  11382. const statusCount = document.getElementById('rf-status-count');
  11383. let list = (state.routingCommunityLists || []).slice();
  11384. const q = state.rfSearchQuery;
  11385. if (q) {
  11386. list = list.filter(cl =>
  11387. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11388. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11389. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11390. );
  11391. }
  11392. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11393. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11394. }
  11395. if (list.length === 0) {
  11396. tbody.innerHTML = '';
  11397. if (empty) empty.classList.remove('hidden');
  11398. return;
  11399. }
  11400. if (empty) empty.classList.add('hidden');
  11401. tbody.innerHTML = list.map(cl => {
  11402. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11403. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11404. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11405. const commBadges = (cl.communities || []).map(c =>
  11406. `<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>`
  11407. ).join(' ');
  11408. return `
  11409. <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'}">
  11410. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11411. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11412. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11413. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11414. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11415. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11416. <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'}">
  11417. ${cl.disabled ? 'Enable' : 'Disable'}
  11418. </button>
  11419. <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">
  11420. Edit
  11421. </button>
  11422. <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">
  11423. ✕
  11424. </button>
  11425. </td>
  11426. </tr>
  11427. `;
  11428. }).join('');
  11429. }
  11430. // -------------------------------------------------------------
  11431. // TAB 4: AS LISTS (/routing filter num-list)
  11432. // -------------------------------------------------------------
  11433. function renderRoutingFilterASLists() {
  11434. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11435. if (!tbody) return;
  11436. const empty = document.getElementById('rf-as-lists-empty');
  11437. const statusCount = document.getElementById('rf-status-count');
  11438. let list = (state.routingASLists || []).slice();
  11439. const q = state.rfSearchQuery;
  11440. if (q) {
  11441. list = list.filter(al =>
  11442. (al.name && al.name.toLowerCase().includes(q)) ||
  11443. (al.range && al.range.toLowerCase().includes(q)) ||
  11444. (al.comment && al.comment.toLowerCase().includes(q))
  11445. );
  11446. }
  11447. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11448. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11449. }
  11450. if (list.length === 0) {
  11451. tbody.innerHTML = '';
  11452. if (empty) empty.classList.remove('hidden');
  11453. return;
  11454. }
  11455. if (empty) empty.classList.add('hidden');
  11456. tbody.innerHTML = list.map(al => {
  11457. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11458. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11459. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11460. return `
  11461. <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'}">
  11462. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11463. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11464. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11465. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11466. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11467. <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'}">
  11468. ${al.disabled ? 'Enable' : 'Disable'}
  11469. </button>
  11470. <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">
  11471. Edit
  11472. </button>
  11473. <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">
  11474. ✕
  11475. </button>
  11476. </td>
  11477. </tr>
  11478. `;
  11479. }).join('');
  11480. }
  11481. // -------------------------------------------------------------
  11482. // SNIPPETS & WIZARD HELPERS
  11483. // -------------------------------------------------------------
  11484. function insertRuleSnippet(type) {
  11485. const textarea = document.getElementById('modal-rf-rule');
  11486. if (!textarea) return;
  11487. let snippet = '';
  11488. switch (type) {
  11489. case 'accept-default':
  11490. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11491. break;
  11492. case 'drop-rfc1918':
  11493. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11494. break;
  11495. case 'len-24':
  11496. snippet = 'if (dst-len > 24) { reject; }';
  11497. break;
  11498. case 'local-pref-150':
  11499. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11500. break;
  11501. case 'as-prepend-2':
  11502. snippet = 'set bgp-path-prepend 2; accept;';
  11503. break;
  11504. case 'set-comm':
  11505. snippet = 'set bgp-communities.add 65000:100; accept;';
  11506. break;
  11507. case 'match-comm':
  11508. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11509. break;
  11510. case 'reject-all':
  11511. snippet = 'reject;';
  11512. break;
  11513. }
  11514. if (!snippet) return;
  11515. if (!textarea.value.trim()) {
  11516. textarea.value = snippet;
  11517. } else {
  11518. textarea.value = textarea.value.trim() + '\n' + snippet;
  11519. }
  11520. }
  11521. function generateScriptFromWizard() {
  11522. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11523. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11524. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11525. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11526. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11527. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11528. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11529. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11530. const conds = [];
  11531. if (pfx) {
  11532. if (pfxLen) {
  11533. if (pfxLen.includes('-')) {
  11534. const parts = pfxLen.split('-');
  11535. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11536. } else {
  11537. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11538. }
  11539. } else {
  11540. conds.push(`dst in ${pfx}`);
  11541. }
  11542. }
  11543. if (proto && proto !== 'any') {
  11544. conds.push(`protocol ${proto}`);
  11545. }
  11546. if (asp) {
  11547. conds.push(`bgp-as-path "${asp}"`);
  11548. }
  11549. if (comm) {
  11550. conds.push(`bgp-communities includes ${comm}`);
  11551. }
  11552. const actions = [];
  11553. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11554. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11555. actions.push(`${act};`);
  11556. let code = '';
  11557. if (conds.length > 0) {
  11558. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11559. } else {
  11560. code = actions.join(' ');
  11561. }
  11562. const textarea = document.getElementById('modal-rf-rule');
  11563. if (textarea) textarea.value = code;
  11564. }
  11565. // -------------------------------------------------------------
  11566. // MODAL CRUD: RULES (/routing filter rule)
  11567. // -------------------------------------------------------------
  11568. function openAddRoutingFilterModal(defaultChain = '') {
  11569. const form = document.getElementById('routing-filter-form');
  11570. if (form) form.reset();
  11571. const idEl = document.getElementById('modal-rf-id');
  11572. if (idEl) idEl.value = '';
  11573. const titleEl = document.getElementById('modal-rf-title');
  11574. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11575. const chainEl = document.getElementById('modal-rf-chain');
  11576. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11577. const orderEl = document.getElementById('modal-rf-order');
  11578. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11579. const ruleEl = document.getElementById('modal-rf-rule');
  11580. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11581. const disEl = document.getElementById('modal-rf-disabled');
  11582. if (disEl) disEl.checked = false;
  11583. const modal = document.getElementById('modal-routing-filter');
  11584. if (modal) modal.classList.remove('hidden');
  11585. }
  11586. function openEditRoutingFilterModal(id) {
  11587. const r = (state.routingFilters || []).find(item => item.id === id);
  11588. if (!r) return;
  11589. const idEl = document.getElementById('modal-rf-id');
  11590. if (idEl) idEl.value = r.id;
  11591. const titleEl = document.getElementById('modal-rf-title');
  11592. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11593. const chainEl = document.getElementById('modal-rf-chain');
  11594. if (chainEl) chainEl.value = r.chain || '';
  11595. const orderEl = document.getElementById('modal-rf-order');
  11596. if (orderEl) orderEl.value = r.rule_order || 10;
  11597. const ruleEl = document.getElementById('modal-rf-rule');
  11598. if (ruleEl) {
  11599. if (r.rule) {
  11600. ruleEl.value = r.rule;
  11601. } else {
  11602. let conds = [];
  11603. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11604. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11605. let act = r.action || 'accept';
  11606. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11607. }
  11608. }
  11609. const comEl = document.getElementById('modal-rf-comment');
  11610. if (comEl) comEl.value = r.comment || '';
  11611. const disEl = document.getElementById('modal-rf-disabled');
  11612. if (disEl) disEl.checked = !!r.disabled;
  11613. const modal = document.getElementById('modal-routing-filter');
  11614. if (modal) modal.classList.remove('hidden');
  11615. }
  11616. function closeRoutingFilterModal() {
  11617. const modal = document.getElementById('modal-routing-filter');
  11618. if (modal) modal.classList.add('hidden');
  11619. }
  11620. async function submitRoutingFilter(e) {
  11621. if (e) e.preventDefault();
  11622. const payload = {
  11623. id: document.getElementById('modal-rf-id').value,
  11624. chain: document.getElementById('modal-rf-chain').value.trim(),
  11625. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11626. rule: document.getElementById('modal-rf-rule').value.trim(),
  11627. comment: document.getElementById('modal-rf-comment').value.trim(),
  11628. disabled: document.getElementById('modal-rf-disabled').checked
  11629. };
  11630. try {
  11631. const res = await fetch(`${API_BASE}/routing/filters`, {
  11632. method: 'POST',
  11633. headers: { 'Content-Type': 'application/json' },
  11634. body: JSON.stringify(payload)
  11635. });
  11636. if (res.ok) {
  11637. closeRoutingFilterModal();
  11638. showToast('Success', 'Routing filter rule saved', 'success');
  11639. loadDynamicRouting();
  11640. } else {
  11641. const err = await res.json();
  11642. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11643. }
  11644. } catch (err) {
  11645. showToast('Error', err.message, 'error');
  11646. }
  11647. }
  11648. async function applyRoutingFilterForm() {
  11649. const payload = {
  11650. id: document.getElementById('modal-rf-id').value,
  11651. chain: document.getElementById('modal-rf-chain').value.trim(),
  11652. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11653. rule: document.getElementById('modal-rf-rule').value.trim(),
  11654. comment: document.getElementById('modal-rf-comment').value.trim(),
  11655. disabled: document.getElementById('modal-rf-disabled').checked
  11656. };
  11657. try {
  11658. const res = await fetch(`${API_BASE}/routing/filters`, {
  11659. method: 'POST',
  11660. headers: { 'Content-Type': 'application/json' },
  11661. body: JSON.stringify(payload)
  11662. });
  11663. if (res.ok) {
  11664. const data = await res.json();
  11665. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11666. showToast('Applied', 'Routing filter configuration applied', 'success');
  11667. loadDynamicRouting();
  11668. } else {
  11669. const err = await res.json();
  11670. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11671. }
  11672. } catch (err) {
  11673. showToast('Error', err.message, 'error');
  11674. }
  11675. }
  11676. async function moveRoutingFilterOrder(id, delta) {
  11677. const list = state.routingFilters || [];
  11678. const idx = list.findIndex(r => r.id === id);
  11679. if (idx < 0) return;
  11680. const targetIdx = idx + delta;
  11681. if (targetIdx < 0 || targetIdx >= list.length) return;
  11682. const currentOrder = list[idx].rule_order || 10;
  11683. const targetOrder = list[targetIdx].rule_order || 20;
  11684. list[idx].rule_order = targetOrder;
  11685. list[targetIdx].rule_order = currentOrder;
  11686. try {
  11687. await fetch(`${API_BASE}/routing/filters`, {
  11688. method: 'POST',
  11689. headers: { 'Content-Type': 'application/json' },
  11690. body: JSON.stringify(list[idx])
  11691. });
  11692. await fetch(`${API_BASE}/routing/filters`, {
  11693. method: 'POST',
  11694. headers: { 'Content-Type': 'application/json' },
  11695. body: JSON.stringify(list[targetIdx])
  11696. });
  11697. loadDynamicRouting();
  11698. } catch (e) {
  11699. console.error('Reorder error:', e);
  11700. }
  11701. }
  11702. async function deleteRoutingFilter(id) {
  11703. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11704. try {
  11705. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11706. if (res.ok) {
  11707. showToast('Deleted', 'Routing filter rule removed', 'info');
  11708. loadDynamicRouting();
  11709. } else {
  11710. const err = await res.json();
  11711. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11712. }
  11713. } catch (err) {
  11714. showToast('Error', err.message, 'error');
  11715. }
  11716. }
  11717. async function toggleRoutingFilterState(id, disabled) {
  11718. try {
  11719. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11720. method: 'POST',
  11721. headers: { 'Content-Type': 'application/json' },
  11722. body: JSON.stringify({ disabled })
  11723. });
  11724. if (res.ok) {
  11725. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11726. loadDynamicRouting();
  11727. } else {
  11728. const err = await res.json();
  11729. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11730. }
  11731. } catch (err) {
  11732. showToast('Error', err.message, 'error');
  11733. }
  11734. }
  11735. // -------------------------------------------------------------
  11736. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11737. // -------------------------------------------------------------
  11738. function openAddSelectRuleModal() {
  11739. document.getElementById('modal-rf-sr-id').value = '';
  11740. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11741. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11742. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11743. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11744. document.getElementById('modal-rf-sr-comment').value = '';
  11745. document.getElementById('modal-rf-sr-disabled').checked = false;
  11746. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11747. }
  11748. function openEditSelectRuleModal(id) {
  11749. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11750. if (!r) return;
  11751. document.getElementById('modal-rf-sr-id').value = r.id;
  11752. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11753. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11754. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11755. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11756. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11757. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11758. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11759. }
  11760. function closeSelectRuleModal() {
  11761. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11762. }
  11763. async function submitSelectRule(e) {
  11764. e.preventDefault();
  11765. const payload = {
  11766. id: document.getElementById('modal-rf-sr-id').value,
  11767. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11768. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11769. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11770. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11771. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11772. };
  11773. try {
  11774. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11775. method: 'POST',
  11776. headers: { 'Content-Type': 'application/json' },
  11777. body: JSON.stringify(payload)
  11778. });
  11779. if (res.ok) {
  11780. closeSelectRuleModal();
  11781. showToast('Success', 'Select rule saved', 'success');
  11782. loadDynamicRouting();
  11783. } else {
  11784. const err = await res.json();
  11785. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11786. }
  11787. } catch (err) {
  11788. showToast('Error', err.message, 'error');
  11789. }
  11790. }
  11791. async function deleteSelectRule(id) {
  11792. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11793. try {
  11794. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11795. if (res.ok) {
  11796. showToast('Deleted', 'Select rule removed', 'info');
  11797. loadDynamicRouting();
  11798. } else {
  11799. const err = await res.json();
  11800. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11801. }
  11802. } catch (err) {
  11803. showToast('Error', err.message, 'error');
  11804. }
  11805. }
  11806. async function toggleSelectRuleState(id, disabled) {
  11807. try {
  11808. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11809. method: 'POST',
  11810. headers: { 'Content-Type': 'application/json' },
  11811. body: JSON.stringify({ disabled })
  11812. });
  11813. if (res.ok) {
  11814. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11815. loadDynamicRouting();
  11816. } else {
  11817. const err = await res.json();
  11818. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11819. }
  11820. } catch (err) {
  11821. showToast('Error', err.message, 'error');
  11822. }
  11823. }
  11824. // -------------------------------------------------------------
  11825. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11826. // -------------------------------------------------------------
  11827. function openAddCommunityListModal() {
  11828. document.getElementById('modal-rf-cl-id').value = '';
  11829. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11830. document.getElementById('modal-rf-cl-name').value = '';
  11831. document.getElementById('modal-rf-cl-communities').value = '';
  11832. document.getElementById('modal-rf-cl-regexp').value = '';
  11833. document.getElementById('modal-rf-cl-comment').value = '';
  11834. document.getElementById('modal-rf-cl-disabled').checked = false;
  11835. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11836. }
  11837. function openEditCommunityListModal(id) {
  11838. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11839. if (!cl) return;
  11840. document.getElementById('modal-rf-cl-id').value = cl.id;
  11841. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11842. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11843. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11844. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11845. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11846. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11847. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11848. }
  11849. function closeCommunityListModal() {
  11850. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11851. }
  11852. async function submitCommunityList(e) {
  11853. e.preventDefault();
  11854. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11855. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11856. const payload = {
  11857. id: document.getElementById('modal-rf-cl-id').value,
  11858. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11859. communities: comms,
  11860. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11861. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11862. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11863. };
  11864. try {
  11865. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11866. method: 'POST',
  11867. headers: { 'Content-Type': 'application/json' },
  11868. body: JSON.stringify(payload)
  11869. });
  11870. if (res.ok) {
  11871. closeCommunityListModal();
  11872. showToast('Success', 'Community list saved', 'success');
  11873. loadDynamicRouting();
  11874. } else {
  11875. const err = await res.json();
  11876. showToast('Error', err.error || 'Failed to save community list', 'error');
  11877. }
  11878. } catch (err) {
  11879. showToast('Error', err.message, 'error');
  11880. }
  11881. }
  11882. async function deleteCommunityList(id) {
  11883. if (!confirm('Are you sure you want to delete this community list?')) return;
  11884. try {
  11885. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11886. if (res.ok) {
  11887. showToast('Deleted', 'Community list removed', 'info');
  11888. loadDynamicRouting();
  11889. } else {
  11890. const err = await res.json();
  11891. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11892. }
  11893. } catch (err) {
  11894. showToast('Error', err.message, 'error');
  11895. }
  11896. }
  11897. async function toggleCommunityListState(id, disabled) {
  11898. try {
  11899. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11900. method: 'POST',
  11901. headers: { 'Content-Type': 'application/json' },
  11902. body: JSON.stringify({ disabled })
  11903. });
  11904. if (res.ok) {
  11905. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11906. loadDynamicRouting();
  11907. } else {
  11908. const err = await res.json();
  11909. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11910. }
  11911. } catch (err) {
  11912. showToast('Error', err.message, 'error');
  11913. }
  11914. }
  11915. // -------------------------------------------------------------
  11916. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11917. // -------------------------------------------------------------
  11918. function openAddASListModal() {
  11919. document.getElementById('modal-rf-al-id').value = '';
  11920. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11921. document.getElementById('modal-rf-al-name').value = '';
  11922. document.getElementById('modal-rf-al-range').value = '';
  11923. document.getElementById('modal-rf-al-comment').value = '';
  11924. document.getElementById('modal-rf-al-disabled').checked = false;
  11925. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11926. }
  11927. function openEditASListModal(id) {
  11928. const al = (state.routingASLists || []).find(item => item.id === id);
  11929. if (!al) return;
  11930. document.getElementById('modal-rf-al-id').value = al.id;
  11931. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11932. document.getElementById('modal-rf-al-name').value = al.name || '';
  11933. document.getElementById('modal-rf-al-range').value = al.range || '';
  11934. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11935. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11936. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11937. }
  11938. function closeASListModal() {
  11939. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11940. }
  11941. async function submitASList(e) {
  11942. e.preventDefault();
  11943. const payload = {
  11944. id: document.getElementById('modal-rf-al-id').value,
  11945. name: document.getElementById('modal-rf-al-name').value.trim(),
  11946. range: document.getElementById('modal-rf-al-range').value.trim(),
  11947. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11948. disabled: document.getElementById('modal-rf-al-disabled').checked
  11949. };
  11950. try {
  11951. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11952. method: 'POST',
  11953. headers: { 'Content-Type': 'application/json' },
  11954. body: JSON.stringify(payload)
  11955. });
  11956. if (res.ok) {
  11957. closeASListModal();
  11958. showToast('Success', 'AS number list saved', 'success');
  11959. loadDynamicRouting();
  11960. } else {
  11961. const err = await res.json();
  11962. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11963. }
  11964. } catch (err) {
  11965. showToast('Error', err.message, 'error');
  11966. }
  11967. }
  11968. async function deleteASList(id) {
  11969. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11970. try {
  11971. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11972. if (res.ok) {
  11973. showToast('Deleted', 'AS list removed', 'info');
  11974. loadDynamicRouting();
  11975. } else {
  11976. const err = await res.json();
  11977. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11978. }
  11979. } catch (err) {
  11980. showToast('Error', err.message, 'error');
  11981. }
  11982. }
  11983. async function toggleASListState(id, disabled) {
  11984. try {
  11985. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11986. method: 'POST',
  11987. headers: { 'Content-Type': 'application/json' },
  11988. body: JSON.stringify({ disabled })
  11989. });
  11990. if (res.ok) {
  11991. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11992. loadDynamicRouting();
  11993. } else {
  11994. const err = await res.json();
  11995. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11996. }
  11997. } catch (err) {
  11998. showToast('Error', err.message, 'error');
  11999. }
  12000. }
  12001. // ==========================================
  12002. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12003. // ==========================================
  12004. function loadToolsView() {
  12005. populateToolsInterfaces();
  12006. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12007. }
  12008. function populateToolsInterfaces() {
  12009. const pingSel = document.getElementById('tools-ping-iface');
  12010. const traceSel = document.getElementById('tools-tr-iface');
  12011. let opts = '<option value="">Auto (Default Route)</option>';
  12012. if (Array.isArray(state.interfaces)) {
  12013. state.interfaces.forEach(iface => {
  12014. if (iface.name) {
  12015. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12016. }
  12017. });
  12018. }
  12019. if (pingSel) {
  12020. const cur = pingSel.value;
  12021. pingSel.innerHTML = opts;
  12022. if (cur) pingSel.value = cur;
  12023. }
  12024. if (traceSel) {
  12025. const cur = traceSel.value;
  12026. traceSel.innerHTML = opts;
  12027. if (cur) traceSel.value = cur;
  12028. }
  12029. }
  12030. function switchToolsSubTab(subTab) {
  12031. state.activeToolsSubTab = subTab;
  12032. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12033. tabs.forEach(t => {
  12034. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12035. const view = document.getElementById(`tools-view-${t}`);
  12036. if (btn) {
  12037. if (t === subTab) {
  12038. 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';
  12039. } else {
  12040. 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';
  12041. }
  12042. }
  12043. if (view) {
  12044. if (t === subTab) {
  12045. view.classList.remove('hidden');
  12046. } else {
  12047. view.classList.add('hidden');
  12048. }
  12049. }
  12050. });
  12051. }
  12052. function setPortPreset(port) {
  12053. const input = document.getElementById('tools-port-num');
  12054. if (input) input.value = port;
  12055. }
  12056. let pingAbortController = null;
  12057. let tracerouteAbortController = null;
  12058. function clearPingTable() {
  12059. const tbody = document.getElementById('tools-ping-tbody');
  12060. if (tbody) tbody.innerHTML = '';
  12061. const rawEl = document.getElementById('tools-ping-raw');
  12062. if (rawEl) rawEl.innerText = '';
  12063. const sentEl = document.getElementById('tools-ping-stat-sent');
  12064. if (sentEl) sentEl.innerText = '0';
  12065. const recvEl = document.getElementById('tools-ping-stat-recv');
  12066. if (recvEl) recvEl.innerText = '0';
  12067. const lossEl = document.getElementById('tools-ping-stat-loss');
  12068. if (lossEl) lossEl.innerText = '0%';
  12069. const avgEl = document.getElementById('tools-ping-stat-avg');
  12070. if (avgEl) avgEl.innerText = '0 ms';
  12071. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12072. if (minMaxEl) minMaxEl.innerText = '-';
  12073. const badge = document.getElementById('tools-ping-status-badge');
  12074. if (badge) {
  12075. badge.className = '';
  12076. badge.innerText = '';
  12077. }
  12078. }
  12079. function clearTracerouteTable() {
  12080. const tbody = document.getElementById('tools-tr-tbody');
  12081. if (tbody) tbody.innerHTML = '';
  12082. const rawEl = document.getElementById('tools-tr-raw');
  12083. if (rawEl) rawEl.innerText = '';
  12084. const statHops = document.getElementById('tools-tr-hops-count');
  12085. if (statHops) statHops.innerText = '0 Hops';
  12086. }
  12087. function resetPingButton() {
  12088. const btn = document.getElementById('tools-ping-btn');
  12089. const btnText = document.getElementById('tools-ping-btn-text');
  12090. const spinner = document.getElementById('tools-ping-spinner');
  12091. if (btn) {
  12092. btn.disabled = false;
  12093. 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';
  12094. }
  12095. if (btnText) btnText.innerText = 'Start Ping';
  12096. if (spinner) spinner.classList.add('hidden');
  12097. }
  12098. function setPingRunningButton() {
  12099. const btn = document.getElementById('tools-ping-btn');
  12100. const btnText = document.getElementById('tools-ping-btn-text');
  12101. const spinner = document.getElementById('tools-ping-spinner');
  12102. if (btn) {
  12103. btn.disabled = false;
  12104. 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';
  12105. }
  12106. if (btnText) btnText.innerText = 'Stop Ping';
  12107. if (spinner) spinner.classList.remove('hidden');
  12108. }
  12109. function resetTracerouteButton() {
  12110. const btn = document.getElementById('tools-tr-btn');
  12111. const btnText = document.getElementById('tools-tr-btn-text');
  12112. const spinner = document.getElementById('tools-tr-spinner');
  12113. if (btn) {
  12114. btn.disabled = false;
  12115. 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';
  12116. }
  12117. if (btnText) btnText.innerText = 'Start Traceroute';
  12118. if (spinner) spinner.classList.add('hidden');
  12119. }
  12120. function setTracerouteRunningButton() {
  12121. const btn = document.getElementById('tools-tr-btn');
  12122. const btnText = document.getElementById('tools-tr-btn-text');
  12123. const spinner = document.getElementById('tools-tr-spinner');
  12124. if (btn) {
  12125. btn.disabled = false;
  12126. 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';
  12127. }
  12128. if (btnText) btnText.innerText = 'Stop Traceroute';
  12129. if (spinner) spinner.classList.remove('hidden');
  12130. }
  12131. async function executePing(e) {
  12132. if (e) e.preventDefault();
  12133. // If already running, clicking the button stops the stream!
  12134. if (pingAbortController) {
  12135. pingAbortController.abort();
  12136. pingAbortController = null;
  12137. resetPingButton();
  12138. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12139. return;
  12140. }
  12141. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12142. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12143. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12144. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12145. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12146. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12147. if (!target) {
  12148. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12149. return;
  12150. }
  12151. clearPingTable();
  12152. const resCard = document.getElementById('tools-ping-results');
  12153. if (resCard) resCard.classList.remove('hidden');
  12154. pingAbortController = new AbortController();
  12155. setPingRunningButton();
  12156. try {
  12157. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12158. method: 'POST',
  12159. headers: { 'Content-Type': 'application/json' },
  12160. body: JSON.stringify({
  12161. target,
  12162. count,
  12163. size,
  12164. timeout,
  12165. interface: iface,
  12166. dont_frag: dontFrag
  12167. }),
  12168. signal: pingAbortController.signal
  12169. });
  12170. if (!res.ok) {
  12171. const errText = await res.text();
  12172. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12173. resetPingButton();
  12174. pingAbortController = null;
  12175. return;
  12176. }
  12177. const reader = res.body.getReader();
  12178. const decoder = new TextDecoder('utf-8');
  12179. let buffer = '';
  12180. while (true) {
  12181. const { done, value } = await reader.read();
  12182. if (done) break;
  12183. buffer += decoder.decode(value, { stream: true });
  12184. const blocks = buffer.split('\n\n');
  12185. buffer = blocks.pop() || '';
  12186. for (const block of blocks) {
  12187. const trimmed = block.trim();
  12188. if (!trimmed) continue;
  12189. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12190. try {
  12191. const evt = JSON.parse(line);
  12192. handleLivePingEvent(evt);
  12193. } catch (parseErr) {
  12194. console.warn('Ping SSE parse error:', parseErr, line);
  12195. }
  12196. }
  12197. }
  12198. } catch (err) {
  12199. if (err.name === 'AbortError') {
  12200. // User aborted normally
  12201. } else {
  12202. showToast('Ping Error', err.message, 'error');
  12203. }
  12204. } finally {
  12205. pingAbortController = null;
  12206. resetPingButton();
  12207. }
  12208. }
  12209. function handleLivePingEvent(evt) {
  12210. const sentEl = document.getElementById('tools-ping-stat-sent');
  12211. const recvEl = document.getElementById('tools-ping-stat-recv');
  12212. const lossEl = document.getElementById('tools-ping-stat-loss');
  12213. const avgEl = document.getElementById('tools-ping-stat-avg');
  12214. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12215. const badge = document.getElementById('tools-ping-status-badge');
  12216. const tbody = document.getElementById('tools-ping-tbody');
  12217. const rawEl = document.getElementById('tools-ping-raw');
  12218. if (evt.raw && rawEl) {
  12219. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12220. rawEl.scrollTop = rawEl.scrollHeight;
  12221. }
  12222. if (evt.type === 'reply') {
  12223. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12224. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12225. if (lossEl && evt.packet_loss_pct !== undefined) {
  12226. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12227. lossEl.className = evt.packet_loss_pct === 0
  12228. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12229. : (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');
  12230. }
  12231. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12232. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12233. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12234. }
  12235. if (badge) {
  12236. if (evt.packet_loss_pct === 0) {
  12237. 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';
  12238. badge.innerText = '100% OK';
  12239. } else {
  12240. 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';
  12241. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12242. }
  12243. }
  12244. if (tbody) {
  12245. const tr = document.createElement('tr');
  12246. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12247. tr.innerHTML = `
  12248. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12249. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12250. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12251. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12252. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12253. <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>
  12254. `;
  12255. tbody.appendChild(tr);
  12256. }
  12257. } else if (evt.type === 'timeout') {
  12258. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12259. if (lossEl && evt.packet_loss_pct !== undefined) {
  12260. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12261. 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';
  12262. }
  12263. if (badge) {
  12264. 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';
  12265. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12266. }
  12267. if (tbody) {
  12268. const tr = document.createElement('tr');
  12269. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12270. tr.innerHTML = `
  12271. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12272. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12273. <td class="py-2 px-3 text-slate-600">--</td>
  12274. <td class="py-2 px-3 text-slate-600">--</td>
  12275. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12276. <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>
  12277. `;
  12278. tbody.appendChild(tr);
  12279. }
  12280. } else if (evt.type === 'unreach') {
  12281. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12282. if (lossEl && evt.packet_loss_pct !== undefined) {
  12283. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12284. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12285. }
  12286. if (badge) {
  12287. 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';
  12288. badge.innerText = 'UNREACHABLE';
  12289. }
  12290. if (tbody) {
  12291. const tr = document.createElement('tr');
  12292. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12293. tr.innerHTML = `
  12294. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12295. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12296. <td class="py-2 px-3 text-slate-600">--</td>
  12297. <td class="py-2 px-3 text-slate-600">--</td>
  12298. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12299. <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>
  12300. `;
  12301. tbody.appendChild(tr);
  12302. }
  12303. } else if (evt.type === 'stats') {
  12304. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12305. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12306. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12307. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12308. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12309. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12310. }
  12311. } else if (evt.type === 'done') {
  12312. 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');
  12313. }
  12314. }
  12315. async function executeTraceroute(e) {
  12316. if (e) e.preventDefault();
  12317. if (tracerouteAbortController) {
  12318. tracerouteAbortController.abort();
  12319. tracerouteAbortController = null;
  12320. resetTracerouteButton();
  12321. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12322. return;
  12323. }
  12324. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12325. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12326. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12327. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12328. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12329. if (!target) {
  12330. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12331. return;
  12332. }
  12333. clearTracerouteTable();
  12334. const resCard = document.getElementById('tools-tr-results');
  12335. if (resCard) resCard.classList.remove('hidden');
  12336. tracerouteAbortController = new AbortController();
  12337. setTracerouteRunningButton();
  12338. try {
  12339. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12340. method: 'POST',
  12341. headers: { 'Content-Type': 'application/json' },
  12342. body: JSON.stringify({
  12343. target,
  12344. max_hops: maxHops,
  12345. protocol,
  12346. interface: iface,
  12347. resolve
  12348. }),
  12349. signal: tracerouteAbortController.signal
  12350. });
  12351. if (!res.ok) {
  12352. const errText = await res.text();
  12353. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12354. resetTracerouteButton();
  12355. tracerouteAbortController = null;
  12356. return;
  12357. }
  12358. const reader = res.body.getReader();
  12359. const decoder = new TextDecoder('utf-8');
  12360. let buffer = '';
  12361. while (true) {
  12362. const { done, value } = await reader.read();
  12363. if (done) break;
  12364. buffer += decoder.decode(value, { stream: true });
  12365. const blocks = buffer.split('\n\n');
  12366. buffer = blocks.pop() || '';
  12367. for (const block of blocks) {
  12368. const trimmed = block.trim();
  12369. if (!trimmed) continue;
  12370. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12371. try {
  12372. const evt = JSON.parse(line);
  12373. handleLiveTracerouteEvent(evt);
  12374. } catch (parseErr) {
  12375. console.warn('Traceroute SSE parse error:', parseErr, line);
  12376. }
  12377. }
  12378. }
  12379. } catch (err) {
  12380. if (err.name === 'AbortError') {
  12381. // User aborted normally
  12382. } else {
  12383. showToast('Traceroute Error', err.message, 'error');
  12384. }
  12385. } finally {
  12386. tracerouteAbortController = null;
  12387. resetTracerouteButton();
  12388. }
  12389. }
  12390. function handleLiveTracerouteEvent(evt) {
  12391. const statHops = document.getElementById('tools-tr-hops-count');
  12392. const tbody = document.getElementById('tools-tr-tbody');
  12393. const rawEl = document.getElementById('tools-tr-raw');
  12394. if (evt.raw && rawEl) {
  12395. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12396. rawEl.scrollTop = rawEl.scrollHeight;
  12397. }
  12398. if (evt.hops_count !== undefined && statHops) {
  12399. statHops.innerText = `${evt.hops_count} Hops`;
  12400. }
  12401. if (evt.type === 'hop' && evt.hop && tbody) {
  12402. const h = evt.hop;
  12403. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12404. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12405. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12406. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12407. const tr = document.createElement('tr');
  12408. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12409. tr.innerHTML = `
  12410. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12411. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12412. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12413. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12414. <td class="py-2.5 px-3 text-right">
  12415. ${isTimeout
  12416. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12417. : '<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>'}
  12418. </td>
  12419. `;
  12420. tbody.appendChild(tr);
  12421. } else if (evt.type === 'done') {
  12422. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12423. }
  12424. }
  12425. async function executeMTR(e) {
  12426. if (e) e.preventDefault();
  12427. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12428. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12429. if (!target) {
  12430. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12431. return;
  12432. }
  12433. const btn = document.getElementById('tools-mtr-btn');
  12434. const spinner = document.getElementById('tools-mtr-spinner');
  12435. if (btn) btn.disabled = true;
  12436. if (spinner) spinner.classList.remove('hidden');
  12437. try {
  12438. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12439. method: 'POST',
  12440. headers: { 'Content-Type': 'application/json' },
  12441. body: JSON.stringify({ target, count: cycles })
  12442. });
  12443. const data = await res.json();
  12444. if (!res.ok) {
  12445. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12446. return;
  12447. }
  12448. const resCard = document.getElementById('tools-mtr-results');
  12449. if (resCard) resCard.classList.remove('hidden');
  12450. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12451. const statHops = document.getElementById('tools-mtr-hops-count');
  12452. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12453. const tbody = document.getElementById('tools-mtr-tbody');
  12454. if (tbody) {
  12455. if (hopsCount > 0) {
  12456. tbody.innerHTML = data.hops.map(h => {
  12457. 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');
  12458. return `
  12459. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12460. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12461. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12462. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12463. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12464. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12465. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12466. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12467. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12468. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12469. </tr>
  12470. `;
  12471. }).join('');
  12472. } else {
  12473. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12474. }
  12475. }
  12476. const rawEl = document.getElementById('tools-mtr-raw');
  12477. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12478. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12479. } catch (err) {
  12480. showToast('MTR Error', err.message, 'error');
  12481. } finally {
  12482. if (btn) btn.disabled = false;
  12483. if (spinner) spinner.classList.add('hidden');
  12484. }
  12485. }
  12486. async function executeDNS(e) {
  12487. if (e) e.preventDefault();
  12488. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12489. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12490. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12491. if (!domain) {
  12492. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12493. return;
  12494. }
  12495. const btn = document.getElementById('tools-dns-btn');
  12496. const spinner = document.getElementById('tools-dns-spinner');
  12497. if (btn) btn.disabled = true;
  12498. if (spinner) spinner.classList.remove('hidden');
  12499. try {
  12500. const res = await fetch(`${API_BASE}/tools/dns`, {
  12501. method: 'POST',
  12502. headers: { 'Content-Type': 'application/json' },
  12503. body: JSON.stringify({ domain, type, server })
  12504. });
  12505. const data = await res.json();
  12506. if (!res.ok) {
  12507. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12508. return;
  12509. }
  12510. const resCard = document.getElementById('tools-dns-results');
  12511. if (resCard) resCard.classList.remove('hidden');
  12512. const metaEl = document.getElementById('tools-dns-meta');
  12513. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12514. const tbody = document.getElementById('tools-dns-tbody');
  12515. if (tbody) {
  12516. if (Array.isArray(data.records) && data.records.length > 0) {
  12517. tbody.innerHTML = data.records.map(r => `
  12518. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12519. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12520. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12521. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12522. <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>
  12523. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12524. </tr>
  12525. `).join('');
  12526. } else {
  12527. 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>`;
  12528. }
  12529. }
  12530. const rawEl = document.getElementById('tools-dns-raw');
  12531. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12532. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12533. } catch (err) {
  12534. showToast('DNS Error', err.message, 'error');
  12535. } finally {
  12536. if (btn) btn.disabled = false;
  12537. if (spinner) spinner.classList.add('hidden');
  12538. }
  12539. }
  12540. async function executePortProbe(e) {
  12541. if (e) e.preventDefault();
  12542. const target = document.getElementById('tools-port-target')?.value?.trim();
  12543. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12544. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12545. if (!target || !port) {
  12546. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12547. return;
  12548. }
  12549. const btn = document.getElementById('tools-port-btn');
  12550. const spinner = document.getElementById('tools-port-spinner');
  12551. if (btn) btn.disabled = true;
  12552. if (spinner) spinner.classList.remove('hidden');
  12553. try {
  12554. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12555. method: 'POST',
  12556. headers: { 'Content-Type': 'application/json' },
  12557. body: JSON.stringify({ target, port, timeout })
  12558. });
  12559. const data = await res.json();
  12560. if (!res.ok) {
  12561. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12562. return;
  12563. }
  12564. const resCard = document.getElementById('tools-port-results');
  12565. if (resCard) resCard.classList.remove('hidden');
  12566. const banner = document.getElementById('tools-port-banner');
  12567. const icon = document.getElementById('tools-port-icon');
  12568. const title = document.getElementById('tools-port-title');
  12569. const sub = document.getElementById('tools-port-sub');
  12570. const latency = document.getElementById('tools-port-latency');
  12571. if (data.open) {
  12572. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12573. if (icon) {
  12574. 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';
  12575. icon.innerText = '✓';
  12576. }
  12577. if (title) {
  12578. title.className = 'text-sm font-bold text-emerald-300';
  12579. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12580. }
  12581. if (sub) {
  12582. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12583. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12584. }
  12585. if (latency) {
  12586. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12587. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12588. }
  12589. } else {
  12590. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12591. if (icon) {
  12592. 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';
  12593. icon.innerText = '✕';
  12594. }
  12595. if (title) {
  12596. title.className = 'text-sm font-bold text-rose-300';
  12597. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12598. }
  12599. if (sub) {
  12600. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12601. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12602. }
  12603. if (latency) {
  12604. latency.className = 'text-base font-bold font-mono text-slate-500';
  12605. latency.innerText = '--';
  12606. }
  12607. }
  12608. const rawEl = document.getElementById('tools-port-raw');
  12609. 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'}`);
  12610. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12611. } catch (err) {
  12612. showToast('Probe Error', err.message, 'error');
  12613. } finally {
  12614. if (btn) btn.disabled = false;
  12615. if (spinner) spinner.classList.add('hidden');
  12616. }
  12617. }
  12618. // ==========================================
  12619. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12620. // ==========================================
  12621. async function loadDHCPClients(showToastMsg = false) {
  12622. try {
  12623. const [clientsRes, sumRes] = await Promise.all([
  12624. fetch(`${API_BASE}/dhcp/clients`),
  12625. fetch(`${API_BASE}/dhcp/clients/summary`)
  12626. ]);
  12627. if (clientsRes.ok) {
  12628. state.dhcpClients = await clientsRes.json();
  12629. }
  12630. if (sumRes.ok) {
  12631. state.dhcpSummary = await sumRes.json();
  12632. }
  12633. renderDHCPClients();
  12634. updateDHCPSummaryCards();
  12635. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12636. if (bDhcp && state.dhcpSummary) {
  12637. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12638. }
  12639. if (showToastMsg) {
  12640. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12641. }
  12642. } catch (err) {
  12643. console.error('Failed to load DHCP clients:', err);
  12644. if (showToastMsg) {
  12645. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12646. }
  12647. }
  12648. }
  12649. function updateDHCPSummaryCards() {
  12650. const sum = state.dhcpSummary || {
  12651. total_clients: (state.dhcpClients || []).length,
  12652. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12653. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12654. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12655. };
  12656. const totalEl = document.getElementById('dhcp-stat-total');
  12657. const boundEl = document.getElementById('dhcp-stat-bound');
  12658. const searchEl = document.getElementById('dhcp-stat-searching');
  12659. const disEl = document.getElementById('dhcp-stat-disabled');
  12660. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12661. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12662. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12663. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12664. }
  12665. function renderDHCPClients() {
  12666. const tbody = document.getElementById('dhcp-clients-tbody');
  12667. const emptyState = document.getElementById('dhcp-clients-empty');
  12668. if (!tbody) return;
  12669. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12670. if (clients.length === 0) {
  12671. tbody.innerHTML = '';
  12672. if (emptyState) emptyState.classList.remove('hidden');
  12673. return;
  12674. }
  12675. if (emptyState) emptyState.classList.add('hidden');
  12676. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12677. if (tbody.dataset.sig === sig) return;
  12678. tbody.dataset.sig = sig;
  12679. tbody.innerHTML = clients.map(c => {
  12680. let statusBadge = '';
  12681. if (!c.enabled) {
  12682. 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>';
  12683. } else if (c.status === 'bound') {
  12684. 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>';
  12685. } else if (c.status === 'searching') {
  12686. 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>';
  12687. } else if (c.status === 'stopped') {
  12688. 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>';
  12689. } else {
  12690. 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>`;
  12691. }
  12692. 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>';
  12693. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12694. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12695. 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>';
  12696. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12697. // Option flags
  12698. const flags = [];
  12699. 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>');
  12700. 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>');
  12701. 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>');
  12702. 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>`);
  12703. return `
  12704. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12705. <td class="py-3 px-4">
  12706. <div class="flex items-center gap-2">
  12707. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12708. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12709. </div>
  12710. </td>
  12711. <td class="py-3 px-4">${statusBadge}</td>
  12712. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12713. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12714. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12715. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12716. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12717. <td class="py-3 px-4">
  12718. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12719. </td>
  12720. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12721. ${c.enabled ? `
  12722. <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>
  12723. <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>
  12724. <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>
  12725. ` : `
  12726. <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>
  12727. `}
  12728. <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>
  12729. <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>
  12730. </td>
  12731. </tr>
  12732. `;
  12733. }).join('');
  12734. }
  12735. function openDHCPClientModal(clientId = null) {
  12736. const modal = document.getElementById('modal-dhcp-client');
  12737. if (!modal) return;
  12738. const title = document.getElementById('modal-dhcp-title');
  12739. const idInput = document.getElementById('modal-dhcp-id');
  12740. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12741. const distInput = document.getElementById('modal-dhcp-distance');
  12742. const commentInput = document.getElementById('modal-dhcp-comment');
  12743. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12744. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12745. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12746. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12747. // Populate interfaces
  12748. if (ifaceSelect) {
  12749. let opts = '<option value="">Select interface...</option>';
  12750. const allIfaces = state.interfaces || [];
  12751. const allVlans = state.vlans || [];
  12752. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12753. // Group 1: Physical & Bridge Interfaces
  12754. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12755. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12756. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12757. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12758. });
  12759. opts += '</optgroup>';
  12760. // Group 2: VLAN Interfaces
  12761. if (allVlans.length > 0) {
  12762. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12763. allVlans.forEach(v => {
  12764. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12765. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12766. });
  12767. opts += '</optgroup>';
  12768. }
  12769. ifaceSelect.innerHTML = opts;
  12770. }
  12771. if (clientId) {
  12772. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12773. if (client) {
  12774. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12775. if (idInput) idInput.value = client.id;
  12776. if (ifaceSelect) {
  12777. ifaceSelect.value = client.interface;
  12778. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12779. }
  12780. if (distInput) distInput.value = client.default_route_distance || 1;
  12781. if (commentInput) commentInput.value = client.comment || '';
  12782. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12783. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12784. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12785. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12786. }
  12787. } else {
  12788. if (title) title.innerText = 'Add DHCP Client';
  12789. if (idInput) idInput.value = '';
  12790. if (ifaceSelect) {
  12791. ifaceSelect.value = '';
  12792. ifaceSelect.disabled = false;
  12793. }
  12794. if (distInput) distInput.value = 1;
  12795. if (commentInput) commentInput.value = '';
  12796. if (defRouteCheck) defRouteCheck.checked = true;
  12797. if (peerDnsCheck) peerDnsCheck.checked = true;
  12798. if (peerNtpCheck) peerNtpCheck.checked = true;
  12799. if (enabledCheck) enabledCheck.checked = true;
  12800. }
  12801. modal.classList.remove('hidden');
  12802. }
  12803. function openDHCPClientModalForIface(ifaceName) {
  12804. openDHCPClientModal();
  12805. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12806. if (ifaceSelect && ifaceName) {
  12807. ifaceSelect.value = ifaceName;
  12808. }
  12809. }
  12810. function closeDHCPClientModal() {
  12811. const modal = document.getElementById('modal-dhcp-client');
  12812. if (modal) modal.classList.add('hidden');
  12813. }
  12814. async function submitSaveDHCPClient(e) {
  12815. if (e) e.preventDefault();
  12816. const id = document.getElementById('modal-dhcp-id')?.value;
  12817. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12818. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12819. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12820. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12821. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12822. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12823. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12824. if (!id && !iface) {
  12825. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12826. return;
  12827. }
  12828. try {
  12829. let res;
  12830. if (id) {
  12831. // PUT update
  12832. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12833. method: 'PUT',
  12834. headers: { 'Content-Type': 'application/json' },
  12835. body: JSON.stringify({
  12836. enabled,
  12837. add_default_route: defRoute,
  12838. default_route_distance: distance,
  12839. use_peer_dns: peerDns,
  12840. use_peer_ntp: peerNtp,
  12841. comment
  12842. })
  12843. });
  12844. } else {
  12845. // POST create
  12846. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12847. method: 'POST',
  12848. headers: { 'Content-Type': 'application/json' },
  12849. body: JSON.stringify({
  12850. interface: iface,
  12851. enabled,
  12852. add_default_route: defRoute,
  12853. default_route_distance: distance,
  12854. use_peer_dns: peerDns,
  12855. use_peer_ntp: peerNtp,
  12856. comment
  12857. })
  12858. });
  12859. }
  12860. const data = await res.json();
  12861. if (!res.ok) {
  12862. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12863. return;
  12864. }
  12865. closeDHCPClientModal();
  12866. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12867. await loadDHCPClients();
  12868. fetchData(); // refresh interfaces list with new lease/status
  12869. } catch (err) {
  12870. showToast('Error', err.message, 'error');
  12871. }
  12872. }
  12873. async function toggleDHCPClientState(id, enabled) {
  12874. try {
  12875. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12876. method: 'POST',
  12877. headers: { 'Content-Type': 'application/json' },
  12878. body: JSON.stringify({ enabled })
  12879. });
  12880. const data = await res.json();
  12881. if (!res.ok) {
  12882. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12883. return;
  12884. }
  12885. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12886. await loadDHCPClients();
  12887. fetchData();
  12888. } catch (err) {
  12889. showToast('Error', err.message, 'error');
  12890. }
  12891. }
  12892. async function renewDHCPClient(id) {
  12893. try {
  12894. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12895. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12896. method: 'POST'
  12897. });
  12898. const data = await res.json();
  12899. if (!res.ok) {
  12900. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12901. return;
  12902. }
  12903. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12904. setTimeout(() => {
  12905. loadDHCPClients();
  12906. fetchData();
  12907. }, 1500);
  12908. } catch (err) {
  12909. showToast('Error', err.message, 'error');
  12910. }
  12911. }
  12912. async function releaseDHCPClient(id) {
  12913. try {
  12914. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12915. method: 'POST'
  12916. });
  12917. const data = await res.json();
  12918. if (!res.ok) {
  12919. showToast('Error', data.error || 'Failed to release lease', 'error');
  12920. return;
  12921. }
  12922. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12923. await loadDHCPClients();
  12924. fetchData();
  12925. } catch (err) {
  12926. showToast('Error', err.message, 'error');
  12927. }
  12928. }
  12929. async function deleteDHCPClient(id, ifaceName) {
  12930. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12931. return;
  12932. }
  12933. try {
  12934. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12935. method: 'DELETE'
  12936. });
  12937. const data = await res.json();
  12938. if (!res.ok) {
  12939. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12940. return;
  12941. }
  12942. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12943. await loadDHCPClients();
  12944. fetchData();
  12945. } catch (err) {
  12946. showToast('Error', err.message, 'error');
  12947. }
  12948. }
  12949. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12950. async function loadDHCPServer(populate = true) {
  12951. try {
  12952. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12953. fetch(`${API_BASE}/dhcp-server/summary`),
  12954. fetch(`${API_BASE}/dhcp-server/servers`),
  12955. fetch(`${API_BASE}/dhcp-server/networks`),
  12956. fetch(`${API_BASE}/dhcp-server/leases`),
  12957. fetch(`${API_BASE}/dhcp-server/options`)
  12958. ]);
  12959. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12960. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12961. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12962. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12963. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12964. const sum = state.dhcpServerSummary || {};
  12965. const srvs = state.dhcpServers || [];
  12966. const nets = state.dhcpNetworks || [];
  12967. const leases = state.dhcpLeases || [];
  12968. const opts = state.dhcpOptions || [];
  12969. // KPI Cards
  12970. const statActive = document.getElementById('dhcp-server-stat-active');
  12971. if (statActive) {
  12972. const activeCount = srvs.filter(s => s.running).length;
  12973. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12974. }
  12975. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12976. if (statLeases) {
  12977. statLeases.innerText = leases.length;
  12978. }
  12979. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12980. if (statLeasesSub) {
  12981. const dyn = leases.filter(l => l.dynamic).length;
  12982. const st = leases.filter(l => !l.dynamic).length;
  12983. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12984. }
  12985. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12986. if (statNetworks) {
  12987. statNetworks.innerText = nets.length;
  12988. }
  12989. // Subtab Badges
  12990. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12991. if (bSrv) bSrv.innerText = srvs.length;
  12992. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12993. if (bNet) bNet.innerText = nets.length;
  12994. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12995. if (bLease) bLease.innerText = leases.length;
  12996. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12997. if (bOpt) bOpt.innerText = opts.length;
  12998. // Sidebar Badge
  12999. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13000. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13001. renderCurrentDHCPServerTab();
  13002. } catch (err) {
  13003. console.error('Failed to load DHCP Server:', err);
  13004. }
  13005. }
  13006. function switchDHCPServerTab(tab) {
  13007. state.dhcpServerTab = tab;
  13008. const tabs = ['servers', 'networks', 'leases', 'options'];
  13009. tabs.forEach(t => {
  13010. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13011. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13012. if (panel) {
  13013. if (t === tab) panel.classList.remove('hidden');
  13014. else panel.classList.add('hidden');
  13015. }
  13016. if (btn) {
  13017. if (t === tab) {
  13018. 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';
  13019. } else {
  13020. 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';
  13021. }
  13022. }
  13023. });
  13024. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13025. if (addBtn) {
  13026. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13027. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13028. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13029. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13030. }
  13031. renderCurrentDHCPServerTab();
  13032. }
  13033. function handleDHCPServerPrimaryAdd() {
  13034. const tab = state.dhcpServerTab || 'servers';
  13035. if (tab === 'servers') openAddDHCPServerModal();
  13036. else if (tab === 'networks') openAddDHCPNetworkModal();
  13037. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13038. else if (tab === 'options') openAddDHCPOptionModal();
  13039. }
  13040. function renderCurrentDHCPServerTab() {
  13041. const tab = state.dhcpServerTab || 'servers';
  13042. if (tab === 'servers') renderDHCPServers();
  13043. else if (tab === 'networks') renderDHCPNetworks();
  13044. else if (tab === 'leases') renderDHCPLeases();
  13045. else if (tab === 'options') renderDHCPOptions();
  13046. }
  13047. function renderDHCPServers() {
  13048. const tbody = document.getElementById('dhcp-server-tbody');
  13049. const empty = document.getElementById('dhcp-server-empty');
  13050. if (!tbody) return;
  13051. const servers = state.dhcpServers || [];
  13052. if (servers.length === 0) {
  13053. tbody.innerHTML = '';
  13054. empty?.classList.remove('hidden');
  13055. return;
  13056. }
  13057. empty?.classList.add('hidden');
  13058. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13059. if (tbody.dataset.sig === sig) return;
  13060. tbody.dataset.sig = sig;
  13061. tbody.innerHTML = '';
  13062. servers.forEach(s => {
  13063. const tr = document.createElement('tr');
  13064. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13065. tr.innerHTML = `
  13066. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13067. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13068. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13069. <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>
  13070. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13071. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13072. <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>
  13073. <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>
  13074. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13075. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13076. <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>
  13077. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13078. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13079. </td>
  13080. `;
  13081. tbody.appendChild(tr);
  13082. });
  13083. }
  13084. function renderDHCPNetworks() {
  13085. const tbody = document.getElementById('dhcp-networks-tbody');
  13086. const empty = document.getElementById('dhcp-networks-empty');
  13087. if (!tbody) return;
  13088. tbody.innerHTML = '';
  13089. const networks = state.dhcpNetworks || [];
  13090. if (networks.length === 0) {
  13091. empty?.classList.remove('hidden');
  13092. return;
  13093. }
  13094. empty?.classList.add('hidden');
  13095. networks.forEach(n => {
  13096. const tr = document.createElement('tr');
  13097. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13098. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13099. const optionsChips = (n.dhcp_options || []).map(optId => {
  13100. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13101. if (!opt) return '';
  13102. 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>`;
  13103. }).filter(Boolean).join('');
  13104. tr.innerHTML = `
  13105. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13106. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13107. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13108. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13109. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13110. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13111. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13112. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13113. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13114. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13115. </td>
  13116. `;
  13117. tbody.appendChild(tr);
  13118. });
  13119. }
  13120. function renderDHCPLeases() {
  13121. const tbody = document.getElementById('dhcp-leases-tbody');
  13122. const empty = document.getElementById('dhcp-leases-empty');
  13123. if (!tbody) return;
  13124. tbody.innerHTML = '';
  13125. const leases = state.dhcpLeases || [];
  13126. if (leases.length === 0) {
  13127. empty?.classList.remove('hidden');
  13128. return;
  13129. }
  13130. empty?.classList.add('hidden');
  13131. leases.forEach(l => {
  13132. const tr = document.createElement('tr');
  13133. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13134. 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>';
  13135. const statusBadge = l.status === 'bound'
  13136. ? '<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>'
  13137. : l.status === 'static'
  13138. ? '<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>'
  13139. : '<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>';
  13140. const makeStaticBtn = l.dynamic
  13141. ? `<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>`
  13142. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13143. tr.innerHTML = `
  13144. <td class="py-2.5 px-3 text-center">${flag}</td>
  13145. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13146. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13147. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13148. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13149. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13150. <td class="py-2.5 px-3">${statusBadge}</td>
  13151. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13152. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13153. ${makeStaticBtn}
  13154. </td>
  13155. `;
  13156. tbody.appendChild(tr);
  13157. });
  13158. }
  13159. function renderDHCPOptions() {
  13160. const tbody = document.getElementById('dhcp-options-tbody');
  13161. const empty = document.getElementById('dhcp-options-empty');
  13162. if (!tbody) return;
  13163. tbody.innerHTML = '';
  13164. const options = state.dhcpOptions || [];
  13165. if (options.length === 0) {
  13166. empty?.classList.remove('hidden');
  13167. return;
  13168. }
  13169. empty?.classList.add('hidden');
  13170. options.forEach(o => {
  13171. const tr = document.createElement('tr');
  13172. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13173. tr.innerHTML = `
  13174. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13175. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13176. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13177. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13178. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13179. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13180. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13181. </td>
  13182. `;
  13183. tbody.appendChild(tr);
  13184. });
  13185. }
  13186. // ==================== MODALS & ACTIONS: SERVER ====================
  13187. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13188. const sel = document.getElementById(elemId);
  13189. if (!sel) return;
  13190. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13191. const networks = state.dhcpNetworks || [];
  13192. networks.forEach(n => {
  13193. const opt = document.createElement('option');
  13194. opt.value = n.address;
  13195. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13196. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13197. opt.selected = true;
  13198. }
  13199. sel.appendChild(opt);
  13200. });
  13201. }
  13202. function onDHCPServerNetworkChange() {
  13203. const netSel = document.getElementById('dhcp-server-modal-network');
  13204. if (!netSel) return;
  13205. const netVal = netSel.value;
  13206. if (!netVal) return;
  13207. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13208. if (!poolInput) return;
  13209. // Auto-calculate suggested address pool based on subnet CIDR
  13210. const parts = netVal.split('/');
  13211. const ip = parts[0];
  13212. const cidr = parseInt(parts[1] || '24', 10);
  13213. if (cidr === 24) {
  13214. const octets = ip.split('.');
  13215. if (octets.length === 4) {
  13216. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13217. poolInput.value = `${base}.10-${base}.254`;
  13218. }
  13219. }
  13220. }
  13221. function openAddDHCPServerModal() {
  13222. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13223. document.getElementById('dhcp-server-modal-id').value = '';
  13224. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13225. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13226. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13227. document.getElementById('dhcp-server-modal-comment').value = '';
  13228. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13229. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13230. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13231. const networks = state.dhcpNetworks || [];
  13232. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13233. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13234. if (defaultNet) {
  13235. onDHCPServerNetworkChange();
  13236. }
  13237. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13238. }
  13239. function openEditDHCPServerModal(id) {
  13240. const s = (state.dhcpServers || []).find(item => item.id === id);
  13241. if (!s) return;
  13242. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13243. document.getElementById('dhcp-server-modal-id').value = s.id;
  13244. document.getElementById('dhcp-server-modal-name').value = s.name;
  13245. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13246. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13247. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13248. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13249. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13250. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13251. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13252. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13253. }
  13254. function closeDHCPServerModal() {
  13255. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13256. }
  13257. async function submitSaveDHCPServer(e) {
  13258. e.preventDefault();
  13259. const id = document.getElementById('dhcp-server-modal-id').value;
  13260. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13261. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13262. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13263. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13264. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13265. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13266. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13267. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13268. try {
  13269. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13270. method: 'POST',
  13271. headers: { 'Content-Type': 'application/json' },
  13272. body: JSON.stringify({
  13273. id,
  13274. name,
  13275. interface: iface,
  13276. network,
  13277. address_pool: pool,
  13278. lease_time: leaseTime,
  13279. authoritative,
  13280. disabled,
  13281. comment
  13282. })
  13283. });
  13284. if (res.ok) {
  13285. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13286. closeDHCPServerModal();
  13287. loadDHCPServer(false);
  13288. fetchData(false);
  13289. } else {
  13290. const err = await res.text();
  13291. showToast('Error', err, 'error');
  13292. }
  13293. } catch (err) {
  13294. showToast('Error', err.message, 'error');
  13295. }
  13296. }
  13297. async function toggleDHCPServerState(id, disabled) {
  13298. try {
  13299. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13300. method: 'POST',
  13301. headers: { 'Content-Type': 'application/json' },
  13302. body: JSON.stringify({ disabled })
  13303. });
  13304. if (res.ok) {
  13305. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13306. loadDHCPServer(false);
  13307. fetchData(false);
  13308. }
  13309. } catch (err) {
  13310. showToast('Error', err.message, 'error');
  13311. }
  13312. }
  13313. async function deleteDHCPServer(id, name) {
  13314. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13315. try {
  13316. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13317. if (res.ok) {
  13318. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13319. loadDHCPServer(false);
  13320. fetchData(false);
  13321. }
  13322. } catch (err) {
  13323. showToast('Error', err.message, 'error');
  13324. }
  13325. }
  13326. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13327. function openAddDHCPNetworkModal() {
  13328. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13329. document.getElementById('dhcp-network-modal-id').value = '';
  13330. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13331. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13332. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13333. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13334. document.getElementById('dhcp-network-modal-netmask').value = '';
  13335. document.getElementById('dhcp-network-modal-comment').value = '';
  13336. renderDHCPNetworkOptionsCheckboxes([]);
  13337. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13338. }
  13339. function openEditDHCPNetworkModal(id) {
  13340. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13341. if (!n) return;
  13342. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13343. document.getElementById('dhcp-network-modal-id').value = n.id;
  13344. document.getElementById('dhcp-network-modal-address').value = n.address;
  13345. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13346. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13347. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13348. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13349. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13350. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13351. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13352. }
  13353. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13354. const container = document.getElementById('dhcp-network-modal-options-list');
  13355. if (!container) return;
  13356. container.innerHTML = '';
  13357. const opts = state.dhcpOptions || [];
  13358. if (opts.length === 0) {
  13359. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13360. return;
  13361. }
  13362. opts.forEach(o => {
  13363. const isChecked = selectedIds.includes(o.id);
  13364. const label = document.createElement('label');
  13365. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13366. label.innerHTML = `
  13367. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13368. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13369. `;
  13370. container.appendChild(label);
  13371. });
  13372. }
  13373. function closeDHCPNetworkModal() {
  13374. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13375. }
  13376. async function submitSaveDHCPNetwork(e) {
  13377. e.preventDefault();
  13378. const id = document.getElementById('dhcp-network-modal-id').value;
  13379. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13380. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13381. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13382. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13383. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13384. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13385. const selectedOpts = [];
  13386. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13387. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13388. try {
  13389. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13390. method: 'POST',
  13391. headers: { 'Content-Type': 'application/json' },
  13392. body: JSON.stringify({
  13393. id,
  13394. address,
  13395. gateway,
  13396. netmask,
  13397. dns_servers: dnsServers,
  13398. domain,
  13399. dhcp_options: selectedOpts,
  13400. comment
  13401. })
  13402. });
  13403. if (res.ok) {
  13404. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13405. closeDHCPNetworkModal();
  13406. loadDHCPServer(false);
  13407. fetchData(false);
  13408. } else {
  13409. const err = await res.text();
  13410. showToast('Error', err, 'error');
  13411. }
  13412. } catch (err) {
  13413. showToast('Error', err.message, 'error');
  13414. }
  13415. }
  13416. async function deleteDHCPNetwork(id, addr) {
  13417. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13418. try {
  13419. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13420. if (res.ok) {
  13421. showToast('Deleted', `Network ${addr} removed`, 'success');
  13422. loadDHCPServer(false);
  13423. fetchData(false);
  13424. }
  13425. } catch (err) {
  13426. showToast('Error', err.message, 'error');
  13427. }
  13428. }
  13429. // ==================== MODALS & ACTIONS: LEASES ====================
  13430. function openAddDHCPStaticLeaseModal() {
  13431. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13432. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13433. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13434. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13435. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13436. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13437. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13438. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13439. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13440. }
  13441. function closeDHCPStaticLeaseModal() {
  13442. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13443. }
  13444. async function submitSaveDHCPStaticLease(e) {
  13445. e.preventDefault();
  13446. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13447. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13448. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13449. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13450. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13451. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13452. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13453. try {
  13454. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13455. method: 'POST',
  13456. headers: { 'Content-Type': 'application/json' },
  13457. body: JSON.stringify({
  13458. id,
  13459. mac_address: mac,
  13460. address: ip,
  13461. hostname,
  13462. server,
  13463. comment,
  13464. disabled
  13465. })
  13466. });
  13467. if (res.ok) {
  13468. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13469. closeDHCPStaticLeaseModal();
  13470. loadDHCPServer(false);
  13471. fetchData(false);
  13472. } else {
  13473. const err = await res.text();
  13474. showToast('Error', err, 'error');
  13475. }
  13476. } catch (err) {
  13477. showToast('Error', err.message, 'error');
  13478. }
  13479. }
  13480. async function deleteDHCPStaticLease(id) {
  13481. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13482. try {
  13483. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13484. if (res.ok) {
  13485. showToast('Deleted', 'Static lease removed', 'success');
  13486. loadDHCPServer(false);
  13487. fetchData(false);
  13488. }
  13489. } catch (err) {
  13490. showToast('Error', err.message, 'error');
  13491. }
  13492. }
  13493. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13494. try {
  13495. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13496. method: 'POST',
  13497. headers: { 'Content-Type': 'application/json' },
  13498. body: JSON.stringify({
  13499. mac_address: mac,
  13500. address: ip,
  13501. hostname,
  13502. comment: comment || 'Converted to static'
  13503. })
  13504. });
  13505. if (res.ok) {
  13506. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13507. loadDHCPServer(false);
  13508. fetchData(false);
  13509. } else {
  13510. const err = await res.text();
  13511. showToast('Error', err, 'error');
  13512. }
  13513. } catch (err) {
  13514. showToast('Error', err.message, 'error');
  13515. }
  13516. }
  13517. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13518. function openAddDHCPOptionModal() {
  13519. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13520. document.getElementById('dhcp-option-modal-id').value = '';
  13521. document.getElementById('dhcp-option-modal-name').value = '';
  13522. document.getElementById('dhcp-option-modal-code').value = '';
  13523. document.getElementById('dhcp-option-modal-value').value = '';
  13524. document.getElementById('dhcp-option-modal-comment').value = '';
  13525. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13526. }
  13527. function openEditDHCPOptionModal(id) {
  13528. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13529. if (!o) return;
  13530. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13531. document.getElementById('dhcp-option-modal-id').value = o.id;
  13532. document.getElementById('dhcp-option-modal-name').value = o.name;
  13533. document.getElementById('dhcp-option-modal-code').value = o.code;
  13534. document.getElementById('dhcp-option-modal-value').value = o.value;
  13535. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13536. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13537. }
  13538. function closeDHCPOptionModal() {
  13539. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13540. }
  13541. async function submitSaveDHCPOption(e) {
  13542. e.preventDefault();
  13543. const id = document.getElementById('dhcp-option-modal-id').value;
  13544. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13545. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13546. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13547. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13548. try {
  13549. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13550. method: 'POST',
  13551. headers: { 'Content-Type': 'application/json' },
  13552. body: JSON.stringify({ id, name, code, value, comment })
  13553. });
  13554. if (res.ok) {
  13555. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13556. closeDHCPOptionModal();
  13557. loadDHCPServer(false);
  13558. fetchData(false);
  13559. } else {
  13560. const err = await res.text();
  13561. showToast('Error', err, 'error');
  13562. }
  13563. } catch (err) {
  13564. showToast('Error', err.message, 'error');
  13565. }
  13566. }
  13567. async function deleteDHCPOption(id, name) {
  13568. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13569. try {
  13570. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13571. if (res.ok) {
  13572. showToast('Deleted', `Option ${name} removed`, 'success');
  13573. loadDHCPServer(false);
  13574. fetchData(false);
  13575. }
  13576. } catch (err) {
  13577. showToast('Error', err.message, 'error');
  13578. }
  13579. }
  13580. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13581. function openDHCPServerSetupModal() {
  13582. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13583. onDHCPWizardIfaceChange();
  13584. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13585. }
  13586. function closeDHCPServerSetupModal() {
  13587. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13588. }
  13589. function onDHCPWizardIfaceChange() {
  13590. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13591. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13592. let ip = '192.168.88.1';
  13593. let prefix = '24';
  13594. if (iface && iface.ip_address) {
  13595. const parts = iface.ip_address.split('/');
  13596. ip = parts[0];
  13597. if (parts.length > 1) prefix = parts[1];
  13598. }
  13599. // Calculate subnet base (e.g. 192.168.88.0/24)
  13600. const ipParts = ip.split('.');
  13601. if (ipParts.length === 4) {
  13602. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13603. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13604. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13605. document.getElementById('dhcp-wizard-gateway').value = ip;
  13606. document.getElementById('dhcp-wizard-pool').value = pool;
  13607. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13608. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13609. }
  13610. }
  13611. async function submitDHCPServerSetupWizard(e) {
  13612. e.preventDefault();
  13613. const iface = document.getElementById('dhcp-wizard-iface').value;
  13614. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13615. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13616. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13617. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13618. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13619. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13620. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13621. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13622. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13623. try {
  13624. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13625. method: 'POST',
  13626. headers: { 'Content-Type': 'application/json' },
  13627. body: JSON.stringify({
  13628. interface: iface,
  13629. address_space: space,
  13630. gateway: gw,
  13631. address_pool: pool,
  13632. dns_servers: dnsServers,
  13633. lease_time: leaseTime,
  13634. ntp_servers: ntpServers,
  13635. next_server: tftp
  13636. })
  13637. });
  13638. if (res.ok) {
  13639. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13640. closeDHCPServerSetupModal();
  13641. loadDHCPServer(false);
  13642. fetchData(false);
  13643. } else {
  13644. const err = await res.text();
  13645. showToast('Error', err, 'error');
  13646. }
  13647. } catch (err) {
  13648. showToast('Error', err.message, 'error');
  13649. }
  13650. }
  13651. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13652. const sel = document.getElementById(elemId);
  13653. if (!sel) return;
  13654. sel.innerHTML = '<option value="">Select interface...</option>';
  13655. const ifaces = state.interfaces || [];
  13656. ifaces.forEach(i => {
  13657. if (i.name === 'lo') return;
  13658. const opt = document.createElement('option');
  13659. opt.value = i.name;
  13660. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13661. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13662. if (i.name === selectedVal) opt.selected = true;
  13663. sel.appendChild(opt);
  13664. });
  13665. }
  13666. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13667. function initTableSorting() {
  13668. document.querySelectorAll('table').forEach(setupSortableTable);
  13669. }
  13670. function setupSortableTable(table) {
  13671. const thead = table.querySelector('thead');
  13672. const tbody = table.querySelector('tbody');
  13673. if (!thead || !tbody) return;
  13674. const headerRows = thead.querySelectorAll('tr');
  13675. if (headerRows.length === 0) return;
  13676. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13677. ths.forEach((th, colIdx) => {
  13678. if (th._sortBound) return;
  13679. th._sortBound = true;
  13680. const rawText = th.innerText.trim().toLowerCase();
  13681. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13682. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13683. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13684. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13685. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13686. return;
  13687. }
  13688. th.classList.add('table-sortable', 'group');
  13689. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13690. let icon = th.querySelector('.table-sort-icon');
  13691. if (!icon) {
  13692. icon = document.createElement('span');
  13693. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13694. icon.innerHTML = '⇅';
  13695. th.appendChild(icon);
  13696. }
  13697. th.addEventListener('click', (e) => {
  13698. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13699. handleHeaderClick(table, th, colIdx);
  13700. });
  13701. });
  13702. if (!tbody._sortObserved) {
  13703. tbody._sortObserved = true;
  13704. let sortDebounceTimer = null;
  13705. const observer = new MutationObserver((mutations) => {
  13706. if (tbody._isSorting) return;
  13707. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13708. if (!hasChildChanges) return;
  13709. clearTimeout(sortDebounceTimer);
  13710. sortDebounceTimer = setTimeout(() => {
  13711. if (tbody._isSorting) return;
  13712. if (table._activeSort && table._activeSort.dir !== 'none') {
  13713. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13714. } else {
  13715. tagOriginalRowOrder(tbody);
  13716. }
  13717. }, 50);
  13718. });
  13719. tbody._sortObserver = observer;
  13720. observer.observe(tbody, { childList: true });
  13721. }
  13722. tagOriginalRowOrder(tbody);
  13723. }
  13724. function tagOriginalRowOrder(tbody) {
  13725. let idx = 0;
  13726. Array.from(tbody.children).forEach(tr => {
  13727. if (!tr.querySelector('td[colspan]')) {
  13728. if (!tr.hasAttribute('data-orig-idx')) {
  13729. tr.setAttribute('data-orig-idx', idx++);
  13730. }
  13731. }
  13732. });
  13733. }
  13734. function handleHeaderClick(table, th, colIdx) {
  13735. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13736. let newDir = 'asc';
  13737. if (currentSort.colIdx === colIdx) {
  13738. if (currentSort.dir === 'asc') newDir = 'desc';
  13739. else if (currentSort.dir === 'desc') newDir = 'none';
  13740. else newDir = 'asc';
  13741. } else {
  13742. newDir = 'asc';
  13743. }
  13744. table._activeSort = { colIdx, dir: newDir };
  13745. updateHeaderIcons(table, colIdx, newDir);
  13746. applyTableSort(table, colIdx, newDir, true);
  13747. }
  13748. function updateHeaderIcons(table, activeColIdx, dir) {
  13749. const thead = table.querySelector('thead');
  13750. if (!thead) return;
  13751. const ths = thead.querySelectorAll('th');
  13752. ths.forEach((th, idx) => {
  13753. const icon = th.querySelector('.table-sort-icon');
  13754. if (!icon) return;
  13755. if (idx === activeColIdx && dir !== 'none') {
  13756. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13757. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13758. th.classList.add('table-sorted-active');
  13759. } else {
  13760. icon.innerHTML = '⇅';
  13761. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13762. th.classList.remove('table-sorted-active');
  13763. }
  13764. });
  13765. }
  13766. function applyTableSort(table, colIdx, dir, userInitiated) {
  13767. const tbody = table.querySelector('tbody');
  13768. if (!tbody || tbody.children.length <= 1) return;
  13769. tbody._isSorting = true;
  13770. tagOriginalRowOrder(tbody);
  13771. // Group parent rows and any attached drawer/sub-rows
  13772. const groups = [];
  13773. let currentGroup = null;
  13774. Array.from(tbody.children).forEach(tr => {
  13775. if (tr.querySelector('td[colspan]')) {
  13776. if (currentGroup) {
  13777. currentGroup.subRows.push(tr);
  13778. } else {
  13779. groups.push({ mainRow: tr, subRows: [] });
  13780. }
  13781. } else {
  13782. currentGroup = { mainRow: tr, subRows: [] };
  13783. groups.push(currentGroup);
  13784. }
  13785. });
  13786. if (dir === 'none') {
  13787. groups.sort((a, b) => {
  13788. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13789. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13790. return idxA - idxB;
  13791. });
  13792. } else {
  13793. groups.sort((a, b) => {
  13794. const cellA = a.mainRow.children[colIdx];
  13795. const cellB = b.mainRow.children[colIdx];
  13796. const res = compareTableCells(cellA, cellB);
  13797. return dir === 'asc' ? res : -res;
  13798. });
  13799. }
  13800. // Check if rows are already in correct order to avoid modifying DOM
  13801. let alreadyOrdered = true;
  13802. let childIdx = 0;
  13803. for (const g of groups) {
  13804. if (tbody.children[childIdx] !== g.mainRow) {
  13805. alreadyOrdered = false;
  13806. break;
  13807. }
  13808. childIdx++;
  13809. for (const sub of g.subRows) {
  13810. if (tbody.children[childIdx] !== sub) {
  13811. alreadyOrdered = false;
  13812. break;
  13813. }
  13814. childIdx++;
  13815. }
  13816. }
  13817. if (alreadyOrdered) {
  13818. tbody._isSorting = false;
  13819. return;
  13820. }
  13821. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13822. if (tbody._sortObserver) {
  13823. tbody._sortObserver.disconnect();
  13824. }
  13825. // Re-append rows in sorted order
  13826. groups.forEach(g => {
  13827. tbody.appendChild(g.mainRow);
  13828. g.subRows.forEach(sub => tbody.appendChild(sub));
  13829. });
  13830. // Drain any queued mutations and re-connect observer
  13831. if (tbody._sortObserver) {
  13832. tbody._sortObserver.takeRecords();
  13833. tbody._sortObserver.observe(tbody, { childList: true });
  13834. }
  13835. tbody._isSorting = false;
  13836. }
  13837. function getCellRawText(cell) {
  13838. if (!cell) return '';
  13839. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13840. const input = cell.querySelector('input, select');
  13841. if (input) {
  13842. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13843. return input.value;
  13844. }
  13845. return cell.innerText.trim();
  13846. }
  13847. function parseTrafficToNumber(str) {
  13848. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13849. if (!m) return null;
  13850. const num = parseFloat(m[1].replace(/,/g, ''));
  13851. if (isNaN(num)) return null;
  13852. const unit = m[2].toUpperCase();
  13853. let mult = 1;
  13854. if (unit.startsWith('K')) mult = 1024;
  13855. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13856. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13857. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13858. return num * mult;
  13859. }
  13860. function parseIpToNumber(str) {
  13861. const clean = str.replace(/^[!~]/, '').trim();
  13862. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13863. if (!m) return null;
  13864. const o1 = parseInt(m[1], 10);
  13865. const o2 = parseInt(m[2], 10);
  13866. const o3 = parseInt(m[3], 10);
  13867. const o4 = parseInt(m[4], 10);
  13868. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13869. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13870. }
  13871. function parseCompoundPackets(str) {
  13872. const m = str.match(/^([\d,]+)p/);
  13873. if (!m) return null;
  13874. return parseInt(m[1].replace(/,/g, ''), 10);
  13875. }
  13876. function compareTableCells(cellA, cellB) {
  13877. const a = getCellRawText(cellA);
  13878. const b = getCellRawText(cellB);
  13879. if (a === '' && b !== '') return 1;
  13880. if (b === '' && a !== '') return -1;
  13881. if (a === b) return 0;
  13882. // 1. IP Addresses / CIDR
  13883. const ipA = parseIpToNumber(a);
  13884. const ipB = parseIpToNumber(b);
  13885. if (ipA !== null && ipB !== null) return ipA - ipB;
  13886. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13887. const pktA = parseCompoundPackets(a);
  13888. const pktB = parseCompoundPackets(b);
  13889. if (pktA !== null && pktB !== null) return pktA - pktB;
  13890. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13891. const trafA = parseTrafficToNumber(a);
  13892. const trafB = parseTrafficToNumber(b);
  13893. if (trafA !== null && trafB !== null) return trafA - trafB;
  13894. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13895. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13896. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13897. const numA = Number(cleanNumA);
  13898. const numB = Number(cleanNumB);
  13899. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13900. return numA - numB;
  13901. }
  13902. // 5. Natural case-insensitive string compare
  13903. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13904. }
  13905. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13906. async function loadVRRP(showToastNotification = false) {
  13907. try {
  13908. const [instRes, sumRes] = await Promise.all([
  13909. fetch(`${API_BASE}/vrrp/instances`),
  13910. fetch(`${API_BASE}/vrrp/summary`)
  13911. ]);
  13912. if (instRes.ok) {
  13913. state.vrrpInstances = await instRes.json();
  13914. renderVRRP();
  13915. }
  13916. if (sumRes.ok) {
  13917. state.vrrpSummary = await sumRes.json();
  13918. renderVRRPSummary();
  13919. }
  13920. if (showToastNotification) {
  13921. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13922. }
  13923. } catch (err) {
  13924. console.error('Failed to load VRRP:', err);
  13925. }
  13926. }
  13927. function renderVRRPSummary() {
  13928. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13929. const elTotal = document.getElementById('vrrp-stat-total');
  13930. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13931. const elMaster = document.getElementById('vrrp-stat-master');
  13932. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13933. const elBackup = document.getElementById('vrrp-stat-backup');
  13934. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13935. const bCount = document.getElementById('badge-vrrp-count');
  13936. if (bCount) bCount.innerText = s.total_instances || 0;
  13937. const dot = document.getElementById('badge-vrrp-dot');
  13938. if (dot) {
  13939. if (s.master_instances > 0) {
  13940. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13941. } else if (s.backup_instances > 0) {
  13942. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13943. } else {
  13944. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13945. }
  13946. }
  13947. }
  13948. function renderVRRP() {
  13949. const tbody = document.getElementById('vrrp-table-tbody');
  13950. const empty = document.getElementById('vrrp-table-empty');
  13951. if (!tbody) return;
  13952. tbody.innerHTML = '';
  13953. const instances = state.vrrpInstances || [];
  13954. if (instances.length === 0) {
  13955. empty?.classList.remove('hidden');
  13956. return;
  13957. }
  13958. empty?.classList.add('hidden');
  13959. instances.forEach(inst => {
  13960. const tr = document.createElement('tr');
  13961. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13962. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13963. 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>`;
  13964. if (inst.disabled) {
  13965. 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>`;
  13966. } else if (inst.state === 'MASTER') {
  13967. 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>`;
  13968. } else if (inst.state === 'BACKUP') {
  13969. 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>`;
  13970. } else if (inst.state === 'FAULT') {
  13971. 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>`;
  13972. }
  13973. // Render State Badge
  13974. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13975. if (!inst.disabled) {
  13976. if (inst.state === 'MASTER') {
  13977. 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>`;
  13978. } else if (inst.state === 'BACKUP') {
  13979. 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>`;
  13980. } else if (inst.state === 'FAULT') {
  13981. 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>`;
  13982. }
  13983. }
  13984. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13985. tr.innerHTML = `
  13986. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13987. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13988. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13989. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13990. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13991. <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>
  13992. <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>
  13993. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13994. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13995. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13996. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13997. <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>
  13998. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13999. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14000. </td>
  14001. `;
  14002. tbody.appendChild(tr);
  14003. });
  14004. }
  14005. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14006. const sel = document.getElementById(elemId);
  14007. if (!sel) return;
  14008. sel.innerHTML = '<option value="">Select interface...</option>';
  14009. const ifaces = state.interfaces || [];
  14010. ifaces.forEach(i => {
  14011. const opt = document.createElement('option');
  14012. opt.value = i.name;
  14013. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14014. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14015. sel.appendChild(opt);
  14016. });
  14017. }
  14018. function openAddVRRPModal() {
  14019. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14020. document.getElementById('modal-vrrp-id').value = '';
  14021. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14022. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14023. document.getElementById('modal-vrrp-priority').value = 100;
  14024. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14025. document.getElementById('modal-vrrp-version').value = '3';
  14026. document.getElementById('modal-vrrp-interval').value = 1;
  14027. document.getElementById('modal-vrrp-authtype').value = 'none';
  14028. document.getElementById('modal-vrrp-authpass').value = '';
  14029. document.getElementById('modal-vrrp-comment').value = '';
  14030. document.getElementById('modal-vrrp-preempt').checked = true;
  14031. document.getElementById('modal-vrrp-disabled').checked = false;
  14032. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14033. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14034. }
  14035. function openEditVRRPModal(id) {
  14036. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14037. if (!inst) return;
  14038. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14039. document.getElementById('modal-vrrp-id').value = inst.id;
  14040. document.getElementById('modal-vrrp-name').value = inst.name;
  14041. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14042. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14043. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14044. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14045. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14046. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14047. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14048. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14049. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14050. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14051. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14052. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14053. }
  14054. function closeVRRPModal() {
  14055. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14056. }
  14057. async function submitSaveVRRP(e) {
  14058. e.preventDefault();
  14059. const id = document.getElementById('modal-vrrp-id').value;
  14060. const name = document.getElementById('modal-vrrp-name').value.trim();
  14061. const iface = document.getElementById('modal-vrrp-iface').value;
  14062. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14063. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14064. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14065. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14066. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14067. const authType = document.getElementById('modal-vrrp-authtype').value;
  14068. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14069. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14070. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14071. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14072. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14073. try {
  14074. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14075. method: 'POST',
  14076. headers: { 'Content-Type': 'application/json' },
  14077. body: JSON.stringify({
  14078. id,
  14079. name,
  14080. interface: iface,
  14081. vrid,
  14082. priority,
  14083. virtual_ips: vips,
  14084. version,
  14085. interval,
  14086. auth_type: authType,
  14087. auth_password: authPass,
  14088. comment,
  14089. preempt,
  14090. disabled
  14091. })
  14092. });
  14093. if (res.ok) {
  14094. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14095. closeVRRPModal();
  14096. loadVRRP(false);
  14097. fetchData(false);
  14098. } else {
  14099. const err = await res.text();
  14100. showToast('Error', err, 'error');
  14101. }
  14102. } catch (err) {
  14103. showToast('Error', err.message, 'error');
  14104. }
  14105. }
  14106. async function deleteVRRP(id, name) {
  14107. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14108. try {
  14109. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14110. if (res.ok) {
  14111. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14112. loadVRRP(false);
  14113. fetchData(false);
  14114. } else {
  14115. const err = await res.text();
  14116. showToast('Error', err, 'error');
  14117. }
  14118. } catch (err) {
  14119. showToast('Error', err.message, 'error');
  14120. }
  14121. }
  14122. async function toggleVRRPState(id, disabled) {
  14123. try {
  14124. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14125. method: 'POST',
  14126. headers: { 'Content-Type': 'application/json' },
  14127. body: JSON.stringify({ disabled })
  14128. });
  14129. if (res.ok) {
  14130. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14131. loadVRRP(false);
  14132. fetchData(false);
  14133. } else {
  14134. const err = await res.text();
  14135. showToast('Error', err, 'error');
  14136. }
  14137. } catch (err) {
  14138. showToast('Error', err.message, 'error');
  14139. }
  14140. }
  14141. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14142. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14143. let docSortDebounce = null;
  14144. const docTableObserver = new MutationObserver((mutations) => {
  14145. let needsInit = false;
  14146. for (const m of mutations) {
  14147. for (const node of m.addedNodes) {
  14148. if (node.nodeType === 1) {
  14149. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14150. needsInit = true;
  14151. break;
  14152. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14153. needsInit = true;
  14154. break;
  14155. }
  14156. }
  14157. }
  14158. if (needsInit) break;
  14159. }
  14160. if (needsInit) {
  14161. clearTimeout(docSortDebounce);
  14162. docSortDebounce = setTimeout(initTableSorting, 100);
  14163. }
  14164. });
  14165. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14166. }
  14167. // =========================================================================
  14168. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14169. // =========================================================================
  14170. const bwtestState = {
  14171. running: false,
  14172. pollTimer: null,
  14173. eventSource: null,
  14174. chartPoints: [],
  14175. maxChartPoints: 60,
  14176. serverConfig: null,
  14177. peakTx: 0,
  14178. peakRx: 0,
  14179. targetDuration: 10,
  14180. lastSampleElapsed: -1,
  14181. sessionID: null
  14182. };
  14183. async function loadBwTestView() {
  14184. resizeBwTestCanvas();
  14185. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14186. }
  14187. async function fetchBwTestServerStatus() {
  14188. try {
  14189. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14190. if (!res.ok) return;
  14191. const s = await res.json();
  14192. bwtestState.serverConfig = s;
  14193. // Update indicator and badges
  14194. const indicator = document.getElementById('bwtest-server-indicator');
  14195. const badge = document.getElementById('bwtest-server-badge');
  14196. const sideBadge = document.getElementById('badge-bwtest-server');
  14197. if (s.enabled && s.running) {
  14198. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14199. if (badge) {
  14200. badge.innerText = `Port ${s.port} (Active)`;
  14201. badge.className = 'text-emerald-400 font-bold';
  14202. }
  14203. if (sideBadge) {
  14204. sideBadge.innerText = s.port;
  14205. 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';
  14206. }
  14207. } else {
  14208. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14209. if (badge) {
  14210. badge.innerText = `Disabled`;
  14211. badge.className = 'text-slate-500 font-bold';
  14212. }
  14213. if (sideBadge) {
  14214. sideBadge.innerText = 'Off';
  14215. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14216. }
  14217. }
  14218. // Modal fields
  14219. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14220. const serverModal = document.getElementById('modal-bwtest-server');
  14221. const editing = serverModal && !serverModal.classList.contains('hidden');
  14222. if (toggle && !editing) toggle.checked = !!s.enabled;
  14223. const portInp = document.getElementById('bwtest-server-port-input');
  14224. if (portInp && !editing) portInp.value = s.port || 2000;
  14225. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14226. if (actSess) actSess.innerText = s.active_sessions || 0;
  14227. const totServ = document.getElementById('bwtest-modal-total-served');
  14228. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14229. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14230. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14231. } catch (err) {
  14232. console.error('Failed to fetch BwTest server status:', err);
  14233. }
  14234. }
  14235. function openBwTestServerModal() {
  14236. const cfg = bwtestState.serverConfig;
  14237. if (cfg) {
  14238. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14239. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14240. }
  14241. fetchBwTestServerStatus();
  14242. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14243. }
  14244. function closeBwTestServerModal() {
  14245. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14246. }
  14247. async function submitBwTestServerSettings(e) {
  14248. e.preventDefault();
  14249. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14250. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14251. try {
  14252. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14253. method: 'POST',
  14254. headers: { 'Content-Type': 'application/json' },
  14255. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14256. });
  14257. if (!res.ok) {
  14258. const err = await res.json();
  14259. throw new Error(err.error || 'Failed to update server configuration');
  14260. }
  14261. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14262. closeBwTestServerModal();
  14263. fetchBwTestServerStatus();
  14264. } catch (err) {
  14265. showToast('Server Configuration Error', err.message, 'error');
  14266. }
  14267. }
  14268. function setBwTestTarget(target) {
  14269. const inp = document.getElementById('bwtest-input-target');
  14270. if (inp) inp.value = target;
  14271. }
  14272. function setBwTestProtocol(proto) {
  14273. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14274. if (hiddenInp) hiddenInp.value = proto;
  14275. const btnUdp = document.getElementById('bwtest-proto-udp');
  14276. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14277. const badge = document.getElementById('bwtest-proto-badge');
  14278. const pktField = document.getElementById('bwtest-field-pktsize');
  14279. 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';
  14280. 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';
  14281. 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';
  14282. if (proto === 'udp') {
  14283. if (btnUdp) {
  14284. btnUdp.className = activeUdpCls;
  14285. const dot = btnUdp.querySelector('span');
  14286. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14287. }
  14288. if (btnTcp) {
  14289. btnTcp.className = inactiveCls;
  14290. const dot = btnTcp.querySelector('span');
  14291. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14292. }
  14293. if (badge) {
  14294. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14295. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14296. }
  14297. if (pktField) pktField.classList.remove('opacity-40');
  14298. } else {
  14299. if (btnUdp) {
  14300. btnUdp.className = inactiveCls;
  14301. const dot = btnUdp.querySelector('span');
  14302. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14303. }
  14304. if (btnTcp) {
  14305. btnTcp.className = activeTcpCls;
  14306. const dot = btnTcp.querySelector('span');
  14307. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14308. }
  14309. if (badge) {
  14310. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14311. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14312. }
  14313. if (pktField) pktField.classList.add('opacity-40');
  14314. }
  14315. }
  14316. function setBwTestDirection(dir) {
  14317. const hiddenInp = document.getElementById('bwtest-input-direction');
  14318. if (hiddenInp) hiddenInp.value = dir;
  14319. const btnBoth = document.getElementById('bwtest-dir-both');
  14320. const btnTx = document.getElementById('bwtest-dir-tx');
  14321. const btnRx = document.getElementById('bwtest-dir-rx');
  14322. 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';
  14323. 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';
  14324. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14325. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14326. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14327. }
  14328. function setBwTestLimit(bps) {
  14329. const sel = document.getElementById('bwtest-input-limit');
  14330. if (sel) sel.value = String(bps);
  14331. }
  14332. async function checkActiveBwTest() {
  14333. try {
  14334. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14335. if (!res.ok) return;
  14336. const st = await res.json();
  14337. if (st.running) {
  14338. setBwTestRunningUI(true);
  14339. processBwTestStatus(st);
  14340. startBwTestTelemetry();
  14341. }
  14342. } catch (err) {
  14343. console.error('Failed to check active BwTest:', err);
  14344. }
  14345. }
  14346. async function startBwTest(e) {
  14347. if (e && e.preventDefault) e.preventDefault();
  14348. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14349. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14350. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14351. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14352. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14353. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14354. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14355. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14356. bwtestState.targetDuration = duration;
  14357. bwtestState.chartPoints = [];
  14358. bwtestState.peakTx = 0;
  14359. bwtestState.peakRx = 0;
  14360. bwtestState.lastSampleElapsed = -1;
  14361. bwtestState.sessionID = null;
  14362. // Clear UI elements
  14363. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14364. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14365. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14366. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14367. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14368. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14369. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14370. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14371. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14372. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14373. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14374. const tbody = document.getElementById('bwtest-samples-tbody');
  14375. if (tbody) tbody.innerHTML = '';
  14376. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14377. setBwTestRunningUI(true);
  14378. try {
  14379. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14380. method: 'POST',
  14381. headers: { 'Content-Type': 'application/json' },
  14382. body: JSON.stringify({
  14383. target,
  14384. port,
  14385. direction,
  14386. protocol,
  14387. bandwidth_limit,
  14388. packet_size,
  14389. streams,
  14390. duration
  14391. })
  14392. });
  14393. if (!res.ok) {
  14394. const err = await res.json();
  14395. throw new Error(err.error || 'Failed to start bandwidth test');
  14396. }
  14397. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14398. startBwTestTelemetry();
  14399. } catch (err) {
  14400. setBwTestRunningUI(false);
  14401. showToast('Start Failed', err.message, 'error');
  14402. }
  14403. }
  14404. function setBwTestRunningUI(running) {
  14405. bwtestState.running = running;
  14406. const startBtn = document.getElementById('bwtest-btn-start');
  14407. const stopBtn = document.getElementById('bwtest-btn-stop');
  14408. const badge = document.getElementById('bwtest-run-status-badge');
  14409. const ph = document.getElementById('bwtest-chart-placeholder');
  14410. if (running) {
  14411. if (startBtn) {
  14412. startBtn.disabled = true;
  14413. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14414. }
  14415. if (stopBtn) {
  14416. stopBtn.disabled = false;
  14417. stopBtn.classList.remove('opacity-40');
  14418. }
  14419. if (badge) {
  14420. badge.innerText = 'TESTING...';
  14421. 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';
  14422. }
  14423. if (ph) ph.style.display = 'none';
  14424. } else {
  14425. if (startBtn) {
  14426. startBtn.disabled = false;
  14427. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14428. }
  14429. if (stopBtn) {
  14430. stopBtn.disabled = true;
  14431. stopBtn.classList.add('opacity-40');
  14432. }
  14433. if (badge) {
  14434. badge.innerText = 'IDLE';
  14435. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14436. }
  14437. }
  14438. }
  14439. async function stopBwTest() {
  14440. try {
  14441. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14442. if (!res.ok) throw new Error(await responseError(res));
  14443. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14444. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14445. } catch (err) {
  14446. showToast('Stop Failed', err.message, 'error');
  14447. }
  14448. }
  14449. async function responseError(res) {
  14450. const text = await res.text();
  14451. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14452. catch { return text || `HTTP ${res.status}`; }
  14453. }
  14454. function processBwTestStatus(st) {
  14455. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14456. bwtestState.sessionID = st.session_id;
  14457. bwtestState.lastSampleElapsed = -1;
  14458. }
  14459. for (const sample of st.recent_samples || []) {
  14460. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14461. handleBwTestSample(sample);
  14462. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14463. }
  14464. }
  14465. if (!st.running) {
  14466. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14467. bwtestState.pollTimer = null;
  14468. setBwTestRunningUI(false);
  14469. handleBwTestFinish(st.summary, st.error);
  14470. }
  14471. }
  14472. function startBwTestTelemetry() {
  14473. if (!state.currentUser) return;
  14474. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14475. let busy = false;
  14476. const poll = async () => {
  14477. if (busy || !state.currentUser || document.hidden) return;
  14478. busy = true;
  14479. try {
  14480. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14481. if (!res.ok) throw new Error(await responseError(res));
  14482. processBwTestStatus(await res.json());
  14483. } catch (err) {
  14484. console.error('BwTest polling error:', err);
  14485. } finally { busy = false; }
  14486. };
  14487. bwtestState.pollTimer = setInterval(poll, 400);
  14488. poll();
  14489. }
  14490. function handleBwTestSample(s) {
  14491. if (!s) return;
  14492. const payloadHint = document.getElementById('bwtest-effective-payload');
  14493. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14494. const txMbps = s.tx_mbps || 0;
  14495. const rxMbps = s.rx_mbps || 0;
  14496. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14497. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14498. // KPI updates
  14499. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14500. if (elTx) {
  14501. elTx.innerText = txMbps.toFixed(2);
  14502. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14503. }
  14504. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14505. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14506. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14507. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14508. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14509. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14510. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14511. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14512. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14513. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14514. const elLoss = document.getElementById('bwtest-stat-loss');
  14515. if (elLoss) {
  14516. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14517. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14518. }
  14519. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14520. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14521. const elJitter = document.getElementById('bwtest-stat-jitter');
  14522. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14523. const elTime = document.getElementById('bwtest-stat-time');
  14524. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14525. const elData = document.getElementById('bwtest-stat-data');
  14526. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14527. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14528. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14529. // Append point to chart buffer
  14530. bwtestState.chartPoints.push({
  14531. elapsed: s.elapsed_sec || 0,
  14532. tx: txMbps,
  14533. rx: rxMbps
  14534. });
  14535. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14536. bwtestState.chartPoints.shift();
  14537. }
  14538. drawBwTestChart();
  14539. // Add row to breakdown table
  14540. const tbody = document.getElementById('bwtest-samples-tbody');
  14541. if (tbody) {
  14542. const tr = document.createElement('tr');
  14543. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14544. tr.innerHTML = `
  14545. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14546. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14547. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14548. <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>
  14549. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14550. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14551. `;
  14552. tbody.insertBefore(tr, tbody.firstChild);
  14553. const countEl = document.getElementById('bwtest-sample-count');
  14554. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14555. }
  14556. }
  14557. function handleBwTestFinish(summary, error) {
  14558. const badge = document.getElementById('bwtest-run-status-badge');
  14559. if (error) {
  14560. showToast('Benchmark Error', error, 'error');
  14561. if (badge) {
  14562. badge.innerText = 'ERROR';
  14563. 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';
  14564. }
  14565. } else if (summary) {
  14566. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14567. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14568. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14569. if (badge) {
  14570. badge.innerText = 'COMPLETED';
  14571. 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';
  14572. }
  14573. }
  14574. loadBwTestHistory();
  14575. fetchBwTestServerStatus();
  14576. }
  14577. function resizeBwTestCanvas() {
  14578. const canvas = document.getElementById('bwtest-chart');
  14579. if (!canvas || !canvas.parentElement) return;
  14580. const rect = canvas.parentElement.getBoundingClientRect();
  14581. const dpr = window.devicePixelRatio || 1;
  14582. canvas.width = rect.width * dpr;
  14583. canvas.height = rect.height * dpr;
  14584. const ctx = canvas.getContext('2d');
  14585. ctx.scale(dpr, dpr);
  14586. drawBwTestChart();
  14587. }
  14588. window.addEventListener('resize', () => {
  14589. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14590. });
  14591. function drawBwTestChart() {
  14592. const canvas = document.getElementById('bwtest-chart');
  14593. if (!canvas) return;
  14594. const ctx = canvas.getContext('2d');
  14595. const dpr = window.devicePixelRatio || 1;
  14596. const width = canvas.width / dpr;
  14597. const height = canvas.height / dpr;
  14598. ctx.clearRect(0, 0, width, height);
  14599. const points = bwtestState.chartPoints;
  14600. if (!points || points.length === 0) return;
  14601. // Determine scale ceiling
  14602. let maxRate = 10;
  14603. for (const p of points) {
  14604. if (p.tx > maxRate) maxRate = p.tx;
  14605. if (p.rx > maxRate) maxRate = p.rx;
  14606. }
  14607. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14608. const paddingLeft = 55;
  14609. const paddingBottom = 24;
  14610. const paddingTop = 12;
  14611. const paddingRight = 16;
  14612. const chartW = width - paddingLeft - paddingRight;
  14613. const chartH = height - paddingTop - paddingBottom;
  14614. // Grid Lines and Y-Axis labels
  14615. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14616. ctx.lineWidth = 1;
  14617. ctx.fillStyle = '#94a3b8';
  14618. ctx.font = '10px monospace';
  14619. ctx.textAlign = 'right';
  14620. const gridSteps = 4;
  14621. for (let i = 0; i <= gridSteps; i++) {
  14622. const val = (maxRate / gridSteps) * i;
  14623. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14624. ctx.beginPath();
  14625. ctx.moveTo(paddingLeft, y);
  14626. ctx.lineTo(width - paddingRight, y);
  14627. ctx.stroke();
  14628. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14629. }
  14630. // Draw TX Line (Cyan #22d3ee)
  14631. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14632. // Draw RX Line (Purple #a855f7)
  14633. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14634. }
  14635. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14636. if (points.length < 2) return;
  14637. const stepX = w / Math.max(points.length - 1, 1);
  14638. // Gradient area fill
  14639. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14640. grad.addColorStop(0, fillColor);
  14641. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14642. ctx.beginPath();
  14643. points.forEach((p, idx) => {
  14644. const x = left + idx * stepX;
  14645. const val = valFn(p);
  14646. const y = top + h - (val / maxVal) * h;
  14647. if (idx === 0) {
  14648. ctx.moveTo(x, y);
  14649. } else {
  14650. ctx.lineTo(x, y);
  14651. }
  14652. });
  14653. // Complete path for fill
  14654. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14655. ctx.lineTo(left, top + h);
  14656. ctx.closePath();
  14657. ctx.fillStyle = grad;
  14658. ctx.fill();
  14659. // Draw line stroke
  14660. ctx.beginPath();
  14661. ctx.lineWidth = 2.5;
  14662. ctx.strokeStyle = strokeColor;
  14663. points.forEach((p, idx) => {
  14664. const x = left + idx * stepX;
  14665. const val = valFn(p);
  14666. const y = top + h - (val / maxVal) * h;
  14667. if (idx === 0) {
  14668. ctx.moveTo(x, y);
  14669. } else {
  14670. ctx.lineTo(x, y);
  14671. }
  14672. });
  14673. ctx.stroke();
  14674. // Draw end point halo
  14675. const lastP = points[points.length - 1];
  14676. const lastX = left + (points.length - 1) * stepX;
  14677. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14678. ctx.fillStyle = strokeColor;
  14679. ctx.beginPath();
  14680. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14681. ctx.fill();
  14682. }
  14683. async function loadBwTestHistory() {
  14684. try {
  14685. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14686. if (!res.ok) return;
  14687. const list = await res.json();
  14688. renderBwTestHistory(Array.isArray(list) ? list : []);
  14689. } catch (err) {
  14690. console.error('Failed to load BwTest history:', err);
  14691. }
  14692. }
  14693. function renderBwTestHistory(list) {
  14694. const tbody = document.getElementById('bwtest-history-tbody');
  14695. if (!tbody) return;
  14696. if (list.length === 0) {
  14697. 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>`;
  14698. return;
  14699. }
  14700. tbody.innerHTML = '';
  14701. list.forEach(item => {
  14702. const s = item.summary || {};
  14703. const tr = document.createElement('tr');
  14704. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14705. const dirBadge = item.direction === 'both'
  14706. ? `<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>`
  14707. : item.direction === 'tx'
  14708. ? `<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>`
  14709. : `<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>`;
  14710. const protoBadge = item.protocol === 'tcp'
  14711. ? `<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>`
  14712. : `<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>`;
  14713. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14714. tr.innerHTML = `
  14715. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14716. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14717. <td class="py-2.5 px-4">${protoBadge}</td>
  14718. <td class="py-2.5 px-4">${dirBadge}</td>
  14719. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14720. <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>
  14721. <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>
  14722. <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>
  14723. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14724. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14725. `;
  14726. tbody.appendChild(tr);
  14727. });
  14728. }
  14729. // ======================== SETTINGS & ROUTER DNS ========================
  14730. state.settingsSubTab = 'dns';
  14731. state.dnsSettings = null;
  14732. state.dnsStaticRecords = [];
  14733. state.dnsStatus = null;
  14734. function switchSettingsSubTab(sub) {
  14735. state.settingsSubTab = sub;
  14736. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14737. const btnSys = document.getElementById('btn-settings-subtab-system');
  14738. const tabDns = document.getElementById('settings-subtab-dns');
  14739. const tabSys = document.getElementById('settings-subtab-system');
  14740. if (sub === 'dns') {
  14741. if (btnDns) {
  14742. 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';
  14743. }
  14744. if (btnSys) {
  14745. 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';
  14746. }
  14747. tabDns?.classList.remove('hidden');
  14748. tabSys?.classList.add('hidden');
  14749. loadDNSSettings();
  14750. } else {
  14751. if (btnSys) {
  14752. 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';
  14753. }
  14754. if (btnDns) {
  14755. 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';
  14756. }
  14757. tabSys?.classList.remove('hidden');
  14758. tabDns?.classList.add('hidden');
  14759. loadSystemSettings();
  14760. }
  14761. }
  14762. async function loadSettingsData(showLoading = false) {
  14763. if (state.settingsSubTab === 'system') {
  14764. await loadSystemSettings();
  14765. } else {
  14766. await loadDNSSettings();
  14767. }
  14768. }
  14769. async function loadDNSSettings() {
  14770. try {
  14771. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14772. fetch(`${API_BASE}/dns/settings`),
  14773. fetch(`${API_BASE}/dns/static`),
  14774. fetch(`${API_BASE}/dns/status`)
  14775. ]);
  14776. if (settingsRes.ok) {
  14777. state.dnsSettings = await settingsRes.json();
  14778. populateDNSSettingsForm(state.dnsSettings);
  14779. }
  14780. if (staticRes.ok) {
  14781. state.dnsStaticRecords = await staticRes.json();
  14782. renderStaticDNSList();
  14783. }
  14784. if (statusRes.ok) {
  14785. state.dnsStatus = await statusRes.json();
  14786. updateDNSStatusView(state.dnsStatus);
  14787. }
  14788. } catch (err) {
  14789. console.error('Failed to load DNS settings:', err);
  14790. }
  14791. }
  14792. function populateDNSSettingsForm(s) {
  14793. if (!s) return;
  14794. const dnsForm = document.getElementById('form-dns-settings');
  14795. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14796. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14797. if (dynamicEl) {
  14798. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14799. 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(' ');
  14800. } else {
  14801. dynamicEl.innerText = 'None';
  14802. }
  14803. }
  14804. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14805. if (isEditing) return;
  14806. const serversInput = document.getElementById('dns-servers-input');
  14807. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14808. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14809. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14810. const domainInput = document.getElementById('dns-domain-input');
  14811. if (domainInput) domainInput.value = s.domain || '';
  14812. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14813. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14814. }
  14815. function updateDNSStatusView(st) {
  14816. if (!st) return;
  14817. const preview = document.getElementById('dns-resolv-preview');
  14818. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14819. const pillText = document.getElementById('dns-live-status-text');
  14820. const pill = document.getElementById('dns-live-status-pill');
  14821. if (pill && pillText) {
  14822. if (st.service_running) {
  14823. 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';
  14824. pillText.innerText = 'DNS Service Active';
  14825. } else {
  14826. 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';
  14827. pillText.innerText = 'DNS Service Inactive';
  14828. }
  14829. }
  14830. }
  14831. function appendDNSPreset(preset) {
  14832. const input = document.getElementById('dns-servers-input');
  14833. if (!input) return;
  14834. const dnsForm = document.getElementById('form-dns-settings');
  14835. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14836. const current = input.value.trim();
  14837. if (!current) {
  14838. input.value = preset;
  14839. } else {
  14840. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14841. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14842. toAdd.forEach(ip => {
  14843. if (!existing.includes(ip)) existing.push(ip);
  14844. });
  14845. input.value = existing.join(', ');
  14846. }
  14847. }
  14848. async function saveDNSSettings(e) {
  14849. e.preventDefault();
  14850. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14851. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14852. if (servers.length === 0) {
  14853. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14854. return;
  14855. }
  14856. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14857. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14858. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14859. try {
  14860. const res = await fetch(`${API_BASE}/dns/settings`, {
  14861. method: 'POST',
  14862. headers: { 'Content-Type': 'application/json' },
  14863. body: JSON.stringify({
  14864. servers: servers,
  14865. cache_size: cacheSize,
  14866. domain: domain,
  14867. allow_remote_requests: allowRemote
  14868. })
  14869. });
  14870. const data = await res.json();
  14871. if (res.ok) {
  14872. const dnsForm = document.getElementById('form-dns-settings');
  14873. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14874. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14875. loadDNSSettings();
  14876. } else {
  14877. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14878. }
  14879. } catch (err) {
  14880. showToast('Error', err.message, 'error');
  14881. }
  14882. }
  14883. async function flushDNSCache() {
  14884. try {
  14885. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14886. if (res.ok) {
  14887. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14888. loadDNSSettings();
  14889. } else {
  14890. const err = await res.json();
  14891. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14892. }
  14893. } catch (err) {
  14894. showToast('Error', err.message, 'error');
  14895. }
  14896. }
  14897. function renderStaticDNSList() {
  14898. const tbody = document.getElementById('dns-static-tbody');
  14899. const empty = document.getElementById('dns-static-empty');
  14900. const badge = document.getElementById('dns-static-count-badge');
  14901. if (!tbody) return;
  14902. tbody.innerHTML = '';
  14903. const records = state.dnsStaticRecords || [];
  14904. if (badge) badge.innerText = `${records.length} Records`;
  14905. if (records.length === 0) {
  14906. empty?.classList.remove('hidden');
  14907. return;
  14908. }
  14909. empty?.classList.add('hidden');
  14910. records.forEach(rec => {
  14911. const tr = document.createElement('tr');
  14912. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14913. tr.innerHTML = `
  14914. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14915. <td class="py-2.5 px-4">
  14916. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14917. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14918. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14919. }">
  14920. ${rec.type || 'A'}
  14921. </span>
  14922. </td>
  14923. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14924. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14925. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14926. <td class="py-2.5 px-4">
  14927. <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'}">
  14928. ${rec.disabled ? 'Disabled' : 'Active'}
  14929. </span>
  14930. </td>
  14931. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14932. <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>
  14933. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14934. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14935. </td>
  14936. `;
  14937. tbody.appendChild(tr);
  14938. });
  14939. }
  14940. function openStaticDNSModal(id = null) {
  14941. const modal = document.getElementById('modal-static-dns');
  14942. const title = document.getElementById('modal-static-dns-title');
  14943. const form = document.getElementById('form-static-dns');
  14944. if (!modal || !form) return;
  14945. form.reset();
  14946. document.getElementById('modal-static-dns-id').value = '';
  14947. if (id) {
  14948. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14949. if (rec) {
  14950. if (title) title.innerText = 'Edit Static DNS Record';
  14951. document.getElementById('modal-static-dns-id').value = rec.id;
  14952. document.getElementById('modal-static-dns-name').value = rec.name;
  14953. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14954. document.getElementById('modal-static-dns-addr').value = rec.address;
  14955. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14956. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14957. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14958. }
  14959. } else {
  14960. if (title) title.innerText = 'Add Static DNS Record';
  14961. }
  14962. modal.classList.remove('hidden');
  14963. }
  14964. function closeStaticDNSModal() {
  14965. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14966. }
  14967. async function submitSaveStaticDNS(e) {
  14968. e.preventDefault();
  14969. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14970. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14971. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14972. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14973. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14974. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14975. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14976. if (!name || !address) {
  14977. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14978. return;
  14979. }
  14980. try {
  14981. const res = await fetch(`${API_BASE}/dns/static`, {
  14982. method: 'POST',
  14983. headers: { 'Content-Type': 'application/json' },
  14984. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14985. });
  14986. const data = await res.json();
  14987. if (res.ok) {
  14988. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14989. closeStaticDNSModal();
  14990. loadDNSSettings();
  14991. } else {
  14992. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14993. }
  14994. } catch (err) {
  14995. showToast('Error', err.message, 'error');
  14996. }
  14997. }
  14998. async function deleteStaticDNS(id) {
  14999. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15000. try {
  15001. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15002. if (res.ok) {
  15003. showToast('Deleted', 'Static DNS record deleted', 'success');
  15004. loadDNSSettings();
  15005. }
  15006. } catch (err) {
  15007. showToast('Error', err.message, 'error');
  15008. }
  15009. }
  15010. async function toggleStaticDNS(id, disabled) {
  15011. try {
  15012. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15013. method: 'POST',
  15014. headers: { 'Content-Type': 'application/json' },
  15015. body: JSON.stringify({ disabled })
  15016. });
  15017. if (res.ok) {
  15018. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15019. loadDNSSettings();
  15020. }
  15021. } catch (err) {
  15022. showToast('Error', err.message, 'error');
  15023. }
  15024. }
  15025. async function loadSystemSettings() {
  15026. try {
  15027. const sysForm = document.getElementById('form-system-settings');
  15028. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15029. const res = await fetch(`${API_BASE}/system/settings`);
  15030. if (res.ok) {
  15031. const data = await res.json();
  15032. if (!isEditing) {
  15033. const hostInput = document.getElementById('system-hostname-input');
  15034. if (hostInput) hostInput.value = data.hostname || '';
  15035. const tzInput = document.getElementById('system-timezone-input');
  15036. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15037. }
  15038. }
  15039. } catch (err) {
  15040. console.error('Failed to load system settings:', err);
  15041. }
  15042. }
  15043. async function saveSystemSettings(e) {
  15044. e.preventDefault();
  15045. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15046. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15047. try {
  15048. const res = await fetch(`${API_BASE}/system/settings`, {
  15049. method: 'POST',
  15050. headers: { 'Content-Type': 'application/json' },
  15051. body: JSON.stringify({ hostname, timezone })
  15052. });
  15053. const data = await res.json();
  15054. if (res.ok) {
  15055. const sysForm = document.getElementById('form-system-settings');
  15056. if (sysForm) sysForm.dataset.dirty = 'false';
  15057. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15058. const sideH = document.getElementById('side-hostname');
  15059. if (sideH) sideH.innerText = data.hostname;
  15060. } else {
  15061. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15062. }
  15063. } catch (err) {
  15064. showToast('Error', err.message, 'error');
  15065. }
  15066. }
  15067. // =============================================================================
  15068. // AUTHENTICATION & USER MANAGER
  15069. // =============================================================================
  15070. async function checkAuthStatus() {
  15071. try {
  15072. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15073. headers: {
  15074. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15075. }
  15076. });
  15077. if (res.ok) {
  15078. const user = await res.json();
  15079. state.currentUser = user;
  15080. updateUserProfileHeader(user);
  15081. hideLoginScreen();
  15082. state.isPolling = true;
  15083. fetchData();
  15084. initLiveTrafficStream();
  15085. return true;
  15086. } else {
  15087. showLoginScreen(false);
  15088. return false;
  15089. }
  15090. } catch (err) {
  15091. showLoginScreen(false);
  15092. return false;
  15093. }
  15094. }
  15095. function showLoginScreen(isExpired = false) {
  15096. const el = document.getElementById('login-screen');
  15097. if (el) el.classList.remove('hidden');
  15098. const errEl = document.getElementById('login-error');
  15099. const errTxt = document.getElementById('login-error-text');
  15100. if (isExpired && errEl && errTxt) {
  15101. errTxt.innerText = 'Session expired. Please sign in again.';
  15102. errEl.classList.remove('hidden');
  15103. } else if (errEl) {
  15104. errEl.classList.add('hidden');
  15105. }
  15106. const pwInput = document.getElementById('login-password');
  15107. if (pwInput) pwInput.value = '';
  15108. const userInput = document.getElementById('login-username');
  15109. if (userInput && !userInput.value) userInput.focus();
  15110. else if (pwInput) pwInput.focus();
  15111. }
  15112. function hideLoginScreen() {
  15113. const el = document.getElementById('login-screen');
  15114. if (el) el.classList.add('hidden');
  15115. const errEl = document.getElementById('login-error');
  15116. if (errEl) errEl.classList.add('hidden');
  15117. }
  15118. async function handleLoginSubmit(event) {
  15119. event.preventDefault();
  15120. const username = (document.getElementById('login-username')?.value || '').trim();
  15121. const password = document.getElementById('login-password')?.value || '';
  15122. const errEl = document.getElementById('login-error');
  15123. const errTxt = document.getElementById('login-error-text');
  15124. const btn = document.getElementById('login-submit-btn');
  15125. const btnText = document.getElementById('login-btn-text');
  15126. const spinner = document.getElementById('login-btn-spinner');
  15127. if (!username || !password) {
  15128. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15129. if (errEl) errEl.classList.remove('hidden');
  15130. return;
  15131. }
  15132. if (errEl) errEl.classList.add('hidden');
  15133. if (btn) btn.disabled = true;
  15134. if (btnText) btnText.innerText = 'Authenticating...';
  15135. if (spinner) spinner.classList.remove('hidden');
  15136. try {
  15137. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15138. method: 'POST',
  15139. headers: { 'Content-Type': 'application/json' },
  15140. body: JSON.stringify({ username, password })
  15141. });
  15142. const data = await res.json();
  15143. if (res.ok && data.success) {
  15144. localStorage.setItem('debtik_token', data.token);
  15145. state.currentUser = data.user;
  15146. updateUserProfileHeader(data.user);
  15147. hideLoginScreen();
  15148. state.isPolling = true;
  15149. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15150. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15151. navigate(hash);
  15152. fetchData();
  15153. initLiveTrafficStream();
  15154. // Ensure background telemetry polling is active
  15155. if (!window._telemetryInterval) {
  15156. window._telemetryInterval = setInterval(() => {
  15157. if (state.isPolling && state.currentUser && !document.hidden) {
  15158. fetchData(false);
  15159. }
  15160. }, 5000);
  15161. }
  15162. } else {
  15163. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15164. if (errEl) errEl.classList.remove('hidden');
  15165. }
  15166. } catch (err) {
  15167. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15168. if (errEl) errEl.classList.remove('hidden');
  15169. } finally {
  15170. if (btn) btn.disabled = false;
  15171. if (btnText) btnText.innerText = 'Sign In to Controller';
  15172. if (spinner) spinner.classList.add('hidden');
  15173. }
  15174. }
  15175. async function handleLogoutClick() {
  15176. try {
  15177. await originalFetch(`${API_BASE}/auth/logout`, {
  15178. method: 'POST',
  15179. headers: {
  15180. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15181. }
  15182. });
  15183. } catch (e) {}
  15184. stopSessionPolling();
  15185. localStorage.removeItem('debtik_token');
  15186. state.currentUser = null;
  15187. state.isPolling = false;
  15188. if (window._telemetryInterval) {
  15189. clearInterval(window._telemetryInterval);
  15190. window._telemetryInterval = null;
  15191. }
  15192. if (trafficEventSource) {
  15193. trafficEventSource.close();
  15194. trafficEventSource = null;
  15195. }
  15196. if (trafficPollFallback) {
  15197. clearInterval(trafficPollFallback);
  15198. trafficPollFallback = null;
  15199. }
  15200. showLoginScreen(false);
  15201. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15202. }
  15203. function togglePasswordVisibility(id) {
  15204. const input = document.getElementById(id);
  15205. if (!input) return;
  15206. input.type = input.type === 'password' ? 'text' : 'password';
  15207. }
  15208. function toggleUserMenu() {
  15209. const menu = document.getElementById('user-menu-dropdown');
  15210. if (menu) menu.classList.toggle('hidden');
  15211. }
  15212. function closeUserMenu() {
  15213. const menu = document.getElementById('user-menu-dropdown');
  15214. if (menu) menu.classList.add('hidden');
  15215. }
  15216. // Close user menu on outside click
  15217. document.addEventListener('click', (e) => {
  15218. const menu = document.getElementById('user-menu-dropdown');
  15219. if (!menu || menu.classList.contains('hidden')) return;
  15220. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15221. menu.classList.add('hidden');
  15222. }
  15223. });
  15224. function updateUserProfileHeader(user) {
  15225. if (!user) return;
  15226. const navName = document.getElementById('nav-user-name');
  15227. if (navName) navName.innerText = user.username;
  15228. const dropName = document.getElementById('dropdown-user-name');
  15229. if (dropName) dropName.innerText = user.username;
  15230. const navRole = document.getElementById('nav-user-role');
  15231. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15232. const navAvatar = document.getElementById('nav-user-avatar');
  15233. if (navAvatar) {
  15234. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15235. navAvatar.innerText = initials;
  15236. }
  15237. const statCurUser = document.getElementById('stat-current-user');
  15238. if (statCurUser) statCurUser.innerText = user.username;
  15239. const statCurRole = document.getElementById('stat-current-role');
  15240. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15241. // Role permissions UI visibility: hide user management for non-admins
  15242. const isFullAdmin = user.role === 'full';
  15243. const navUsers = document.getElementById('nav-users');
  15244. if (navUsers) {
  15245. if (isFullAdmin) navUsers.classList.remove('hidden');
  15246. else navUsers.classList.add('hidden');
  15247. }
  15248. const dropdownUsers = document.getElementById('dropdown-item-users');
  15249. if (dropdownUsers) {
  15250. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15251. else dropdownUsers.classList.add('hidden');
  15252. }
  15253. }
  15254. // ================= User Management CRUD =================
  15255. async function loadUsers(isManual = false) {
  15256. try {
  15257. const res = await fetch(`${API_BASE}/users`);
  15258. if (res.status === 403) {
  15259. const tbody = document.getElementById('users-table-tbody');
  15260. if (tbody) {
  15261. tbody.innerHTML = `
  15262. <tr>
  15263. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15264. <div class="inline-flex items-center gap-2">
  15265. <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>
  15266. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15267. </div>
  15268. </td>
  15269. </tr>
  15270. `;
  15271. }
  15272. return;
  15273. }
  15274. if (res.ok) {
  15275. state.users = await res.json();
  15276. renderUsersTable();
  15277. const totalUsers = document.getElementById('stat-total-users');
  15278. if (totalUsers) totalUsers.innerText = state.users.length;
  15279. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15280. const adminUsers = document.getElementById('stat-admin-users');
  15281. if (adminUsers) adminUsers.innerText = adminCount;
  15282. const badgeCount = document.getElementById('badge-users-count');
  15283. if (badgeCount) badgeCount.innerText = state.users.length;
  15284. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15285. }
  15286. } catch (err) {
  15287. console.error('Failed to load users:', err);
  15288. }
  15289. }
  15290. function renderUsersTable() {
  15291. const tbody = document.getElementById('users-table-tbody');
  15292. const emptyState = document.getElementById('users-empty-state');
  15293. if (!tbody) return;
  15294. tbody.innerHTML = '';
  15295. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15296. const filtered = (state.users || []).filter(u => {
  15297. if (!query) return true;
  15298. return u.username.toLowerCase().includes(query) ||
  15299. (u.role || '').toLowerCase().includes(query) ||
  15300. (u.comment || '').toLowerCase().includes(query);
  15301. });
  15302. if (filtered.length === 0) {
  15303. if (emptyState) emptyState.classList.remove('hidden');
  15304. return;
  15305. }
  15306. if (emptyState) emptyState.classList.add('hidden');
  15307. const currentAuthUser = state.currentUser?.username || '';
  15308. filtered.forEach(u => {
  15309. const isSelf = u.username === currentAuthUser;
  15310. const isFull = u.role === 'full';
  15311. const isWrite = u.role === 'write';
  15312. 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>`;
  15313. if (isFull) {
  15314. 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>`;
  15315. } else if (isWrite) {
  15316. 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>`;
  15317. }
  15318. const statusBadge = u.disabled
  15319. ? `<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>`
  15320. : `<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>`;
  15321. let lastLoginText = 'Never';
  15322. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15323. const dt = new Date(u.last_login_at);
  15324. lastLoginText = dt.toLocaleString();
  15325. }
  15326. const initials = u.username.slice(0, 2).toUpperCase();
  15327. const tr = document.createElement('tr');
  15328. tr.className = 'hover:bg-slate-800/40 transition group';
  15329. tr.innerHTML = `
  15330. <td class="py-3 px-4">
  15331. <div class="flex items-center gap-3">
  15332. <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">
  15333. ${initials}
  15334. </div>
  15335. <div>
  15336. <div class="font-bold text-white text-xs flex items-center gap-2">
  15337. <span>${escapeHtml(u.username)}</span>
  15338. ${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>' : ''}
  15339. </div>
  15340. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15341. </div>
  15342. </div>
  15343. </td>
  15344. <td class="py-3 px-4 font-sans">
  15345. ${roleBadge}
  15346. </td>
  15347. <td class="py-3 px-4 font-sans">
  15348. ${statusBadge}
  15349. </td>
  15350. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15351. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15352. </td>
  15353. <td class="py-3 px-4 text-slate-400 text-xs">
  15354. ${lastLoginText}
  15355. </td>
  15356. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15357. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15358. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15359. <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>
  15360. </button>
  15361. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15362. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15363. <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>
  15364. </button>
  15365. ${!isSelf ? `
  15366. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15367. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15368. <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>
  15369. </button>
  15370. ` : ''}
  15371. </td>
  15372. `;
  15373. tbody.appendChild(tr);
  15374. });
  15375. }
  15376. function openAddUserModal() {
  15377. document.getElementById('user-add-username').value = '';
  15378. document.getElementById('user-add-password').value = '';
  15379. document.getElementById('user-add-confirm').value = '';
  15380. document.getElementById('user-add-role').value = 'full';
  15381. document.getElementById('user-add-comment').value = '';
  15382. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15383. document.getElementById('user-add-username')?.focus();
  15384. }
  15385. function closeAddUserModal() {
  15386. document.getElementById('modal-add-user')?.classList.add('hidden');
  15387. }
  15388. async function submitAddUser(event) {
  15389. event.preventDefault();
  15390. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15391. const password = document.getElementById('user-add-password')?.value || '';
  15392. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15393. const role = document.getElementById('user-add-role')?.value || 'full';
  15394. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15395. if (password !== confirm) {
  15396. showToast('Validation Error', 'Passwords do not match', 'warning');
  15397. return;
  15398. }
  15399. if (password.length < 4) {
  15400. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15401. return;
  15402. }
  15403. try {
  15404. const res = await fetch(`${API_BASE}/users`, {
  15405. method: 'POST',
  15406. headers: { 'Content-Type': 'application/json' },
  15407. body: JSON.stringify({ username, password, role, comment })
  15408. });
  15409. const data = await res.json();
  15410. if (res.ok) {
  15411. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15412. closeAddUserModal();
  15413. loadUsers(false);
  15414. } else {
  15415. showToast('Error', data.message || 'Failed to create user', 'error');
  15416. }
  15417. } catch (err) {
  15418. showToast('Error', err.message, 'error');
  15419. }
  15420. }
  15421. function openEditUserModal(username) {
  15422. const user = (state.users || []).find(u => u.username === username);
  15423. if (!user) return;
  15424. document.getElementById('user-edit-username').value = user.username;
  15425. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15426. document.getElementById('user-edit-role').value = user.role || 'read';
  15427. document.getElementById('user-edit-comment').value = user.comment || '';
  15428. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15429. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15430. }
  15431. function closeEditUserModal() {
  15432. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15433. }
  15434. async function submitEditUser(event) {
  15435. event.preventDefault();
  15436. const username = document.getElementById('user-edit-username')?.value;
  15437. const role = document.getElementById('user-edit-role')?.value || 'read';
  15438. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15439. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15440. try {
  15441. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15442. method: 'PUT',
  15443. headers: { 'Content-Type': 'application/json' },
  15444. body: JSON.stringify({ role, comment, disabled })
  15445. });
  15446. const data = await res.json();
  15447. if (res.ok) {
  15448. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15449. closeEditUserModal();
  15450. loadUsers(false);
  15451. // If updated own role/disabled status, refresh self profile
  15452. if (username === state.currentUser?.username) {
  15453. checkAuthStatus();
  15454. }
  15455. } else {
  15456. showToast('Error', data.message || 'Failed to update user', 'error');
  15457. }
  15458. } catch (err) {
  15459. showToast('Error', err.message, 'error');
  15460. }
  15461. }
  15462. function openAdminResetPasswordModal(username) {
  15463. document.getElementById('admin-reset-username').value = username;
  15464. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15465. document.getElementById('admin-reset-new-pw').value = '';
  15466. document.getElementById('admin-reset-confirm-pw').value = '';
  15467. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15468. document.getElementById('admin-reset-new-pw')?.focus();
  15469. }
  15470. function closeAdminResetPasswordModal() {
  15471. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15472. }
  15473. async function submitAdminResetPassword(event) {
  15474. event.preventDefault();
  15475. const username = document.getElementById('admin-reset-username')?.value;
  15476. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15477. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15478. if (newPassword !== confirm) {
  15479. showToast('Validation Error', 'Passwords do not match', 'warning');
  15480. return;
  15481. }
  15482. if (newPassword.length < 4) {
  15483. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15484. return;
  15485. }
  15486. try {
  15487. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15488. method: 'POST',
  15489. headers: { 'Content-Type': 'application/json' },
  15490. body: JSON.stringify({ new_password: newPassword })
  15491. });
  15492. const data = await res.json();
  15493. if (res.ok) {
  15494. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15495. closeAdminResetPasswordModal();
  15496. } else {
  15497. showToast('Error', data.message || 'Failed to reset password', 'error');
  15498. }
  15499. } catch (err) {
  15500. showToast('Error', err.message, 'error');
  15501. }
  15502. }
  15503. async function deleteUser(username) {
  15504. if (username === state.currentUser?.username) {
  15505. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15506. return;
  15507. }
  15508. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15509. return;
  15510. }
  15511. try {
  15512. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15513. method: 'DELETE'
  15514. });
  15515. const data = await res.json();
  15516. if (res.ok) {
  15517. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15518. loadUsers(false);
  15519. } else {
  15520. showToast('Error', data.message || 'Failed to delete user', 'error');
  15521. }
  15522. } catch (err) {
  15523. showToast('Error', err.message, 'error');
  15524. }
  15525. }
  15526. function openSelfPasswordModal() {
  15527. document.getElementById('self-current-password').value = '';
  15528. document.getElementById('self-new-password').value = '';
  15529. document.getElementById('self-confirm-password').value = '';
  15530. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15531. document.getElementById('self-current-password')?.focus();
  15532. }
  15533. function closeSelfPasswordModal() {
  15534. document.getElementById('modal-self-password')?.classList.add('hidden');
  15535. }
  15536. async function submitSelfPassword(event) {
  15537. event.preventDefault();
  15538. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15539. const newPassword = document.getElementById('self-new-password')?.value || '';
  15540. const confirm = document.getElementById('self-confirm-password')?.value || '';
  15541. if (newPassword !== confirm) {
  15542. showToast('Validation Error', 'New passwords do not match', 'warning');
  15543. return;
  15544. }
  15545. if (newPassword.length < 4) {
  15546. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15547. return;
  15548. }
  15549. try {
  15550. const res = await fetch(`${API_BASE}/auth/change-password`, {
  15551. method: 'POST',
  15552. headers: { 'Content-Type': 'application/json' },
  15553. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15554. });
  15555. const data = await res.json();
  15556. if (res.ok) {
  15557. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15558. closeSelfPasswordModal();
  15559. } else {
  15560. showToast('Error', data.message || 'Failed to change password', 'error');
  15561. }
  15562. } catch (err) {
  15563. showToast('Error', err.message, 'error');
  15564. }
  15565. }
  15566. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15567. state.services = [];
  15568. async function loadServices(manual = false) {
  15569. try {
  15570. const res = await fetch(`${API_BASE}/system/services`);
  15571. if (!res.ok) throw new Error('Failed to load services');
  15572. const data = await res.json();
  15573. state.services = data || [];
  15574. renderServicesTable();
  15575. updateCertificatesBadges();
  15576. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15577. } catch (err) {
  15578. if (manual) showToast('Error', err.message, 'error');
  15579. }
  15580. }
  15581. function renderServicesTable() {
  15582. const tbody = document.getElementById('services-table-body');
  15583. if (!tbody) return;
  15584. if (!state.services || state.services.length === 0) {
  15585. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15586. return;
  15587. }
  15588. tbody.innerHTML = state.services.map(s => {
  15589. const isOff = s.disabled;
  15590. const statusBadge = isOff
  15591. ? '<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>'
  15592. : '<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>';
  15593. const toggleBtn = isOff
  15594. ? `<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>`
  15595. : `<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>`;
  15596. let certBadge = '';
  15597. if (s.name === 'www-ssl') {
  15598. if (s.certificate) {
  15599. 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>`;
  15600. } else {
  15601. 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>`;
  15602. }
  15603. }
  15604. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15605. return `
  15606. <tr class="hover:bg-slate-800/40 transition">
  15607. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15608. <td class="py-3 px-4">
  15609. <div class="flex items-center gap-2">
  15610. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15611. <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">
  15612. <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>
  15613. </button>
  15614. </div>
  15615. </td>
  15616. <td class="py-3 px-4">${statusBadge}</td>
  15617. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  15618. <td class="py-3 px-4 text-right">
  15619. <div class="flex items-center justify-end gap-2">
  15620. <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">
  15621. <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>
  15622. <span>Edit</span>
  15623. </button>
  15624. ${toggleBtn}
  15625. </div>
  15626. </td>
  15627. </tr>
  15628. `;
  15629. }).join('');
  15630. }
  15631. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  15632. document.getElementById('modal-service-name').value = serviceName;
  15633. document.getElementById('modal-service-disabled').value = String(isDisabled);
  15634. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  15635. document.getElementById('modal-service-port').value = currentPort;
  15636. const hintEl = document.getElementById('modal-service-port-hint');
  15637. const warnEl = document.getElementById('modal-service-warning');
  15638. const certGroup = document.getElementById('modal-service-cert-group');
  15639. const certSelect = document.getElementById('modal-service-cert-select');
  15640. if (serviceName === 'www') {
  15641. hintEl.textContent = 'Default HTTP web port: 80';
  15642. warnEl.classList.remove('hidden');
  15643. certGroup.classList.add('hidden');
  15644. } else if (serviceName === 'www-ssl') {
  15645. hintEl.textContent = 'Default HTTPS web port: 443';
  15646. warnEl.classList.remove('hidden');
  15647. certGroup.classList.remove('hidden');
  15648. const populateCertOptions = (certs) => {
  15649. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15650. (certs || []).forEach(c => {
  15651. const opt = document.createElement('option');
  15652. opt.value = c.name;
  15653. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15654. if (c.name === currentCert) opt.selected = true;
  15655. certSelect.appendChild(opt);
  15656. });
  15657. };
  15658. if (state.certificates && state.certificates.length > 0) {
  15659. populateCertOptions(state.certificates);
  15660. } else {
  15661. loadCertificates(false).then(() => {
  15662. populateCertOptions(state.certificates);
  15663. });
  15664. }
  15665. } else if (serviceName === 'telnet') {
  15666. hintEl.textContent = 'Default Telnet console port: 8282';
  15667. warnEl.classList.add('hidden');
  15668. certGroup.classList.add('hidden');
  15669. } else if (serviceName === 'ssh') {
  15670. hintEl.textContent = 'Default SSH port: 2222';
  15671. warnEl.classList.add('hidden');
  15672. certGroup.classList.add('hidden');
  15673. } else {
  15674. hintEl.textContent = '';
  15675. warnEl.classList.add('hidden');
  15676. certGroup.classList.add('hidden');
  15677. }
  15678. const modal = document.getElementById('modal-service-edit');
  15679. modal.classList.remove('hidden');
  15680. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15681. }
  15682. function closeEditServiceModal() {
  15683. const modal = document.getElementById('modal-service-edit');
  15684. if (modal) modal.classList.add('hidden');
  15685. }
  15686. async function submitSaveServicePort(event) {
  15687. event.preventDefault();
  15688. const name = document.getElementById('modal-service-name').value;
  15689. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15690. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15691. if (isNaN(port) || port < 1 || port > 65535) {
  15692. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15693. return;
  15694. }
  15695. const certSelect = document.getElementById('modal-service-cert-select');
  15696. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15697. try {
  15698. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15699. method: 'POST',
  15700. headers: { 'Content-Type': 'application/json' },
  15701. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15702. });
  15703. if (!res.ok) {
  15704. const errData = await res.json();
  15705. throw new Error(errData.message || 'Failed to update service settings');
  15706. }
  15707. closeEditServiceModal();
  15708. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15709. await loadServices();
  15710. } catch (err) {
  15711. showToast('Error', err.message, 'error');
  15712. }
  15713. }
  15714. async function toggleServiceState(serviceName, newDisabled) {
  15715. if (serviceName === 'www' && newDisabled) {
  15716. 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?")) {
  15717. return;
  15718. }
  15719. }
  15720. if (serviceName === 'www-ssl' && !newDisabled) {
  15721. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15722. if (!sslSvc || !sslSvc.certificate) {
  15723. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15724. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15725. return;
  15726. }
  15727. }
  15728. try {
  15729. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15730. method: 'POST',
  15731. headers: { 'Content-Type': 'application/json' },
  15732. body: JSON.stringify({ disabled: newDisabled })
  15733. });
  15734. if (!res.ok) {
  15735. const errData = await res.json();
  15736. throw new Error(errData.message || 'Failed to update service');
  15737. }
  15738. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15739. await loadServices();
  15740. } catch (err) {
  15741. showToast('Error', err.message, 'error');
  15742. }
  15743. }
  15744. // ==================== SYSTEM LOGS (/log) ====================
  15745. state.logs = [];
  15746. let logsTimer = null;
  15747. async function loadLogs(manual = false) {
  15748. const limitEl = document.getElementById('logs-limit-select');
  15749. const limit = limitEl ? limitEl.value : '100';
  15750. try {
  15751. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15752. if (!res.ok) throw new Error('Failed to load logs');
  15753. const data = await res.json();
  15754. state.logs = data.logs || [];
  15755. renderLogsTable();
  15756. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15757. } catch (err) {
  15758. if (manual) showToast('Error', err.message, 'error');
  15759. }
  15760. // Setup auto-refresh if enabled and on logs tab
  15761. if (!logsTimer && state.currentUser) {
  15762. logsTimer = setInterval(() => {
  15763. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15764. const auto = document.getElementById('logs-auto-refresh');
  15765. if (auto && auto.checked) {
  15766. loadLogs(false);
  15767. }
  15768. }
  15769. }, 3000);
  15770. }
  15771. }
  15772. function renderLogsTable() {
  15773. const tbody = document.getElementById('logs-table-body');
  15774. if (!tbody) return;
  15775. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15776. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15777. const filtered = state.logs.filter(entry => {
  15778. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15779. return false;
  15780. }
  15781. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15782. return false;
  15783. }
  15784. return true;
  15785. });
  15786. if (filtered.length === 0) {
  15787. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15788. return;
  15789. }
  15790. tbody.innerHTML = filtered.map(l => {
  15791. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15792. const topLower = l.topics.toLowerCase();
  15793. if (topLower.includes('auth')) {
  15794. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15795. } else if (topLower.includes('dhcp')) {
  15796. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15797. } else if (topLower.includes('route')) {
  15798. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15799. } else if (topLower.includes('firewall')) {
  15800. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15801. } else if (topLower.includes('error')) {
  15802. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15803. } else if (topLower.includes('system')) {
  15804. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15805. }
  15806. const d = new Date(l.time);
  15807. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15808. return `
  15809. <tr class="hover:bg-slate-800/40 transition">
  15810. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15811. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15812. <td class="py-2 px-3 whitespace-nowrap">
  15813. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15814. </td>
  15815. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15816. </tr>
  15817. `;
  15818. }).join('');
  15819. }
  15820. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15821. state.certificates = [];
  15822. async function loadCertificates(manual = false) {
  15823. try {
  15824. const res = await fetch(`${API_BASE}/certificates`);
  15825. if (!res.ok) throw new Error('Failed to load certificates');
  15826. state.certificates = await res.json() || [];
  15827. updateCertificatesBadges();
  15828. renderCertificatesTable();
  15829. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15830. } catch (err) {
  15831. if (manual) showToast('Error', err.message, 'error');
  15832. }
  15833. }
  15834. function updateCertificatesBadges() {
  15835. const total = (state.certificates || []).length;
  15836. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15837. const bCount = document.getElementById('badge-certs-count');
  15838. if (bCount) bCount.innerText = total;
  15839. const kpiTotal = document.getElementById('kpi-certs-total');
  15840. if (kpiTotal) kpiTotal.innerText = total;
  15841. const kpiCA = document.getElementById('kpi-certs-ca');
  15842. if (kpiCA) kpiCA.innerText = caCount;
  15843. const kpiHttps = document.getElementById('kpi-https-status');
  15844. if (kpiHttps) {
  15845. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15846. if (sslSvc) {
  15847. if (!sslSvc.disabled) {
  15848. 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>`;
  15849. } else {
  15850. 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>`;
  15851. }
  15852. }
  15853. }
  15854. }
  15855. function renderCertificatesTable() {
  15856. const tbody = document.getElementById('certs-table-body');
  15857. if (!tbody) return;
  15858. if (!state.certificates || state.certificates.length === 0) {
  15859. 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>';
  15860. return;
  15861. }
  15862. tbody.innerHTML = state.certificates.map(c => {
  15863. let typeBadge = '';
  15864. if (c.is_ca) {
  15865. 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>';
  15866. } else if (c.type === 'acme') {
  15867. 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>';
  15868. } else if (c.issuer && c.issuer !== c.common_name) {
  15869. 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>';
  15870. } else {
  15871. 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>';
  15872. }
  15873. const sansHtml = (c.sans && c.sans.length > 0)
  15874. ? 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('')
  15875. : '<span class="text-slate-500">-</span>';
  15876. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15877. let validStr = '-';
  15878. let validBadge = '';
  15879. if (validTo && !isNaN(validTo.getTime())) {
  15880. const now = new Date();
  15881. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15882. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15883. if (daysLeft < 0) {
  15884. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15885. } else if (daysLeft < 30) {
  15886. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15887. } else {
  15888. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15889. }
  15890. }
  15891. return `
  15892. <tr class="hover:bg-slate-800/40 transition">
  15893. <td class="py-3 px-4">${typeBadge}</td>
  15894. <td class="py-3 px-4">
  15895. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15896. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15897. </td>
  15898. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15899. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15900. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15901. <span>${validStr}</span> ${validBadge}
  15902. ${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>` : ''}
  15903. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15904. </td>
  15905. <td class="py-3 px-4 text-right whitespace-nowrap">
  15906. <div class="flex items-center justify-end gap-1.5">
  15907. <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">
  15908. <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>
  15909. <span>View</span>
  15910. </button>
  15911. <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">
  15912. <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>
  15913. </button>
  15914. </div>
  15915. </td>
  15916. </tr>
  15917. `;
  15918. }).join('');
  15919. }
  15920. // Create CA
  15921. function openCreateCAModal() {
  15922. document.getElementById('form-create-ca').reset();
  15923. document.getElementById('ca-days').value = '3650';
  15924. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15925. document.getElementById('ca-country').value = 'GR';
  15926. document.getElementById('ca-key-type').value = 'RSA-2048';
  15927. document.getElementById('modal-create-ca').classList.remove('hidden');
  15928. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15929. }
  15930. function closeCreateCAModal() {
  15931. document.getElementById('modal-create-ca').classList.add('hidden');
  15932. }
  15933. async function submitCreateCA(event) {
  15934. event.preventDefault();
  15935. const payload = {
  15936. name: document.getElementById('ca-name').value.trim(),
  15937. common_name: document.getElementById('ca-cn').value.trim(),
  15938. organization: document.getElementById('ca-org').value.trim(),
  15939. country: document.getElementById('ca-country').value.trim(),
  15940. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15941. key_type: document.getElementById('ca-key-type').value
  15942. };
  15943. try {
  15944. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15945. method: 'POST',
  15946. headers: { 'Content-Type': 'application/json' },
  15947. body: JSON.stringify(payload)
  15948. });
  15949. if (!res.ok) {
  15950. const errData = await res.json();
  15951. throw new Error(errData.message || 'Failed to create CA');
  15952. }
  15953. closeCreateCAModal();
  15954. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15955. await loadCertificates();
  15956. } catch (err) {
  15957. showToast('Error', err.message, 'error');
  15958. }
  15959. }
  15960. // Create Cert
  15961. function openCreateCertModal() {
  15962. document.getElementById('form-create-cert').reset();
  15963. document.getElementById('cert-days').value = '730';
  15964. document.getElementById('cert-key-type').value = 'RSA-2048';
  15965. const caSelect = document.getElementById('cert-ca-select');
  15966. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15967. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15968. const opt = document.createElement('option');
  15969. opt.value = ca.name;
  15970. opt.textContent = `${ca.name} (${ca.common_name})`;
  15971. caSelect.appendChild(opt);
  15972. });
  15973. document.getElementById('modal-create-cert').classList.remove('hidden');
  15974. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15975. }
  15976. function closeCreateCertModal() {
  15977. document.getElementById('modal-create-cert').classList.add('hidden');
  15978. }
  15979. async function submitCreateCert(event) {
  15980. event.preventDefault();
  15981. const rawSans = document.getElementById('cert-sans').value;
  15982. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15983. const caName = document.getElementById('cert-ca-select').value;
  15984. const payload = {
  15985. name: document.getElementById('cert-name').value.trim(),
  15986. common_name: document.getElementById('cert-cn').value.trim(),
  15987. ca_name: caName,
  15988. sans: sansList,
  15989. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15990. key_type: document.getElementById('cert-key-type').value,
  15991. is_server: true
  15992. };
  15993. try {
  15994. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15995. method: 'POST',
  15996. headers: { 'Content-Type': 'application/json' },
  15997. body: JSON.stringify(payload)
  15998. });
  15999. if (!res.ok) {
  16000. const errData = await res.json();
  16001. throw new Error(errData.message || 'Failed to issue certificate');
  16002. }
  16003. closeCreateCertModal();
  16004. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16005. await loadCertificates();
  16006. } catch (err) {
  16007. showToast('Error', err.message, 'error');
  16008. }
  16009. }
  16010. // Let's Encrypt
  16011. function openLetsEncryptModal() {
  16012. document.getElementById('form-letsencrypt').reset();
  16013. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16014. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16015. }
  16016. function closeLetsEncryptModal() {
  16017. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16018. }
  16019. async function submitLetsEncrypt(event) {
  16020. event.preventDefault();
  16021. const domain = document.getElementById('le-domain').value.trim();
  16022. const email = document.getElementById('le-email').value.trim();
  16023. let name = document.getElementById('le-name').value.trim();
  16024. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16025. const staging = document.getElementById('le-staging').checked;
  16026. const btn = document.getElementById('btn-submit-letsencrypt');
  16027. const origBtnHtml = btn.innerHTML;
  16028. btn.disabled = true;
  16029. 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>`;
  16030. try {
  16031. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16032. method: 'POST',
  16033. headers: { 'Content-Type': 'application/json' },
  16034. body: JSON.stringify({
  16035. name: name,
  16036. domain: domain,
  16037. email: email,
  16038. staging: staging
  16039. })
  16040. });
  16041. if (!res.ok) {
  16042. const errData = await res.json();
  16043. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16044. }
  16045. closeLetsEncryptModal();
  16046. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16047. await loadCertificates();
  16048. } catch (err) {
  16049. showToast('Let\'s Encrypt Error', err.message, 'error');
  16050. } finally {
  16051. btn.disabled = false;
  16052. btn.innerHTML = origBtnHtml;
  16053. }
  16054. }
  16055. // Import Cert
  16056. function openImportCertModal() {
  16057. document.getElementById('form-import-cert').reset();
  16058. document.getElementById('modal-import-cert').classList.remove('hidden');
  16059. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16060. }
  16061. function closeImportCertModal() {
  16062. document.getElementById('modal-import-cert').classList.add('hidden');
  16063. }
  16064. async function submitImportCert(event) {
  16065. event.preventDefault();
  16066. const payload = {
  16067. name: document.getElementById('import-cert-name').value.trim(),
  16068. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16069. key_pem: document.getElementById('import-key-pem').value.trim()
  16070. };
  16071. try {
  16072. const res = await fetch(`${API_BASE}/certificates/import`, {
  16073. method: 'POST',
  16074. headers: { 'Content-Type': 'application/json' },
  16075. body: JSON.stringify(payload)
  16076. });
  16077. if (!res.ok) {
  16078. const errData = await res.json();
  16079. throw new Error(errData.message || 'Failed to import certificate');
  16080. }
  16081. closeImportCertModal();
  16082. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16083. await loadCertificates();
  16084. } catch (err) {
  16085. showToast('Error', err.message, 'error');
  16086. }
  16087. }
  16088. // View / Export Modal
  16089. async function openViewCertModal(name) {
  16090. const c = (state.certificates || []).find(x => x.name === name);
  16091. if (!c) return;
  16092. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16093. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16094. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16095. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16096. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16097. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16098. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16099. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16100. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16101. document.getElementById('modal-view-cert').classList.remove('hidden');
  16102. try {
  16103. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16104. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16105. const data = await res.json();
  16106. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16107. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16108. } catch (err) {
  16109. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16110. document.getElementById('view-key-pem-text').value = '';
  16111. }
  16112. }
  16113. function closeViewCertModal() {
  16114. document.getElementById('modal-view-cert').classList.add('hidden');
  16115. }
  16116. function copyCertPEM() {
  16117. const text = document.getElementById('view-cert-pem-text').value;
  16118. if (!text) return;
  16119. navigator.clipboard.writeText(text).then(() => {
  16120. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16121. }).catch(() => {
  16122. showToast('Error', 'Failed to copy to clipboard', 'error');
  16123. });
  16124. }
  16125. function copyKeyPEM() {
  16126. const text = document.getElementById('view-key-pem-text').value;
  16127. if (!text) return;
  16128. navigator.clipboard.writeText(text).then(() => {
  16129. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16130. }).catch(() => {
  16131. showToast('Error', 'Failed to copy to clipboard', 'error');
  16132. });
  16133. }
  16134. async function deleteCertificate(name) {
  16135. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16136. return;
  16137. }
  16138. try {
  16139. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16140. method: 'DELETE'
  16141. });
  16142. if (!res.ok) {
  16143. const errData = await res.json();
  16144. throw new Error(errData.message || 'Failed to delete certificate');
  16145. }
  16146. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16147. await loadCertificates();
  16148. } catch (err) {
  16149. showToast('Error', err.message, 'error');
  16150. }
  16151. }
  16152. // Refresh immediately when returning to a backgrounded controller tab.
  16153. document.addEventListener('visibilitychange', () => {
  16154. if (!state.currentUser) return;
  16155. if (document.hidden) {
  16156. if (trafficEventSource) trafficEventSource.close();
  16157. trafficEventSource = null;
  16158. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16159. trafficPollFallback = null;
  16160. } else {
  16161. fetchData(false);
  16162. initLiveTrafficStream();
  16163. if (state.activeTab === 'bwtest') loadBwTestView();
  16164. }
  16165. });
  16166. async function loadUpdateStatus(populate = true) {
  16167. try {
  16168. const res = await fetch(`${API_BASE}/update/status`);
  16169. if (!res.ok) throw new Error(await responseError(res));
  16170. const data = await res.json();
  16171. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16172. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16173. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16174. document.getElementById('update-state').textContent = data.state || 'idle';
  16175. document.getElementById('update-log').textContent = data.log || '';
  16176. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16177. }
  16178. async function saveUpdateConfig() {
  16179. try {
  16180. const repository = document.getElementById('update-repository').value.trim();
  16181. const branch = 'master';
  16182. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16183. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16184. if (!res.ok) throw new Error(await responseError(res));
  16185. document.getElementById('update-install-button').disabled = true;
  16186. document.getElementById('update-available').textContent = '—';
  16187. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16188. await loadUpdateStatus(false);
  16189. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16190. }
  16191. async function checkUpdate() {
  16192. try {
  16193. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16194. if (!res.ok) throw new Error(await responseError(res));
  16195. const data = await res.json();
  16196. document.getElementById('update-available').textContent = data.available_version;
  16197. document.getElementById('update-install-button').disabled = !data.update_available;
  16198. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16199. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16200. }
  16201. async function startUpdate(action) {
  16202. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16203. try {
  16204. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16205. if (!res.ok) throw new Error(await responseError(res));
  16206. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16207. await loadUpdateStatus(false);
  16208. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16209. }
  16210. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16211. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16212. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16213. function safeFirewallRow(row) {
  16214. const result = {...row};
  16215. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16216. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16217. return result;
  16218. }
  16219. function setFirewallDays(prefix, days) {
  16220. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16221. 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); }
  16222. }
  16223. function getFirewallDays(prefix) {
  16224. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16225. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16226. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16227. return selected.join(',');
  16228. }
  16229. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16230. const id = document.getElementById(kind+'-modal-id')?.value;
  16231. if (!id) { resetDisplay(); return; }
  16232. try {
  16233. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16234. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16235. resetDisplay(); await loadFirewall(false);
  16236. } catch(error) { showToast('Error', error.message, 'error'); }
  16237. }
  16238. function reviewLegacyFirewallSettings(kind, id) {
  16239. if (!id) return true;
  16240. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16241. const rule = (rows || []).find(r => r.id === id);
  16242. if (!rule) return true;
  16243. 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'];
  16244. const present = unsupported.filter(key => rule[key]);
  16245. if (!present.length) return true;
  16246. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16247. }
  16248. function refreshFirewallRejectTypes() {
  16249. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16250. const old=select.value;
  16251. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16252. 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'];
  16253. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16254. if(types.includes(old))select.value=old;
  16255. }
  16256. function setFirewallActionSelection(kind, value) {
  16257. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16258. if(!Array.from(select.options).some(option=>option.value===value)) {
  16259. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16260. }
  16261. select.value=value;
  16262. }