app.js 736 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. pppSecrets: [],
  109. pppProfiles: [],
  110. pppActiveSessions: [],
  111. pppoeServer: null,
  112. pptpServer: null,
  113. l2tpServer: null,
  114. ipsecServer: null,
  115. ifaceFilter: 'all',
  116. currentModalIface: null,
  117. isPolling: false,
  118. expandedParents: new Set(['eth0']),
  119. pppoeData: null,
  120. wgData: null,
  121. ipsecData: null,
  122. l2tpData: null,
  123. pptpData: null,
  124. fwSummary: null,
  125. filterRules: [],
  126. natRules: [],
  127. mangleRules: [],
  128. addressLists: [],
  129. connections: [],
  130. policyRules: [],
  131. routingTables: [],
  132. routingFilters: [],
  133. filterChainSelected: 'all',
  134. activeToolsSubTab: 'ping',
  135. dhcpClients: [],
  136. dhcpSummary: null,
  137. dhcpServerTab: 'servers',
  138. dhcpServers: [],
  139. dhcpNetworks: [],
  140. dhcpLeases: [],
  141. dhcpOptions: [],
  142. dhcpServerSummary: null
  143. };
  144. const API_BASE = '/api';
  145. function escapeHtml(str) {
  146. if (str === null || str === undefined) return '';
  147. return String(str)
  148. .replace(/&/g, '&')
  149. .replace(/</g, '&lt;')
  150. .replace(/>/g, '&gt;')
  151. .replace(/"/g, '&quot;')
  152. .replace(/'/g, '&#039;');
  153. }
  154. function formatBytes(bytes) {
  155. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  156. const k = 1024;
  157. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  158. const i = Math.floor(Math.log(bytes) / Math.log(k));
  159. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  160. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  161. }
  162. // Initialize on page load
  163. document.addEventListener('DOMContentLoaded', async () => {
  164. initTableSorting();
  165. // Verify authentication before bootstrapping telemetry and views
  166. const isAuthenticated = await checkAuthStatus();
  167. if (isAuthenticated) {
  168. const hash = window.location.hash.replace('#', '') || 'dashboard';
  169. navigate(hash);
  170. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  171. if (!window._telemetryInterval) {
  172. window._telemetryInterval = setInterval(() => {
  173. if (state.isPolling && state.currentUser && !document.hidden) {
  174. fetchData(false);
  175. }
  176. }, 5000);
  177. }
  178. }
  179. });
  180. let trafficEventSource = null;
  181. let trafficPollFallback = null;
  182. function initLiveTrafficStream() {
  183. if (trafficEventSource) {
  184. try { trafficEventSource.close(); } catch(e) {}
  185. trafficEventSource = null;
  186. }
  187. if (trafficPollFallback) {
  188. clearInterval(trafficPollFallback);
  189. trafficPollFallback = null;
  190. }
  191. if (window.EventSource) {
  192. try {
  193. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  194. trafficEventSource.onmessage = (event) => {
  195. try {
  196. const data = JSON.parse(event.data);
  197. updateLiveInterfaceTraffic(data);
  198. } catch (e) {
  199. console.error('Error parsing live traffic event:', e);
  200. }
  201. };
  202. trafficEventSource.onerror = () => {
  203. // Fallback polling if SSE disconnects
  204. if (!trafficPollFallback) {
  205. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  206. }
  207. };
  208. trafficEventSource.onopen = () => {
  209. if (trafficPollFallback) {
  210. clearInterval(trafficPollFallback);
  211. trafficPollFallback = null;
  212. }
  213. };
  214. return;
  215. } catch (e) {
  216. console.warn('EventSource failed, using 1s polling fallback:', e);
  217. }
  218. }
  219. // Fallback if EventSource is unavailable
  220. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  221. }
  222. async function pollLiveTrafficSnapshot() {
  223. try {
  224. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  225. if (res.ok) {
  226. const data = await res.json();
  227. updateLiveInterfaceTraffic(data);
  228. }
  229. } catch (e) {}
  230. }
  231. function updateLiveInterfaceTraffic(data) {
  232. if (!data || !data.interfaces) return;
  233. state.latestTraffic = data;
  234. // 1. Update Top & Dashboard Total Bandwidth Indicators
  235. const rxHuman = data.total_rx_human || '0 B/s';
  236. const txHuman = data.total_tx_human || '0 B/s';
  237. const statRx = document.getElementById('stat-traffic-rx');
  238. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  239. const statTx = document.getElementById('stat-traffic-tx');
  240. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  241. // 2. Update state.interfaces rates in-memory
  242. if (Array.isArray(state.interfaces)) {
  243. state.interfaces.forEach(i => {
  244. const live = data.interfaces[i.name];
  245. if (live) {
  246. i.rate = {
  247. rx_bytes_sec: live.rx_bytes_sec,
  248. tx_bytes_sec: live.tx_bytes_sec,
  249. rx_human: live.rx_human,
  250. tx_human: live.tx_human
  251. };
  252. i.stats = {
  253. rx_bytes: live.rx_bytes,
  254. tx_bytes: live.tx_bytes,
  255. rx_packets: live.rx_packets,
  256. tx_packets: live.tx_packets,
  257. rx_errors: live.rx_errors,
  258. tx_errors: live.tx_errors,
  259. rx_dropped: live.rx_dropped,
  260. tx_dropped: live.tx_dropped
  261. };
  262. }
  263. });
  264. }
  265. // 3. Update all live UI rate spans in-place (ZERO flicker)
  266. Object.keys(data.interfaces).forEach(name => {
  267. const live = data.interfaces[name];
  268. // Dashboard Port Matrix Card
  269. const cardRate = document.getElementById(`port-card-rate-${name}`);
  270. if (cardRate && cardRate.innerText !== live.rx_human) {
  271. cardRate.innerText = live.rx_human;
  272. }
  273. // Dashboard Quick Interfaces Table
  274. const quickRx = document.getElementById(`quick-rx-${name}`);
  275. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  276. const quickTx = document.getElementById(`quick-tx-${name}`);
  277. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  278. // Main Interfaces Tree Table
  279. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  280. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  281. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  282. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  283. // VLAN Sub-interfaces Table
  284. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  285. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  286. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  287. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  288. // VLAN Page Table
  289. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  290. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  291. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  292. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  293. });
  294. }
  295. // Navigation Handler
  296. function navigate(tabName) {
  297. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  298. navigate('bgp');
  299. return;
  300. }
  301. if (tabName === 'vlans') {
  302. navigate('interfaces');
  303. return;
  304. }
  305. if (tabName === 'persistence') {
  306. navigate('dashboard');
  307. return;
  308. }
  309. stopFwStatPolling();
  310. stopNATStatPolling();
  311. stopMangleStatPolling();
  312. state.activeTab = tabName;
  313. window.location.hash = tabName;
  314. // Update nav links styling
  315. document.querySelectorAll('.nav-link').forEach(link => {
  316. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  317. });
  318. const activeNav = document.getElementById(`nav-${tabName}`);
  319. if (activeNav) {
  320. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  321. }
  322. // Update page headers
  323. const titles = {
  324. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  325. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  326. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  327. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  328. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  329. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  330. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  331. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  332. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  333. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  334. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  335. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  336. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  337. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  338. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  339. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  340. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  341. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  342. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  343. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  344. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  345. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  346. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  347. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  348. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  349. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  350. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  351. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  352. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  353. };
  354. const header = titles[tabName] || titles.dashboard;
  355. const pTitle = document.getElementById('page-title');
  356. if (pTitle) pTitle.innerText = header.title;
  357. const pSub = document.getElementById('page-subtitle');
  358. if (pSub) pSub.innerText = header.sub;
  359. // Toggle sections dynamically for all section elements
  360. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  361. if (el.id === `section-${tabName}`) {
  362. el.classList.remove('hidden');
  363. } else {
  364. el.classList.add('hidden');
  365. }
  366. });
  367. if (tabName === 'interfaces') {
  368. loadRoles();
  369. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  370. else switchIfaceSubTab('tree');
  371. }
  372. if (tabName === 'bridge') loadBridge();
  373. if (tabName === 'firewall') loadFirewall();
  374. if (tabName === 'routes') loadRoutes();
  375. if (tabName === 'bgp') {
  376. loadDynamicRouting();
  377. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  378. }
  379. if (tabName === 'ospf') {
  380. loadDynamicRouting();
  381. switchOspfTab(state.activeOspfTab || 'instances');
  382. }
  383. if (tabName === 'routing-filters') loadDynamicRouting();
  384. if (tabName === 'dynamic-routing') loadDynamicRouting();
  385. if (tabName === 'ppp') loadPPP();
  386. if (tabName === 'eoip') loadEoIP();
  387. if (tabName === 'aerotun') loadAeroTUN();
  388. if (tabName === 'pppoe') loadPPPoE();
  389. if (tabName === 'wireguard') loadWireGuard();
  390. if (tabName === 'ipsec') loadIPSec();
  391. if (tabName === 'l2tp') loadL2TP();
  392. if (tabName === 'pptp') loadPPTP();
  393. if (tabName === 'tools') loadToolsView();
  394. if (tabName === 'dhcp-client') loadDHCPClients();
  395. if (tabName === 'dhcp-server') loadDHCPServer();
  396. if (tabName === 'vrrp') loadVRRP();
  397. if (tabName === 'bwtest') loadBwTestView();
  398. if (tabName === 'settings') loadSettingsData();
  399. if (tabName === 'users') loadUsers();
  400. if (tabName === 'certificates') loadCertificates();
  401. if (tabName === 'services') loadServices();
  402. if (tabName === 'updates') loadUpdateStatus();
  403. if (tabName === 'logs') loadLogs();
  404. setTimeout(initTableSorting, 50);
  405. }
  406. // Fetch all core system, network and VPN telemetry
  407. function fetchData(isManual = false) {
  408. if (coreRefreshPromise) return coreRefreshPromise;
  409. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  410. return coreRefreshPromise;
  411. }
  412. async function refreshCoreData(isManual = false) {
  413. const spinner = document.getElementById('refresh-spinner');
  414. if (isManual && spinner) spinner.classList.add('animate-spin');
  415. try {
  416. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  417. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  418. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  419. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  420. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  421. summaryFetch('/vlans'),
  422. summaryFetch('/vpn/status'),
  423. summaryFetch('/firewall/summary'),
  424. summaryFetch('/routing/dynamic/summary'),
  425. summaryFetch('/bridge/summary'),
  426. summaryFetch('/dhcp/clients/summary'),
  427. summaryFetch('/dhcp/clients'),
  428. summaryFetch('/vrrp/summary').catch(() => null),
  429. summaryFetch('/roles').catch(() => null)
  430. ]);
  431. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  432. if (rolesRes && rolesRes.ok) {
  433. state.roles = await rolesRes.json();
  434. const countEl = document.getElementById('badge-roles-count');
  435. if (countEl) countEl.innerText = (state.roles || []).length;
  436. }
  437. if (vrrpSumRes && vrrpSumRes.ok) {
  438. state.vrrpSummary = await vrrpSumRes.json();
  439. renderVRRPSummary();
  440. }
  441. if (dhcpSumRes && dhcpSumRes.ok) {
  442. state.dhcpSummary = await dhcpSumRes.json();
  443. const bDhcp = document.getElementById('badge-dhcp-client-count');
  444. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  445. }
  446. if (dhcpClientsRes && dhcpClientsRes.ok) {
  447. state.dhcpClients = await dhcpClientsRes.json();
  448. }
  449. if (brSummaryRes.ok) {
  450. state.bridgeSummary = await brSummaryRes.json();
  451. const bBridge = document.getElementById('badge-bridge-count');
  452. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  453. const sBr = document.getElementById('bridge-stat-bridges');
  454. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  455. const sPorts = document.getElementById('bridge-stat-ports');
  456. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  457. const sHosts = document.getElementById('bridge-stat-hosts');
  458. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  459. }
  460. if (statusRes.ok) state.systemStatus = await statusRes.json();
  461. if (ifacesRes.ok) {
  462. const ifacesData = await ifacesRes.json();
  463. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  464. state.interfaces = rawIfaces.filter(i => {
  465. if (!i.name) return false;
  466. if (i.name.startsWith('ep_')) return false;
  467. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  468. });
  469. try { populateToolsInterfaces(); } catch (e) {}
  470. }
  471. if (vlansRes.ok) {
  472. const vlansData = await vlansRes.json();
  473. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  474. }
  475. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  476. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  477. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  478. updateSystemMetrics();
  479. updateBadges();
  480. if (state.activeTab === 'dashboard') renderDashboard();
  481. if (state.activeTab === 'interfaces') {
  482. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  483. else renderInterfacesList();
  484. }
  485. if (state.activeTab === 'vlans') renderVlansList();
  486. if (state.activeTab === 'firewall') await loadFirewall(false);
  487. if (state.activeTab === 'routes') await loadRoutes(false);
  488. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
  489. if (state.activeTab === 'ppp') await loadPPP(false);
  490. if (state.activeTab === 'eoip') await loadEoIP(false);
  491. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  492. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  493. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  494. if (state.activeTab === 'ipsec') await loadIPSec(false);
  495. if (state.activeTab === 'l2tp') await loadL2TP(false);
  496. if (state.activeTab === 'pptp') await loadPPTP(false);
  497. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  498. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  499. if (state.activeTab === 'vrrp') await loadVRRP(false);
  500. if (state.activeTab === 'settings') await loadSettingsData(false);
  501. if (state.activeTab === 'users') await loadUsers(false);
  502. if (state.activeTab === 'certificates') await loadCertificates(false);
  503. if (state.activeTab === 'services') await loadServices(false);
  504. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  505. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  506. } catch (err) {
  507. console.error('Failed to fetch router state:', err);
  508. } finally {
  509. if (isManual && spinner) {
  510. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  511. }
  512. }
  513. }
  514. // Update Top KPI and Sidebar Telemetry
  515. function updateSystemMetrics() {
  516. const s = state.systemStatus;
  517. const v = state.vpnStatus;
  518. if (!s) return;
  519. // Sidebar Host & Uptime
  520. const sideHost = document.getElementById('side-hostname');
  521. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  522. const sideUp = document.getElementById('side-uptime');
  523. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  524. const sideGw = document.getElementById('side-gateway-ip');
  525. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  526. // Compute CPU Metrics
  527. let cpuPct = 0;
  528. if (s.cpu_pct !== undefined) {
  529. cpuPct = s.cpu_pct;
  530. } else if (s.cpu_load && s.cpu_load.length > 0) {
  531. const cores = s.cpu_cores || 1;
  532. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  533. }
  534. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  535. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  536. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  537. // Sidebar CPU
  538. const sideCpuVal = document.getElementById('side-cpu-val');
  539. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  540. const sideCpuBar = document.getElementById('side-cpu-bar');
  541. if (sideCpuBar) {
  542. sideCpuBar.style.width = cpuWidth;
  543. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  544. }
  545. // Dashboard CPU Card
  546. const dashCpuVal = document.getElementById('dash-cpu-val');
  547. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  548. const dashCpuBar = document.getElementById('dash-cpu-bar');
  549. if (dashCpuBar) {
  550. dashCpuBar.style.width = cpuWidth;
  551. if (cpuPct > 85) {
  552. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  553. } else if (cpuPct > 65) {
  554. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  555. } else {
  556. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  557. }
  558. }
  559. const dashCpuCores = document.getElementById('dash-cpu-cores');
  560. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  561. const dashCpuLoad = document.getElementById('dash-cpu-load');
  562. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  563. const dashCpuStatus = document.getElementById('dash-cpu-status');
  564. if (dashCpuStatus) {
  565. if (cpuPct > 85) {
  566. dashCpuStatus.innerText = 'High';
  567. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  568. } else if (cpuPct > 65) {
  569. dashCpuStatus.innerText = 'Heavy';
  570. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  571. } else {
  572. dashCpuStatus.innerText = 'Normal';
  573. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  574. }
  575. }
  576. // Compute RAM Metrics
  577. const memPct = Math.round(s.mem_usage_pct || 0);
  578. const memPctStr = `${memPct}%`;
  579. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  580. const usedMB = s.mem_used_mb || 0;
  581. const totalMB = s.mem_total_mb || 0;
  582. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  583. function fmtMemMB(mb) {
  584. if (mb >= 1024) {
  585. return `${(mb / 1024).toFixed(1)} GB`;
  586. }
  587. return `${mb} MB`;
  588. }
  589. // Sidebar RAM
  590. const sideRamVal = document.getElementById('side-ram-val');
  591. if (sideRamVal) sideRamVal.innerText = memPctStr;
  592. const sideRamBar = document.getElementById('side-ram-bar');
  593. if (sideRamBar) sideRamBar.style.width = memWidth;
  594. // Dashboard RAM Card
  595. const dashRamVal = document.getElementById('dash-ram-val');
  596. if (dashRamVal) dashRamVal.innerText = memPctStr;
  597. const dashRamBar = document.getElementById('dash-ram-bar');
  598. if (dashRamBar) {
  599. dashRamBar.style.width = memWidth;
  600. if (memPct > 85) {
  601. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  602. } else if (memPct > 70) {
  603. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  604. } else {
  605. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  606. }
  607. }
  608. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  609. if (dashRamUsedTotal) {
  610. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  611. }
  612. const dashRamFree = document.getElementById('dash-ram-free');
  613. if (dashRamFree) {
  614. dashRamFree.innerText = fmtMemMB(freeMB);
  615. }
  616. const dashRamStatus = document.getElementById('dash-ram-status');
  617. if (dashRamStatus) {
  618. if (memPct > 85) {
  619. dashRamStatus.innerText = 'High';
  620. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  621. } else {
  622. dashRamStatus.innerText = 'Active';
  623. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  624. }
  625. }
  626. // Legacy Dashboard Stats (Safe checks)
  627. const elIfacesUp = document.getElementById('stat-ifaces-up');
  628. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  629. const elIfacesTot = document.getElementById('stat-ifaces-total');
  630. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  631. const elIfacesDown = document.getElementById('stat-ifaces-down');
  632. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  633. const elVlans = document.getElementById('stat-vlans-count');
  634. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  635. // VPN Status Indicators
  636. if (v) {
  637. const totalActive = v.total_active_tunnels || 0;
  638. const statVpnActive = document.getElementById('stat-vpn-active');
  639. if (statVpnActive) statVpnActive.innerText = totalActive;
  640. const tunnelsDot = document.getElementById('tunnels-dot');
  641. const tunnelsLabel = document.getElementById('tunnels-label');
  642. if (tunnelsDot && tunnelsLabel) {
  643. if (totalActive > 0) {
  644. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  645. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  646. } else {
  647. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  648. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  649. }
  650. }
  651. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  652. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  653. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  654. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  655. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  656. }
  657. // Total Live Bandwidth Rate
  658. let totalRx = 0;
  659. let totalTx = 0;
  660. (state.interfaces || []).forEach(i => {
  661. if (i.rate) {
  662. totalRx += i.rate.rx_bytes_sec || 0;
  663. totalTx += i.rate.tx_bytes_sec || 0;
  664. }
  665. });
  666. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  667. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  668. }
  669. function setDotBadge(id, active) {
  670. const el = document.getElementById(id);
  671. if (!el) return;
  672. if (active) {
  673. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  674. } else {
  675. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  676. }
  677. }
  678. function updateBadges() {
  679. const bIfaces = document.getElementById('badge-ifaces-count');
  680. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  681. const bVlans = document.getElementById('badge-vlans-count');
  682. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  683. if (state.fwSummary) {
  684. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  685. const badgeFw = document.getElementById('badge-firewall-count');
  686. if (badgeFw) badgeFw.innerText = totalFwRules;
  687. }
  688. if (state.vpnStatus) {
  689. const v = state.vpnStatus;
  690. const bEoIP = document.getElementById('badge-eoip-count');
  691. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  692. const bAero = document.getElementById('badge-aerotun-count');
  693. if (bAero) bAero.innerText = v.total_aerotun || 0;
  694. const bPPPSess = document.getElementById('badge-ppp-sessions');
  695. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  696. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  697. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  698. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  699. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  700. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  701. }
  702. if (state.dynSummary) {
  703. const d = state.dynSummary;
  704. setDotBadge('badge-bgp-dot', d.bgp_running);
  705. setDotBadge('badge-ospf-dot', d.ospf_running);
  706. const bBgp = document.getElementById('badge-bgp-count');
  707. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  708. const bOspf = document.getElementById('badge-ospf-count');
  709. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  710. const bFilters = document.getElementById('badge-filters-count');
  711. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  712. }
  713. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  714. if (bDhcpServer) {
  715. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  716. }
  717. }
  718. // Render Dashboard View
  719. function renderDashboard() {
  720. const matrix = document.getElementById('port-matrix');
  721. if (!matrix) return;
  722. const ifaces = state.interfaces || [];
  723. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  724. if (matrix.dataset.sig === sig) {
  725. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  726. }
  727. matrix.dataset.sig = sig;
  728. matrix.innerHTML = '';
  729. (state.interfaces || []).forEach(iface => {
  730. const isUp = iface.state === 'UP';
  731. const isVlan = iface.is_vlan;
  732. const portCard = document.createElement('div');
  733. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  734. isUp
  735. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  736. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  737. }`;
  738. portCard.onclick = () => openIfaceModal(iface.name);
  739. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  740. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  741. portCard.innerHTML = `
  742. <div class="flex items-center justify-between mb-2">
  743. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  744. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  745. </div>
  746. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  747. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  748. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  749. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  750. </div>
  751. `;
  752. matrix.appendChild(portCard);
  753. });
  754. const ifaceTbody = document.getElementById('quick-interfaces-table');
  755. if (ifaceTbody) {
  756. ifaceTbody.innerHTML = '';
  757. (state.interfaces || []).forEach(i => {
  758. const isUp = i.state === 'UP';
  759. const tr = document.createElement('tr');
  760. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  761. tr.onclick = () => openIfaceModal(i.name);
  762. const rxStr = i.rate?.rx_human || '0 B/s';
  763. const txStr = i.rate?.tx_human || '0 B/s';
  764. tr.innerHTML = `
  765. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  766. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  767. <span>${i.name}</span>
  768. </td>
  769. <td class="py-2.5 text-slate-300 font-sans">
  770. ${getRoleBadge(i.role || 'LAN')}
  771. </td>
  772. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  773. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  774. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  775. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  776. </td>
  777. <td class="py-2.5 text-right font-sans font-semibold">
  778. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  779. </td>
  780. `;
  781. ifaceTbody.appendChild(tr);
  782. });
  783. }
  784. const vlanTbody = document.getElementById('quick-vlans-table');
  785. if (vlanTbody) {
  786. vlanTbody.innerHTML = '';
  787. }
  788. }
  789. // Expand / Collapse Handlers
  790. function toggleExpand(parentName) {
  791. if (state.expandedParents.has(parentName)) {
  792. state.expandedParents.delete(parentName);
  793. } else {
  794. state.expandedParents.add(parentName);
  795. }
  796. renderInterfacesList();
  797. }
  798. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  799. function supportsVLAN(iface) {
  800. if (!iface) return false;
  801. if (iface.is_vlan) return false;
  802. const name = (iface.name || '').toLowerCase();
  803. const type = (iface.type || '').toLowerCase();
  804. const role = (iface.role || '').toLowerCase();
  805. // Exclude loopback
  806. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  807. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  808. if (type === 'wireguard' || name.startsWith('wg')) return false;
  809. // Exclude PPP / PPPoE
  810. if (type === 'ppp' || name.startsWith('ppp')) return false;
  811. // Exclude other Layer 3 tunnels and dummy devices
  812. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  813. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  814. return false;
  815. }
  816. // If name already contains a dot, it's already a sub-interface
  817. if (name.includes('.')) return false;
  818. return true;
  819. }
  820. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  821. function supportsDHCPClient(iface) {
  822. if (!iface) return false;
  823. const name = (iface.name || '').toLowerCase();
  824. const type = (iface.type || '').toLowerCase();
  825. const role = (iface.role || '').toLowerCase();
  826. // Exclude loopback
  827. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  828. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  829. if (type === 'wireguard' || name.startsWith('wg')) return false;
  830. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  831. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  832. // Exclude other Layer 3 tunnels and dummy devices
  833. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  834. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  835. return false;
  836. }
  837. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  838. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  839. if (isBridgePort) return false;
  840. return true;
  841. }
  842. // Expand / Collapse Handlers
  843. function toggleExpand(parentName) {
  844. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  845. if (childVlans.length === 0) {
  846. // Cannot expand an interface with no VLANs
  847. state.expandedParents.delete(parentName);
  848. return;
  849. }
  850. if (state.expandedParents.has(parentName)) {
  851. state.expandedParents.delete(parentName);
  852. } else {
  853. state.expandedParents.add(parentName);
  854. }
  855. renderInterfacesList();
  856. }
  857. function expandAllIfaces(expand) {
  858. if (expand) {
  859. (state.interfaces || []).forEach(i => {
  860. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  861. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  862. });
  863. } else {
  864. state.expandedParents.clear();
  865. }
  866. renderInterfacesList();
  867. }
  868. // =========================================================================
  869. // INTERFACE ROLE TAGS MANAGEMENT
  870. // =========================================================================
  871. const ROLE_COLORS = {
  872. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  873. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  874. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  875. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  876. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  877. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  878. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  879. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  880. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  881. };
  882. function getRoleBadge(roleName) {
  883. const name = roleName || 'LAN';
  884. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  885. const colorKey = (role?.color || 'blue').toLowerCase();
  886. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  887. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  888. }
  889. function switchIfaceSubTab(subTab) {
  890. state.activeIfaceSubTab = subTab;
  891. const treeTab = document.getElementById('ifaces-subtab-tree');
  892. const rolesTab = document.getElementById('ifaces-subtab-roles');
  893. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  894. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  895. if (subTab === 'roles') {
  896. treeTab?.classList.add('hidden');
  897. rolesTab?.classList.remove('hidden');
  898. if (btnRoles) {
  899. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  900. }
  901. if (btnTree) {
  902. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  903. }
  904. loadRoles();
  905. } else {
  906. rolesTab?.classList.add('hidden');
  907. treeTab?.classList.remove('hidden');
  908. if (btnTree) {
  909. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  910. }
  911. if (btnRoles) {
  912. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  913. }
  914. renderInterfacesList();
  915. }
  916. }
  917. async function loadRoles() {
  918. try {
  919. const res = await fetch(`${API_BASE}/roles`);
  920. if (res.ok) {
  921. state.roles = await res.json();
  922. const countEl = document.getElementById('badge-roles-count');
  923. if (countEl) countEl.innerText = (state.roles || []).length;
  924. renderRolesTable();
  925. populateRoleSelects();
  926. }
  927. } catch (err) {
  928. console.error('Failed to load role tags:', err);
  929. }
  930. }
  931. function renderRolesTable() {
  932. const tbody = document.getElementById('roles-table-body');
  933. const empty = document.getElementById('roles-empty-state');
  934. if (!tbody) return;
  935. const roles = state.roles || [];
  936. if (roles.length === 0) {
  937. tbody.innerHTML = '';
  938. empty?.classList.remove('hidden');
  939. return;
  940. }
  941. empty?.classList.add('hidden');
  942. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  943. if (tbody.dataset.sig === sig) return;
  944. tbody.dataset.sig = sig;
  945. tbody.innerHTML = roles.map(r => {
  946. const colorKey = (r.color || 'blue').toLowerCase();
  947. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  948. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  949. const ifacesChips = ifaces.length > 0
  950. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  951. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  952. return `
  953. <tr class="hover:bg-slate-800/40 transition">
  954. <td class="py-3 px-4">
  955. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  956. ${escapeHtml(r.name)}
  957. </span>
  958. </td>
  959. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  960. <span>${escapeHtml(r.name)}</span>
  961. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  962. </td>
  963. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  964. <span class="inline-flex items-center gap-1.5">
  965. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  966. <span>${escapeHtml(r.color || 'blue')}</span>
  967. </span>
  968. </td>
  969. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  970. <td class="py-3 px-4 font-sans">
  971. <div class="flex flex-wrap items-center">
  972. ${ifacesChips}
  973. </div>
  974. </td>
  975. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  976. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  977. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  978. Edit
  979. </button>
  980. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  981. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  982. Delete
  983. </button>
  984. </td>
  985. </tr>
  986. `;
  987. }).join('');
  988. }
  989. function openRoleModal(id = null) {
  990. const modal = document.getElementById('role-modal');
  991. if (!modal) return;
  992. const idInput = document.getElementById('role-modal-id');
  993. const nameInput = document.getElementById('role-modal-name');
  994. const colorSelect = document.getElementById('role-modal-color');
  995. const descInput = document.getElementById('role-modal-desc');
  996. const title = document.getElementById('role-modal-title');
  997. if (id) {
  998. const role = (state.roles || []).find(r => r.id === id);
  999. if (role) {
  1000. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1001. if (idInput) idInput.value = role.id;
  1002. if (nameInput) nameInput.value = role.name;
  1003. if (colorSelect) colorSelect.value = role.color || 'blue';
  1004. if (descInput) descInput.value = role.description || '';
  1005. }
  1006. } else {
  1007. if (title) title.innerText = 'Add Role Tag';
  1008. if (idInput) idInput.value = '';
  1009. if (nameInput) nameInput.value = '';
  1010. if (colorSelect) colorSelect.value = 'blue';
  1011. if (descInput) descInput.value = '';
  1012. }
  1013. updateRoleModalPreview();
  1014. modal.classList.remove('hidden');
  1015. }
  1016. function closeRoleModal() {
  1017. const modal = document.getElementById('role-modal');
  1018. if (modal) modal.classList.add('hidden');
  1019. }
  1020. function updateRoleModalPreview() {
  1021. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1022. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1023. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1024. const preview = document.getElementById('role-modal-preview');
  1025. if (preview) {
  1026. preview.innerText = name;
  1027. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1028. }
  1029. }
  1030. async function submitSaveRole(e) {
  1031. e.preventDefault();
  1032. const id = document.getElementById('role-modal-id')?.value;
  1033. const name = document.getElementById('role-modal-name')?.value.trim();
  1034. const color = document.getElementById('role-modal-color')?.value;
  1035. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1036. if (!name) return;
  1037. try {
  1038. const payload = { id, name, color, description: desc };
  1039. const method = id ? 'PUT' : 'POST';
  1040. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1041. const res = await fetch(url, {
  1042. method,
  1043. headers: { 'Content-Type': 'application/json' },
  1044. body: JSON.stringify(payload)
  1045. });
  1046. if (res.ok) {
  1047. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1048. closeRoleModal();
  1049. await loadRoles();
  1050. fetchData(false);
  1051. } else {
  1052. const err = await res.json();
  1053. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1054. }
  1055. } catch (err) {
  1056. showToast('Error', err.message, 'error');
  1057. }
  1058. }
  1059. async function deleteRoleTag(id, name) {
  1060. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1063. method: 'DELETE'
  1064. });
  1065. if (res.ok) {
  1066. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1067. await loadRoles();
  1068. fetchData(false);
  1069. } else {
  1070. const err = await res.json();
  1071. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1072. }
  1073. } catch (err) {
  1074. showToast('Error', err.message, 'error');
  1075. }
  1076. }
  1077. function populateRoleSelects(selectedRole = '') {
  1078. const ifaceSelect = document.getElementById('modal-iface-role');
  1079. const vlanSelect = document.getElementById('vlan-role');
  1080. const roles = state.roles || [];
  1081. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1082. if (ifaceSelect) {
  1083. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1084. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1085. ifaceSelect.innerHTML = optionsHtml;
  1086. ifaceSelect.dataset.optionsSig = optionsHtml;
  1087. }
  1088. if (currentVal) ifaceSelect.value = currentVal;
  1089. }
  1090. if (vlanSelect) {
  1091. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1092. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1093. vlanSelect.innerHTML = optionsHtml;
  1094. vlanSelect.dataset.optionsSig = optionsHtml;
  1095. }
  1096. if (currentVal) vlanSelect.value = currentVal;
  1097. }
  1098. }
  1099. // Filter and Render Hierarchical Interfaces List
  1100. function filterIfaces(filter) {
  1101. state.ifaceFilter = filter || 'all';
  1102. renderInterfacesList();
  1103. }
  1104. function renderInterfacesList() {
  1105. const tbody = document.getElementById('interfaces-tree-tbody');
  1106. const emptyState = document.getElementById('interfaces-empty-state');
  1107. const summary = document.getElementById('ifaces-list-summary');
  1108. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1109. const allIfaces = state.interfaces || [];
  1110. const allVlans = state.vlans || [];
  1111. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1112. const filteredParents = parentIfaces.filter(parent => {
  1113. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1114. if (query) {
  1115. const matchName = parent.name.toLowerCase().includes(query);
  1116. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1117. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1118. const matchType = (parent.type || '').toLowerCase().includes(query);
  1119. const matchVlan = childVlans.some(v =>
  1120. v.name.toLowerCase().includes(query) ||
  1121. String(v.vlan_id).includes(query) ||
  1122. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1123. (v.description || '').toLowerCase().includes(query)
  1124. );
  1125. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1126. }
  1127. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1128. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1129. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1130. return true;
  1131. });
  1132. if (summary) {
  1133. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1134. }
  1135. if (filteredParents.length === 0) {
  1136. emptyState?.classList.remove('hidden');
  1137. tbody.innerHTML = '';
  1138. return;
  1139. }
  1140. emptyState?.classList.add('hidden');
  1141. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1142. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1143. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1144. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1145. }).join(';');
  1146. if (tbody.dataset.sig === sig) {
  1147. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1148. }
  1149. tbody.dataset.sig = sig;
  1150. tbody.innerHTML = '';
  1151. filteredParents.forEach(parent => {
  1152. const isUp = parent.state === 'UP';
  1153. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1154. const hasVlans = childVlans.length > 0;
  1155. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1156. const canHaveVlan = supportsVLAN(parent);
  1157. const parentRow = document.createElement('tr');
  1158. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1159. parentRow.innerHTML = `
  1160. <td class="py-3 px-3 text-center">
  1161. ${hasVlans ? `
  1162. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1163. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1164. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1165. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1166. </svg>
  1167. </button>
  1168. ` : `
  1169. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1170. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1171. </div>
  1172. `}
  1173. </td>
  1174. <td class="py-3 px-4">
  1175. <div class="flex items-center space-x-2.5">
  1176. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1177. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1178. </div>
  1179. <div>
  1180. <div class="flex items-center gap-2">
  1181. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1182. <span>${parent.name}</span>
  1183. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1184. </span>
  1185. ${hasVlans ? `
  1186. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1187. ` : `
  1188. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1189. `}
  1190. </div>
  1191. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1192. </div>
  1193. </div>
  1194. </td>
  1195. <td class="py-3 px-4 font-sans">
  1196. <div class="flex items-center gap-1.5">
  1197. ${getRoleBadge(parent.role || 'LAN')}
  1198. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1199. </div>
  1200. </td>
  1201. <td class="py-3 px-4">
  1202. ${parent.ipv4 && parent.ipv4.length > 0
  1203. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1204. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1205. }
  1206. ${(() => {
  1207. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1208. if (!c) return '';
  1209. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1210. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1211. })()}
  1212. </td>
  1213. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1214. <div>${parent.mac || 'N/A'}</div>
  1215. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1216. </td>
  1217. <td class="py-3 px-4 text-[11px]">
  1218. <div class="flex items-center space-x-2">
  1219. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1220. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1221. </div>
  1222. </td>
  1223. <td class="py-3 px-4 font-sans">
  1224. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1225. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1226. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1227. }" title="Click to toggle link status">
  1228. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1229. <span>${parent.state}</span>
  1230. </button>
  1231. </td>
  1232. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1233. ${(() => {
  1234. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1235. if (c) {
  1236. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1237. }
  1238. if (!supportsDHCPClient(parent)) {
  1239. return '';
  1240. }
  1241. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1242. })()}
  1243. ${canHaveVlan ? `
  1244. <button onclick="openVlanModal('${parent.name}')"
  1245. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1246. + Add VLAN
  1247. </button>
  1248. ` : ''}
  1249. <button onclick="openIfaceModal('${parent.name}')"
  1250. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1251. Edit
  1252. </button>
  1253. </td>
  1254. `;
  1255. tbody.appendChild(parentRow);
  1256. if (isExpanded) {
  1257. const drawerRow = document.createElement('tr');
  1258. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1259. const drawerCell = document.createElement('td');
  1260. drawerCell.colSpan = 8;
  1261. drawerCell.className = 'p-0';
  1262. drawerCell.innerHTML = `
  1263. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1264. <div class="flex items-center justify-between mb-3">
  1265. <div class="flex items-center space-x-3">
  1266. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1267. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1268. </span>
  1269. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1270. ${childVlans.length} Attached
  1271. </span>
  1272. </div>
  1273. <button onclick="openVlanModal('${parent.name}')"
  1274. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1275. <span>+ Create VLAN on ${parent.name}</span>
  1276. </button>
  1277. </div>
  1278. ${childVlans.length === 0 ? `
  1279. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1280. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1281. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1282. <span>+ Create Your First VLAN on ${parent.name}</span>
  1283. </button>
  1284. </div>
  1285. ` : `
  1286. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1287. <table class="w-full text-left text-xs font-mono">
  1288. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1289. <tr>
  1290. <th class="py-2.5 px-4">VLAN ID</th>
  1291. <th class="py-2.5 px-4">Interface Device</th>
  1292. <th class="py-2.5 px-4">Subnet Gateway</th>
  1293. <th class="py-2.5 px-4">Role / Alias</th>
  1294. <th class="py-2.5 px-4">MTU</th>
  1295. <th class="py-2.5 px-4">Throughput</th>
  1296. <th class="py-2.5 px-4">Status</th>
  1297. <th class="py-2.5 px-4 text-right">Actions</th>
  1298. </tr>
  1299. </thead>
  1300. <tbody class="divide-y divide-slate-800/70">
  1301. ${childVlans.map(v => {
  1302. const isVlanUp = v.state === 'UP';
  1303. return `
  1304. <tr class="hover:bg-slate-800/40 transition">
  1305. <td class="py-2.5 px-4">
  1306. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1307. VLAN ${v.vlan_id}
  1308. </span>
  1309. </td>
  1310. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1311. <span class="text-cyan-500">└─</span>
  1312. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1313. <span>${v.name}</span>
  1314. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1315. </span>
  1316. </td>
  1317. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1318. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1319. ${(() => {
  1320. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1321. if (!c) return '';
  1322. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1323. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1324. })()}
  1325. </td>
  1326. <td class="py-2.5 px-4 font-sans text-slate-300">
  1327. <div class="flex items-center gap-1.5">
  1328. ${getRoleBadge(v.role || 'LAN')}
  1329. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1330. </div>
  1331. </td>
  1332. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1333. <td class="py-2.5 px-4 text-[11px]">
  1334. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1335. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1336. </td>
  1337. <td class="py-2.5 px-4 font-sans">
  1338. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1339. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1340. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1341. }">
  1342. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1343. <span>${v.state}</span>
  1344. </button>
  1345. </td>
  1346. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1347. ${(() => {
  1348. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1349. if (c) {
  1350. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1351. }
  1352. if (!supportsDHCPClient(v)) {
  1353. return '';
  1354. }
  1355. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1356. })()}
  1357. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1358. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1359. </td>
  1360. </tr>
  1361. `;
  1362. }).join('')}
  1363. </tbody>
  1364. </table>
  1365. </div>
  1366. `}
  1367. </div>
  1368. `;
  1369. drawerRow.appendChild(drawerCell);
  1370. tbody.appendChild(drawerRow);
  1371. }
  1372. });
  1373. }
  1374. // Render VLANs Dedicated View
  1375. function renderVlansList() {
  1376. const tbody = document.getElementById('vlans-table-body');
  1377. if (!tbody) return;
  1378. const emptyState = document.getElementById('vlans-empty-state');
  1379. const countBadge = document.getElementById('vlans-table-count');
  1380. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1381. const allVlans = state.vlans || [];
  1382. if (countBadge) countBadge.innerText = allVlans.length;
  1383. const filtered = allVlans.filter(v => {
  1384. if (!query) return true;
  1385. return v.name.toLowerCase().includes(query) ||
  1386. String(v.vlan_id).includes(query) ||
  1387. (v.description || '').toLowerCase().includes(query) ||
  1388. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1389. });
  1390. if (allVlans.length === 0) {
  1391. emptyState.classList.remove('hidden');
  1392. tbody.innerHTML = '';
  1393. return;
  1394. }
  1395. emptyState.classList.add('hidden');
  1396. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1397. if (tbody.dataset.sig === sig) return;
  1398. tbody.dataset.sig = sig;
  1399. tbody.innerHTML = '';
  1400. filtered.forEach(v => {
  1401. const isUp = v.state === 'UP';
  1402. const tr = document.createElement('tr');
  1403. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1404. tr.innerHTML = `
  1405. <td class="py-3 px-4">
  1406. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1407. VLAN ${v.vlan_id}
  1408. </span>
  1409. </td>
  1410. <td class="py-3 px-4 font-bold text-white">
  1411. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1412. <span>${v.name}</span>
  1413. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1414. </span>
  1415. </td>
  1416. <td class="py-3 px-4 text-slate-300">
  1417. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1418. </td>
  1419. <td class="py-3 px-4 text-emerald-400 font-medium">
  1420. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1421. </td>
  1422. <td class="py-3 px-4 text-slate-300 font-sans">
  1423. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1424. </td>
  1425. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1426. <td class="py-3 px-4 font-sans">
  1427. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1428. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1429. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1430. }">
  1431. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1432. <span>${v.state}</span>
  1433. </button>
  1434. </td>
  1435. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1436. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1437. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1438. </td>
  1439. `;
  1440. tbody.appendChild(tr);
  1441. });
  1442. }
  1443. // Toggle interface UP / DOWN
  1444. async function toggleInterfaceState(name, newState) {
  1445. try {
  1446. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1447. method: 'POST',
  1448. headers: { 'Content-Type': 'application/json' },
  1449. body: JSON.stringify({ state: newState })
  1450. });
  1451. const data = await res.json();
  1452. if (res.ok) {
  1453. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1454. fetchData(false);
  1455. } else {
  1456. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1457. }
  1458. } catch (err) {
  1459. showToast('Error', err.message, 'error');
  1460. }
  1461. }
  1462. // ---------------- MikroTik Flag & Utilities ----------------
  1463. function renderMikroTikFlag(running, disabled) {
  1464. if (running) {
  1465. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1466. }
  1467. if (disabled) {
  1468. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1469. }
  1470. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1471. }
  1472. function copyToClipboard(text, label = 'Text') {
  1473. navigator.clipboard.writeText(text).then(() => {
  1474. showToast('Copied', `${label} copied to clipboard`, 'success');
  1475. }).catch(() => {
  1476. prompt('Copy value:', text);
  1477. });
  1478. }
  1479. // ======================== PPP Profiles Shared Helper ========================
  1480. async function fetchPPPProfilesList() {
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1483. if (res.ok) {
  1484. state.pppProfiles = await res.json();
  1485. }
  1486. } catch (err) {
  1487. console.error('Failed to load PPP profiles:', err);
  1488. }
  1489. }
  1490. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1491. const sel = document.getElementById(selectId);
  1492. if (!sel) return;
  1493. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1494. { name: 'default', use_encryption: 'no' },
  1495. { name: 'default-encryption', use_encryption: 'required' }
  1496. ];
  1497. sel.innerHTML = '';
  1498. profiles.forEach(p => {
  1499. const opt = document.createElement('option');
  1500. opt.value = p.name;
  1501. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1502. opt.innerText = `${p.name}${encBadge}`;
  1503. sel.appendChild(opt);
  1504. });
  1505. if (selectedVal) {
  1506. sel.value = selectedVal;
  1507. } else {
  1508. sel.value = defaultVal;
  1509. }
  1510. if (!sel.value && sel.options.length > 0) {
  1511. sel.selectedIndex = 0;
  1512. }
  1513. }
  1514. // ======================== PPPoE Multi-Instance ========================
  1515. async function loadPPPoE(populateInputs = true) {
  1516. try {
  1517. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1518. await fetchPPPProfilesList();
  1519. }
  1520. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1521. const list = await res.json();
  1522. state.pppoeList = Array.isArray(list) ? list : [];
  1523. const badge = document.getElementById('pppoe-count-badge');
  1524. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1525. const tbody = document.getElementById('pppoe-table-body');
  1526. const empty = document.getElementById('pppoe-empty');
  1527. if (!tbody) return;
  1528. tbody.innerHTML = '';
  1529. if (state.pppoeList.length === 0) {
  1530. if (empty) empty.classList.remove('hidden');
  1531. } else {
  1532. if (empty) empty.classList.add('hidden');
  1533. state.pppoeList.forEach(inst => {
  1534. const tr = document.createElement('tr');
  1535. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1536. tr.innerHTML = `
  1537. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1538. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1539. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1540. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1541. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1542. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1543. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1544. <td class="py-2.5 px-3 text-center">
  1545. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1546. ${inst.default_route ? 'Yes' : 'No'}
  1547. </span>
  1548. </td>
  1549. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1550. ${inst.running ? `
  1551. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1552. ` : `
  1553. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1554. `}
  1555. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1556. ${inst.disabled ? 'Enable' : 'Disable'}
  1557. </button>
  1558. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1559. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1560. </td>
  1561. `;
  1562. tbody.appendChild(tr);
  1563. });
  1564. }
  1565. } catch (err) {
  1566. console.error('Failed to load PPPoE:', err);
  1567. }
  1568. }
  1569. function openAddPPPoEModal() {
  1570. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1571. document.getElementById('pppoe-modal-edit-orig').value = '';
  1572. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1573. document.getElementById('pppoe-modal-name').readOnly = false;
  1574. document.getElementById('pppoe-modal-user').value = '';
  1575. document.getElementById('pppoe-modal-pass').value = '';
  1576. document.getElementById('pppoe-modal-service').value = '';
  1577. document.getElementById('pppoe-modal-mtu').value = '1492';
  1578. document.getElementById('pppoe-modal-defroute').checked = true;
  1579. document.getElementById('pppoe-modal-reconnect').checked = true;
  1580. document.getElementById('pppoe-modal-disabled').checked = false;
  1581. // Populate profiles
  1582. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1583. // Populate interfaces
  1584. const sel = document.getElementById('pppoe-modal-iface');
  1585. sel.innerHTML = '';
  1586. (state.interfaces || []).forEach(i => {
  1587. if (i.name === 'lo') return;
  1588. const opt = document.createElement('option');
  1589. opt.value = i.name;
  1590. opt.innerText = `${i.name} (${i.role || i.type})`;
  1591. sel.appendChild(opt);
  1592. });
  1593. document.getElementById('pppoe-modal').classList.remove('hidden');
  1594. }
  1595. function openEditPPPoEModal(name) {
  1596. const inst = (state.pppoeList || []).find(i => i.name === name);
  1597. if (!inst) return;
  1598. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1599. document.getElementById('pppoe-modal-edit-orig').value = name;
  1600. document.getElementById('pppoe-modal-name').value = inst.name;
  1601. document.getElementById('pppoe-modal-name').readOnly = true;
  1602. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1603. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1604. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1605. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1606. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1607. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1608. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1609. // Populate profiles
  1610. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1611. const sel = document.getElementById('pppoe-modal-iface');
  1612. sel.innerHTML = '';
  1613. (state.interfaces || []).forEach(i => {
  1614. if (i.name === 'lo') return;
  1615. const opt = document.createElement('option');
  1616. opt.value = i.name;
  1617. opt.innerText = `${i.name} (${i.role || i.type})`;
  1618. if (i.name === inst.interface) opt.selected = true;
  1619. sel.appendChild(opt);
  1620. });
  1621. document.getElementById('pppoe-modal').classList.remove('hidden');
  1622. }
  1623. function closePPPoEModal() {
  1624. document.getElementById('pppoe-modal').classList.add('hidden');
  1625. }
  1626. async function submitSavePPPoE(e) {
  1627. e.preventDefault();
  1628. const name = document.getElementById('pppoe-modal-name').value.trim();
  1629. const iface = document.getElementById('pppoe-modal-iface').value;
  1630. const user = document.getElementById('pppoe-modal-user').value.trim();
  1631. const pass = document.getElementById('pppoe-modal-pass').value;
  1632. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1633. const service = document.getElementById('pppoe-modal-service').value.trim();
  1634. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1635. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1636. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1637. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1638. try {
  1639. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1640. method: 'POST',
  1641. headers: { 'Content-Type': 'application/json' },
  1642. body: JSON.stringify({
  1643. name,
  1644. interface: iface,
  1645. username: user,
  1646. password: pass,
  1647. profile: profile,
  1648. service_name: service,
  1649. mtu,
  1650. default_route: defRoute,
  1651. auto_reconnect: reconnect,
  1652. disabled
  1653. })
  1654. });
  1655. if (res.ok) {
  1656. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1657. closePPPoEModal();
  1658. loadPPPoE(false);
  1659. fetchData(false);
  1660. } else {
  1661. const err = await res.json();
  1662. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1663. }
  1664. } catch (err) {
  1665. showToast('Error', err.message, 'error');
  1666. }
  1667. }
  1668. async function connectPPPoEInstance(name) {
  1669. try {
  1670. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1671. if (res.ok) {
  1672. showToast('Connecting', `Dialing ${name}...`, 'info');
  1673. setTimeout(() => loadPPPoE(false), 2000);
  1674. }
  1675. } catch (err) {
  1676. showToast('Error', err.message, 'error');
  1677. }
  1678. }
  1679. async function disconnectPPPoEInstance(name) {
  1680. try {
  1681. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1682. if (res.ok) {
  1683. showToast('Disconnected', `${name} session terminated`, 'info');
  1684. setTimeout(() => loadPPPoE(false), 1000);
  1685. }
  1686. } catch (err) {
  1687. showToast('Error', err.message, 'error');
  1688. }
  1689. }
  1690. async function togglePPPoEState(name, enable) {
  1691. try {
  1692. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1693. method: 'POST',
  1694. headers: { 'Content-Type': 'application/json' },
  1695. body: JSON.stringify({ enabled: enable })
  1696. });
  1697. if (res.ok) {
  1698. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1699. loadPPPoE(false);
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function deletePPPoEInstance(name) {
  1706. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1707. try {
  1708. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1709. if (res.ok) {
  1710. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1711. loadPPPoE(false);
  1712. fetchData(false);
  1713. }
  1714. } catch (err) {
  1715. showToast('Error', err.message, 'error');
  1716. }
  1717. }
  1718. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1719. state.wgSubTab = 'ifaces';
  1720. function switchWGSubTab(tab) {
  1721. state.wgSubTab = tab;
  1722. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1723. const peersPanel = document.getElementById('wg-subtab-peers');
  1724. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1725. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1726. if (tab === 'ifaces') {
  1727. ifacesPanel?.classList.remove('hidden');
  1728. peersPanel?.classList.add('hidden');
  1729. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1730. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1731. } else {
  1732. ifacesPanel?.classList.add('hidden');
  1733. peersPanel?.classList.remove('hidden');
  1734. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1735. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1736. renderWGPeers();
  1737. }
  1738. }
  1739. async function loadWireGuard(populateInputs = true) {
  1740. try {
  1741. const [ifacesRes, peersRes] = await Promise.all([
  1742. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1743. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1744. ]);
  1745. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1746. const peers = peersRes.ok ? await peersRes.json() : [];
  1747. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1748. state.wgPeers = Array.isArray(peers) ? peers : [];
  1749. // Badges
  1750. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1751. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1752. const peersCountBadge = document.getElementById('wg-peers-count');
  1753. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1754. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1755. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1756. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1757. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1758. // Render Interfaces
  1759. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1760. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1761. if (ifacesTbody) {
  1762. ifacesTbody.innerHTML = '';
  1763. if (state.wgInterfaces.length === 0) {
  1764. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1765. } else {
  1766. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1767. state.wgInterfaces.forEach(iface => {
  1768. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1769. const tr = document.createElement('tr');
  1770. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1771. tr.innerHTML = `
  1772. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1773. <td class="py-2.5 px-3">
  1774. <div class="flex items-center gap-1.5">
  1775. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1776. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1777. </div>
  1778. </td>
  1779. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1780. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1781. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1782. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1783. ${(iface.public_key || '').substring(0, 10)}... 📋
  1784. </span>
  1785. </td>
  1786. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1787. <td class="py-2.5 px-3 text-center">
  1788. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1789. </td>
  1790. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1791. ${iface.running ? `
  1792. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1793. ` : `
  1794. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1795. `}
  1796. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1797. ${iface.disabled ? 'Enable' : 'Disable'}
  1798. </button>
  1799. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1800. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1801. </td>
  1802. `;
  1803. ifacesTbody.appendChild(tr);
  1804. });
  1805. }
  1806. }
  1807. // Populate filter dropdown in peers tab
  1808. const filterSel = document.getElementById('wg-peers-filter-iface');
  1809. if (filterSel) {
  1810. const currentVal = filterSel.value;
  1811. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1812. state.wgInterfaces.forEach(i => {
  1813. const opt = document.createElement('option');
  1814. opt.value = i.name;
  1815. opt.innerText = i.name;
  1816. if (i.name === currentVal) opt.selected = true;
  1817. filterSel.appendChild(opt);
  1818. });
  1819. }
  1820. renderWGPeers();
  1821. } catch (err) {
  1822. console.error('Failed to load WireGuard:', err);
  1823. }
  1824. }
  1825. function formatWGPeerEndpoint(address, port) {
  1826. if (!address || address === '(none)') return '--';
  1827. let addr = address.trim();
  1828. let p = port || 0;
  1829. while (addr.includes(':') && !addr.startsWith('[')) {
  1830. const lastColon = addr.lastIndexOf(':');
  1831. const maybePort = addr.substring(lastColon + 1);
  1832. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1833. if (!p) p = parseInt(maybePort, 10);
  1834. addr = addr.substring(0, lastColon);
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. return p ? `${addr}:${p}` : addr;
  1840. }
  1841. function renderWGPeers() {
  1842. const filterSel = document.getElementById('wg-peers-filter-iface');
  1843. const selectedIface = filterSel ? filterSel.value : '';
  1844. const tbody = document.getElementById('wg-peers-table-body');
  1845. const empty = document.getElementById('wg-peers-empty');
  1846. if (!tbody) return;
  1847. tbody.innerHTML = '';
  1848. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1849. if (filtered.length === 0) {
  1850. if (empty) empty.classList.remove('hidden');
  1851. } else {
  1852. if (empty) empty.classList.add('hidden');
  1853. filtered.forEach(p => {
  1854. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1855. const tr = document.createElement('tr');
  1856. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1857. tr.innerHTML = `
  1858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1859. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1860. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1861. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1862. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1863. ${(p.public_key || '').substring(0, 10)}... 📋
  1864. </span>
  1865. </td>
  1866. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1867. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1868. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1869. <td class="py-2.5 px-3 font-mono text-[11px]">
  1870. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1871. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1872. </td>
  1873. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1874. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1875. ${p.disabled ? 'Enable' : 'Disable'}
  1876. </button>
  1877. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1878. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1879. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1880. </td>
  1881. `;
  1882. tbody.appendChild(tr);
  1883. });
  1884. }
  1885. }
  1886. function openAddWGInterfaceModal() {
  1887. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1888. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1889. const nameEl = document.getElementById('wg-iface-modal-name');
  1890. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1891. nameEl.readOnly = false;
  1892. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1893. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1894. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1895. document.getElementById('wg-iface-modal-comment').value = '';
  1896. document.getElementById('wg-iface-modal-pubkey').value = '';
  1897. document.getElementById('wg-iface-modal-privkey').value = '';
  1898. document.getElementById('wg-iface-modal-disabled').checked = false;
  1899. generateWGInterfaceKeys();
  1900. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1901. }
  1902. function openEditWGInterfaceModal(name) {
  1903. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1904. if (!iface) return;
  1905. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1906. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1907. const nameEl = document.getElementById('wg-iface-modal-name');
  1908. nameEl.value = iface.name;
  1909. nameEl.readOnly = false; // ALLOW RENAMING
  1910. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1911. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1912. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1913. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1914. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1915. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1916. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1917. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1918. }
  1919. function closeAddWGInterfaceModal() {
  1920. document.getElementById('wg-iface-modal').classList.add('hidden');
  1921. }
  1922. async function generateWGInterfaceKeys() {
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1925. const keys = await res.json();
  1926. if (res.ok) {
  1927. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1928. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1929. }
  1930. } catch (err) {
  1931. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1932. }
  1933. }
  1934. async function onWGInterfacePrivKeyInput() {
  1935. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1936. if (!privKey) return;
  1937. try {
  1938. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1939. method: 'POST',
  1940. headers: { 'Content-Type': 'application/json' },
  1941. body: JSON.stringify({ private_key: privKey })
  1942. });
  1943. if (res.ok) {
  1944. const data = await res.json();
  1945. if (data.public_key) {
  1946. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1947. }
  1948. }
  1949. } catch (err) {
  1950. // Ignore while typing
  1951. }
  1952. }
  1953. function toggleWGPrivKeyVisibility() {
  1954. const el = document.getElementById('wg-iface-modal-privkey');
  1955. const btn = document.getElementById('btn-toggle-wg-privkey');
  1956. if (el.type === 'password') {
  1957. el.type = 'text';
  1958. btn.innerText = '🙈 Hide';
  1959. } else {
  1960. el.type = 'password';
  1961. btn.innerText = '👁️ Show';
  1962. }
  1963. }
  1964. function copyWGInterfacePubKey() {
  1965. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1966. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1967. }
  1968. async function submitSaveWGInterface(e) {
  1969. e.preventDefault();
  1970. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1971. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1972. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1973. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1974. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1975. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1976. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1977. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1978. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1979. try {
  1980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1981. method: 'POST',
  1982. headers: { 'Content-Type': 'application/json' },
  1983. body: JSON.stringify({
  1984. orig_name: origName,
  1985. name,
  1986. listen_port: port,
  1987. address: addr,
  1988. mtu,
  1989. comment,
  1990. public_key: pub,
  1991. private_key: priv,
  1992. disabled
  1993. })
  1994. });
  1995. const data = await res.json();
  1996. if (res.ok) {
  1997. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1998. closeAddWGInterfaceModal();
  1999. loadWireGuard(false);
  2000. fetchData(false);
  2001. } else {
  2002. showToast('Error', data.error || 'Failed to save interface', 'error');
  2003. }
  2004. } catch (err) {
  2005. showToast('Error', err.message, 'error');
  2006. }
  2007. }
  2008. async function startWGInterface(name) {
  2009. try {
  2010. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2011. if (res.ok) {
  2012. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2013. loadWireGuard(false);
  2014. fetchData(false);
  2015. }
  2016. } catch (err) {
  2017. showToast('Error', err.message, 'error');
  2018. }
  2019. }
  2020. async function stopWGInterface(name) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2023. if (res.ok) {
  2024. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2025. loadWireGuard(false);
  2026. fetchData(false);
  2027. }
  2028. } catch (err) {
  2029. showToast('Error', err.message, 'error');
  2030. }
  2031. }
  2032. async function toggleWGInterfaceState(name, enable) {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2035. method: 'POST',
  2036. headers: { 'Content-Type': 'application/json' },
  2037. body: JSON.stringify({ enabled: enable })
  2038. });
  2039. if (res.ok) {
  2040. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2041. loadWireGuard(false);
  2042. fetchData(false);
  2043. }
  2044. } catch (err) {
  2045. showToast('Error', err.message, 'error');
  2046. }
  2047. }
  2048. async function deleteWGInterface(name) {
  2049. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2050. try {
  2051. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2052. if (res.ok) {
  2053. showToast('Deleted', `Interface ${name} removed`, 'success');
  2054. loadWireGuard(false);
  2055. fetchData(false);
  2056. }
  2057. } catch (err) {
  2058. showToast('Error', err.message, 'error');
  2059. }
  2060. }
  2061. function populateWGPeerIfaceSelect(selectedIface = '') {
  2062. const sel = document.getElementById('wg-peer-modal-iface');
  2063. if (!sel) return;
  2064. sel.innerHTML = '';
  2065. (state.wgInterfaces || []).forEach(i => {
  2066. const opt = document.createElement('option');
  2067. opt.value = i.name;
  2068. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2069. if (i.name === selectedIface) opt.selected = true;
  2070. sel.appendChild(opt);
  2071. });
  2072. }
  2073. function openAddWGPeerModal() {
  2074. if ((state.wgInterfaces || []).length === 0) {
  2075. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2076. openAddWGInterfaceModal();
  2077. return;
  2078. }
  2079. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2080. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2081. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2082. populateWGPeerIfaceSelect();
  2083. document.getElementById('wg-peer-modal-name').value = '';
  2084. document.getElementById('wg-peer-modal-pubkey').value = '';
  2085. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2086. document.getElementById('wg-peer-modal-endpoint').value = '';
  2087. document.getElementById('wg-peer-modal-port').value = '';
  2088. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2089. document.getElementById('wg-peer-modal-preshared').value = '';
  2090. document.getElementById('wg-peer-modal-disabled').checked = false;
  2091. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2092. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2093. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2094. }
  2095. function openEditWGPeerModal(ifaceName, pubKey) {
  2096. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2097. if (!peer) {
  2098. showToast('Not Found', 'Peer not found', 'warning');
  2099. return;
  2100. }
  2101. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2102. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2103. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2104. populateWGPeerIfaceSelect(peer.interface);
  2105. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2106. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2107. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2108. let epHost = (peer.endpoint_address || '').trim();
  2109. let epPort = peer.endpoint_port || '';
  2110. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2111. const lastColon = epHost.lastIndexOf(':');
  2112. const maybePort = epHost.substring(lastColon + 1);
  2113. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2114. if (!epPort) epPort = parseInt(maybePort, 10);
  2115. epHost = epHost.substring(0, lastColon);
  2116. } else {
  2117. break;
  2118. }
  2119. }
  2120. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2121. document.getElementById('wg-peer-modal-port').value = epPort;
  2122. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2123. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2124. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2125. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2126. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2127. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2128. }
  2129. function closeAddWGPeerModal() {
  2130. document.getElementById('wg-peer-modal').classList.add('hidden');
  2131. }
  2132. async function generatePeerKeypairHelper() {
  2133. try {
  2134. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2135. const keys = await res.json();
  2136. if (res.ok) {
  2137. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2138. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2139. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2140. checkWGPeerKeyValidity();
  2141. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2142. }
  2143. } catch (err) {
  2144. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2145. }
  2146. }
  2147. function copyGeneratedPeerPrivKey() {
  2148. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2149. if (priv) copyToClipboard(priv, 'Client Private Key');
  2150. }
  2151. async function generatePeerPSK() {
  2152. try {
  2153. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2154. const keys = await res.json();
  2155. if (res.ok && keys.private_key) {
  2156. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2157. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2158. }
  2159. } catch (err) {
  2160. showToast('Error', err.message, 'error');
  2161. }
  2162. }
  2163. function checkWGPeerKeyValidity() {
  2164. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2165. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2166. const warningEl = document.getElementById('wg-peer-key-warning');
  2167. if (!warningEl) return;
  2168. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2169. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2170. warningEl.classList.remove('hidden');
  2171. } else {
  2172. warningEl.classList.add('hidden');
  2173. }
  2174. }
  2175. async function submitSaveWGPeer(e) {
  2176. e.preventDefault();
  2177. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2178. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2179. const iface = document.getElementById('wg-peer-modal-iface').value;
  2180. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2181. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2182. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2183. .split(',')
  2184. .map(s => s.trim())
  2185. .filter(s => s.length > 0);
  2186. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2187. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2188. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2189. const lastColon = epHost.lastIndexOf(':');
  2190. const maybePort = epHost.substring(lastColon + 1);
  2191. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2192. if (!epPort) epPort = parseInt(maybePort, 10);
  2193. epHost = epHost.substring(0, lastColon);
  2194. } else {
  2195. break;
  2196. }
  2197. }
  2198. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2199. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2200. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2201. // Validation
  2202. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2203. if (targetIface && targetIface.public_key === pub) {
  2204. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2205. return;
  2206. }
  2207. try {
  2208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2209. method: 'POST',
  2210. headers: { 'Content-Type': 'application/json' },
  2211. body: JSON.stringify({
  2212. orig_interface: origIface,
  2213. orig_public_key: origPubKey,
  2214. interface: iface,
  2215. name,
  2216. public_key: pub,
  2217. allowed_ips: allowed,
  2218. endpoint_address: epHost,
  2219. endpoint_port: epPort,
  2220. persistent_keepalive: keepalive,
  2221. preshared_key: psk,
  2222. disabled
  2223. })
  2224. });
  2225. const data = await res.json();
  2226. if (res.ok) {
  2227. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2228. closeAddWGPeerModal();
  2229. loadWireGuard(false);
  2230. } else {
  2231. showToast('Error', data.error || 'Failed to save peer', 'error');
  2232. }
  2233. } catch (err) {
  2234. showToast('Error', err.message, 'error');
  2235. }
  2236. }
  2237. async function toggleWGPeerState(iface, pubkey, enable) {
  2238. try {
  2239. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2240. method: 'POST',
  2241. headers: { 'Content-Type': 'application/json' },
  2242. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2243. });
  2244. const data = await res.json();
  2245. if (res.ok) {
  2246. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2247. loadWireGuard(false);
  2248. } else {
  2249. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2250. }
  2251. } catch (err) {
  2252. showToast('Error', err.message, 'error');
  2253. }
  2254. }
  2255. async function deleteWGPeer(iface, pubkey) {
  2256. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2257. try {
  2258. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2259. method: 'POST',
  2260. headers: { 'Content-Type': 'application/json' },
  2261. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2262. });
  2263. const data = await res.json();
  2264. if (res.ok) {
  2265. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2266. loadWireGuard(false);
  2267. } else {
  2268. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2275. function switchIpsecModalTab(tab) {
  2276. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2277. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2278. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2279. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2280. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2281. if (tab === 'p1') {
  2282. if (p1Tab) {
  2283. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2284. }
  2285. if (p2Tab) {
  2286. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2287. }
  2288. if (p1Content) p1Content.classList.remove('hidden');
  2289. if (p2Content) p2Content.classList.add('hidden');
  2290. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2291. } else {
  2292. if (p1Tab) {
  2293. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2294. }
  2295. if (p2Tab) {
  2296. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2297. }
  2298. if (p1Content) p1Content.classList.add('hidden');
  2299. if (p2Content) p2Content.classList.remove('hidden');
  2300. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2301. }
  2302. }
  2303. function toggleIpsecPhaseStep() {
  2304. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2305. if (p1Content && !p1Content.classList.contains('hidden')) {
  2306. switchIpsecModalTab('p2');
  2307. } else {
  2308. switchIpsecModalTab('p1');
  2309. }
  2310. }
  2311. function toggleIpsecPskVisibility() {
  2312. const pskInput = document.getElementById('ipsec-modal-psk');
  2313. if (!pskInput) return;
  2314. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2315. }
  2316. function addIpsecLocalSubnet(val = '') {
  2317. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2318. if (!container) return;
  2319. const row = document.createElement('div');
  2320. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2321. row.innerHTML = `
  2322. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2323. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2324. `;
  2325. container.appendChild(row);
  2326. }
  2327. function addIpsecRemoteSubnet(val = '') {
  2328. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2329. if (!container) return;
  2330. const row = document.createElement('div');
  2331. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2332. row.innerHTML = `
  2333. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2334. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2335. `;
  2336. container.appendChild(row);
  2337. }
  2338. function updateIpsecEspProposalFromPFS(val) {
  2339. const prop = document.getElementById('ipsec-modal-espprop');
  2340. if (!prop) return;
  2341. if (val === 'none') {
  2342. prop.value = 'aes256-sha256,aes128-sha256,default';
  2343. } else {
  2344. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2345. }
  2346. }
  2347. function updateIpsecIkeProposalFromDH(dh) {
  2348. const el = document.getElementById('ipsec-modal-ikeprop');
  2349. if (el) {
  2350. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2351. }
  2352. }
  2353. function safeSetVal(id, val) {
  2354. const el = document.getElementById(id);
  2355. if (el) el.value = val;
  2356. }
  2357. function safeSetChecked(id, val) {
  2358. const el = document.getElementById(id);
  2359. if (el) el.checked = !!val;
  2360. }
  2361. function safeGetVal(id, def = '') {
  2362. const el = document.getElementById(id);
  2363. return el ? el.value : def;
  2364. }
  2365. async function loadIPSec(populateInputs = true) {
  2366. try {
  2367. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2368. const list = await res.json();
  2369. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2370. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2371. const badge = document.getElementById('ipsec-sas-badge');
  2372. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2373. const tbody = document.getElementById('ipsec-table-body');
  2374. const empty = document.getElementById('ipsec-empty');
  2375. if (!tbody) return;
  2376. tbody.innerHTML = '';
  2377. if (state.ipsecTunnels.length === 0) {
  2378. if (empty) empty.classList.remove('hidden');
  2379. } else {
  2380. if (empty) empty.classList.add('hidden');
  2381. state.ipsecTunnels.forEach(c => {
  2382. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2383. const tr = document.createElement('tr');
  2384. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2385. // Local subnets tags
  2386. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2387. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2388. // Remote subnets tags
  2389. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2390. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2391. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2392. const p2Name = c.phase2_name || `${c.name}_p2`;
  2393. tr.innerHTML = `
  2394. <td class="py-2.5 px-3 text-center">
  2395. ${isEstablished ? `
  2396. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2397. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2398. <span>UP</span>
  2399. </span>
  2400. ` : (c.disabled ? `
  2401. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2402. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2403. <span>DOWN</span>
  2404. </span>
  2405. ` : `
  2406. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2407. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2408. <span>IDLE</span>
  2409. </span>
  2410. `)}
  2411. </td>
  2412. <td class="py-2.5 px-4 font-bold text-white">
  2413. <div class="flex items-center gap-2">
  2414. <span class="text-amber-400">🛡</span>
  2415. <div>
  2416. <div>${escapeHtml(c.name)}</div>
  2417. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2418. </div>
  2419. </div>
  2420. </td>
  2421. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2422. <td class="py-2.5 px-4 font-sans">
  2423. <div class="flex items-center gap-1.5">
  2424. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2425. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2426. </div>
  2427. </td>
  2428. <td class="py-2.5 px-4">
  2429. <div class="space-y-1">
  2430. <div class="flex items-center flex-wrap gap-1">
  2431. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2432. ${localBadges}
  2433. </div>
  2434. <div class="flex items-center flex-wrap gap-1">
  2435. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2436. ${remoteBadges}
  2437. </div>
  2438. </div>
  2439. </td>
  2440. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2441. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2442. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2443. </div>
  2444. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2445. </td>
  2446. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2447. ${isEstablished ? `
  2448. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2449. ` : `
  2450. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2451. `}
  2452. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2453. ${c.disabled ? 'Enable' : 'Disable'}
  2454. </button>
  2455. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2456. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2457. </td>
  2458. `;
  2459. tbody.appendChild(tr);
  2460. });
  2461. }
  2462. } catch (err) {
  2463. console.error('Failed to load IPSec:', err);
  2464. }
  2465. }
  2466. function openAddIPSecModal() {
  2467. const modal = document.getElementById('ipsec-modal');
  2468. if (!modal) return;
  2469. const title = document.getElementById('ipsec-modal-title');
  2470. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2471. // Phase 1 Fields
  2472. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2473. const nameEl = document.getElementById('ipsec-modal-name');
  2474. if (nameEl) nameEl.readOnly = false;
  2475. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2476. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2477. safeSetVal('ipsec-modal-remotegw', '');
  2478. safeSetVal('ipsec-modal-localaddrs', '');
  2479. safeSetVal('ipsec-modal-comments', '');
  2480. safeSetVal('ipsec-modal-psk', '');
  2481. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2482. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2483. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2484. safeSetVal('ipsec-modal-localid', '');
  2485. safeSetVal('ipsec-modal-remoteid', '');
  2486. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2487. // Phase 2 Fields
  2488. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2489. safeSetVal('ipsec-modal-espkeylife', '28800');
  2490. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2491. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2492. safeSetChecked('ipsec-modal-autostart', true);
  2493. safeSetChecked('ipsec-modal-disabled', false);
  2494. // Clear & Populate default dynamic subnets
  2495. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2496. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2497. if (localContainer) {
  2498. localContainer.innerHTML = '';
  2499. addIpsecLocalSubnet('192.168.10.0/24');
  2500. }
  2501. if (remoteContainer) {
  2502. remoteContainer.innerHTML = '';
  2503. addIpsecRemoteSubnet('192.168.20.0/24');
  2504. }
  2505. switchIpsecModalTab('p1');
  2506. modal.classList.remove('hidden');
  2507. }
  2508. function openEditIPSecModal(name) {
  2509. const modal = document.getElementById('ipsec-modal');
  2510. if (!modal) return;
  2511. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2512. if (!conn) return;
  2513. const title = document.getElementById('ipsec-modal-title');
  2514. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2515. // Phase 1 Fields
  2516. safeSetVal('ipsec-modal-name', conn.name);
  2517. const nameEl = document.getElementById('ipsec-modal-name');
  2518. if (nameEl) nameEl.readOnly = true;
  2519. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2520. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2521. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2522. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2523. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2524. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2525. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2526. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2527. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2528. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2529. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2530. // Phase 2 Fields
  2531. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2532. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2533. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2534. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2535. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2536. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2537. // Populate dynamic subnets
  2538. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2539. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2540. if (localContainer) {
  2541. localContainer.innerHTML = '';
  2542. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2543. locals.forEach(s => addIpsecLocalSubnet(s));
  2544. }
  2545. if (remoteContainer) {
  2546. remoteContainer.innerHTML = '';
  2547. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2548. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2549. }
  2550. switchIpsecModalTab('p1');
  2551. modal.classList.remove('hidden');
  2552. }
  2553. function closeAddIPSecModal() {
  2554. const modal = document.getElementById('ipsec-modal');
  2555. if (modal) modal.classList.add('hidden');
  2556. }
  2557. async function submitSaveIPSec(e) {
  2558. if (e) e.preventDefault();
  2559. const name = safeGetVal('ipsec-modal-name').trim();
  2560. if (!name) {
  2561. showToast('Error', 'Tunnel name is required', 'error');
  2562. return;
  2563. }
  2564. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2565. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2566. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2567. const comments = safeGetVal('ipsec-modal-comments').trim();
  2568. const psk = safeGetVal('ipsec-modal-psk');
  2569. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2570. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2571. const localId = safeGetVal('ipsec-modal-localid').trim();
  2572. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2573. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2574. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2575. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2576. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2577. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2578. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2579. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2580. // Scrape dynamic local and remote subnets
  2581. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2582. const localSubnets = [];
  2583. localInputs.forEach(inp => {
  2584. const v = inp.value.trim();
  2585. if (v) localSubnets.push(v);
  2586. });
  2587. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2588. const remoteSubnets = [];
  2589. remoteInputs.forEach(inp => {
  2590. const v = inp.value.trim();
  2591. if (v) remoteSubnets.push(v);
  2592. });
  2593. try {
  2594. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2595. method: 'POST',
  2596. headers: { 'Content-Type': 'application/json' },
  2597. body: JSON.stringify({
  2598. name,
  2599. comment: comments,
  2600. ike_version: ikeVersion,
  2601. local_addrs: localAddrs,
  2602. remote_addrs: remotegw,
  2603. preshared_key: psk,
  2604. ike_proposals: ikeProposals,
  2605. ike_keylife: ikeKeylife,
  2606. local_id: localId,
  2607. remote_id: remoteId,
  2608. dpd: dpd,
  2609. phase2_name: phase2Name,
  2610. esp_proposals: espProposals,
  2611. esp_keylife: espKeylife,
  2612. pfs_group: pfsGroup,
  2613. pfs: pfsGroup !== 'none',
  2614. local_subnets: localSubnets,
  2615. remote_subnets: remoteSubnets,
  2616. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2617. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2618. auto_start: autostart,
  2619. disabled
  2620. })
  2621. });
  2622. if (res.ok) {
  2623. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2624. closeAddIPSecModal();
  2625. loadIPSec(false);
  2626. } else {
  2627. const err = await res.json();
  2628. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2629. }
  2630. } catch (err) {
  2631. showToast('Error', err.message, 'error');
  2632. }
  2633. }
  2634. async function startIPSecTunnel(name) {
  2635. try {
  2636. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2637. if (res.ok) {
  2638. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2639. setTimeout(() => loadIPSec(false), 2000);
  2640. }
  2641. } catch (err) {
  2642. showToast('Error', err.message, 'error');
  2643. }
  2644. }
  2645. async function stopIPSecTunnel(name) {
  2646. try {
  2647. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2648. if (res.ok) {
  2649. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2650. loadIPSec(false);
  2651. }
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. async function toggleIPSecState(name, enable) {
  2657. try {
  2658. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2659. method: 'POST',
  2660. headers: { 'Content-Type': 'application/json' },
  2661. body: JSON.stringify({ enabled: enable })
  2662. });
  2663. if (res.ok) {
  2664. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2665. loadIPSec(false);
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function deleteIPSecConn(name) {
  2672. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2673. try {
  2674. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2675. if (res.ok) {
  2676. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2677. loadIPSec(false);
  2678. fetchData(false);
  2679. }
  2680. } catch (err) {
  2681. showToast('Error', err.message, 'error');
  2682. }
  2683. }
  2684. // ======================== L2TP Multi-Instance ========================
  2685. async function loadL2TP(populateInputs = true) {
  2686. try {
  2687. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2688. await fetchPPPProfilesList();
  2689. }
  2690. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2691. const list = await res.json();
  2692. state.l2tpList = Array.isArray(list) ? list : [];
  2693. const badge = document.getElementById('l2tp-count-badge');
  2694. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2695. const tbody = document.getElementById('l2tp-table-body');
  2696. const empty = document.getElementById('l2tp-empty');
  2697. if (!tbody) return;
  2698. tbody.innerHTML = '';
  2699. if (state.l2tpList.length === 0) {
  2700. if (empty) empty.classList.remove('hidden');
  2701. } else {
  2702. if (empty) empty.classList.add('hidden');
  2703. state.l2tpList.forEach(inst => {
  2704. const tr = document.createElement('tr');
  2705. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2706. tr.innerHTML = `
  2707. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2708. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2709. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2710. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2711. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2712. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2713. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2714. <td class="py-2.5 px-3 text-center">
  2715. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2716. ${inst.default_route ? 'Yes' : 'No'}
  2717. </span>
  2718. </td>
  2719. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2720. ${inst.running ? `
  2721. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2722. ` : `
  2723. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2724. `}
  2725. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2726. ${inst.disabled ? 'Enable' : 'Disable'}
  2727. </button>
  2728. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2729. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2730. </td>
  2731. `;
  2732. tbody.appendChild(tr);
  2733. });
  2734. }
  2735. } catch (err) {
  2736. console.error('Failed to load L2TP:', err);
  2737. }
  2738. }
  2739. async function openAddL2TPModal() {
  2740. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2741. await fetchPPPProfilesList();
  2742. }
  2743. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2744. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2745. document.getElementById('l2tp-modal-name').readOnly = false;
  2746. document.getElementById('l2tp-modal-server').value = '';
  2747. document.getElementById('l2tp-modal-user').value = '';
  2748. document.getElementById('l2tp-modal-pass').value = '';
  2749. document.getElementById('l2tp-modal-ipsec').value = '';
  2750. document.getElementById('l2tp-modal-defroute').checked = true;
  2751. document.getElementById('l2tp-modal-disabled').checked = false;
  2752. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2753. document.getElementById('l2tp-modal').classList.remove('hidden');
  2754. }
  2755. async function openEditL2TPModal(name) {
  2756. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2757. await fetchPPPProfilesList();
  2758. }
  2759. const inst = (state.l2tpList || []).find(i => i.name === name);
  2760. if (!inst) return;
  2761. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2762. document.getElementById('l2tp-modal-name').value = inst.name;
  2763. document.getElementById('l2tp-modal-name').readOnly = true;
  2764. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2765. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2766. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2767. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2768. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2769. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2770. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2771. document.getElementById('l2tp-modal').classList.remove('hidden');
  2772. }
  2773. function closeL2TPModal() {
  2774. document.getElementById('l2tp-modal').classList.add('hidden');
  2775. }
  2776. async function submitSaveL2TP(e) {
  2777. e.preventDefault();
  2778. const name = document.getElementById('l2tp-modal-name').value.trim();
  2779. const server = document.getElementById('l2tp-modal-server').value.trim();
  2780. const user = document.getElementById('l2tp-modal-user').value.trim();
  2781. const pass = document.getElementById('l2tp-modal-pass').value;
  2782. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2783. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2784. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2785. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2786. try {
  2787. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2788. method: 'POST',
  2789. headers: { 'Content-Type': 'application/json' },
  2790. body: JSON.stringify({
  2791. name,
  2792. connect_to: server,
  2793. username: user,
  2794. password: pass,
  2795. profile: profile,
  2796. ipsec_secret: ipsec,
  2797. default_route: defRoute,
  2798. disabled
  2799. })
  2800. });
  2801. if (res.ok) {
  2802. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2803. closeL2TPModal();
  2804. loadL2TP(false);
  2805. fetchData(false);
  2806. }
  2807. } catch (err) {
  2808. showToast('Error', err.message, 'error');
  2809. }
  2810. }
  2811. async function connectL2TPInstance(name) {
  2812. try {
  2813. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2814. if (res.ok) {
  2815. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2816. setTimeout(() => loadL2TP(false), 2000);
  2817. }
  2818. } catch (err) {
  2819. showToast('Error', err.message, 'error');
  2820. }
  2821. }
  2822. async function disconnectL2TPInstance(name) {
  2823. try {
  2824. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2825. if (res.ok) {
  2826. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2827. loadL2TP(false);
  2828. }
  2829. } catch (err) {
  2830. showToast('Error', err.message, 'error');
  2831. }
  2832. }
  2833. async function toggleL2TPState(name, enable) {
  2834. try {
  2835. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2836. method: 'POST',
  2837. headers: { 'Content-Type': 'application/json' },
  2838. body: JSON.stringify({ enabled: enable })
  2839. });
  2840. if (res.ok) {
  2841. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2842. loadL2TP(false);
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function deleteL2TPInstance(name) {
  2849. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2850. try {
  2851. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2852. if (res.ok) {
  2853. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2854. loadL2TP(false);
  2855. fetchData(false);
  2856. }
  2857. } catch (err) {
  2858. showToast('Error', err.message, 'error');
  2859. }
  2860. }
  2861. // ======================== PPTP Multi-Instance ========================
  2862. async function loadPPTP(populateInputs = true) {
  2863. try {
  2864. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2865. await fetchPPPProfilesList();
  2866. }
  2867. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2868. const list = await res.json();
  2869. state.pptpList = Array.isArray(list) ? list : [];
  2870. const badge = document.getElementById('pptp-count-badge');
  2871. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2872. const tbody = document.getElementById('pptp-table-body');
  2873. const empty = document.getElementById('pptp-empty');
  2874. if (!tbody) return;
  2875. tbody.innerHTML = '';
  2876. if (state.pptpList.length === 0) {
  2877. if (empty) empty.classList.remove('hidden');
  2878. } else {
  2879. if (empty) empty.classList.add('hidden');
  2880. state.pptpList.forEach(inst => {
  2881. const tr = document.createElement('tr');
  2882. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2883. tr.innerHTML = `
  2884. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2885. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2886. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2887. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2888. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2889. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2890. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2891. <td class="py-2.5 px-3 text-center">
  2892. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2893. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2894. </span>
  2895. </td>
  2896. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2897. ${inst.running ? `
  2898. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2899. ` : `
  2900. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2901. `}
  2902. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2903. ${inst.disabled ? 'Enable' : 'Disable'}
  2904. </button>
  2905. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2906. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2907. </td>
  2908. `;
  2909. tbody.appendChild(tr);
  2910. });
  2911. }
  2912. } catch (err) {
  2913. console.error('Failed to load PPTP:', err);
  2914. }
  2915. }
  2916. async function openAddPPTPModal() {
  2917. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2918. await fetchPPPProfilesList();
  2919. }
  2920. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2921. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2922. document.getElementById('pptp-modal-name').readOnly = false;
  2923. document.getElementById('pptp-modal-server').value = '';
  2924. document.getElementById('pptp-modal-user').value = '';
  2925. document.getElementById('pptp-modal-pass').value = '';
  2926. document.getElementById('pptp-modal-mppe').checked = true;
  2927. document.getElementById('pptp-modal-defroute').checked = true;
  2928. document.getElementById('pptp-modal-disabled').checked = false;
  2929. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2930. document.getElementById('pptp-modal').classList.remove('hidden');
  2931. }
  2932. async function openEditPPTPModal(name) {
  2933. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2934. await fetchPPPProfilesList();
  2935. }
  2936. const inst = (state.pptpList || []).find(i => i.name === name);
  2937. if (!inst) return;
  2938. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2939. document.getElementById('pptp-modal-name').value = inst.name;
  2940. document.getElementById('pptp-modal-name').readOnly = true;
  2941. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2942. document.getElementById('pptp-modal-user').value = inst.username || '';
  2943. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2944. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2945. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2946. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2947. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2948. document.getElementById('pptp-modal').classList.remove('hidden');
  2949. }
  2950. function closePPTPModal() {
  2951. document.getElementById('pptp-modal').classList.add('hidden');
  2952. }
  2953. async function submitSavePPTP(e) {
  2954. e.preventDefault();
  2955. const name = document.getElementById('pptp-modal-name').value.trim();
  2956. const server = document.getElementById('pptp-modal-server').value.trim();
  2957. const user = document.getElementById('pptp-modal-user').value.trim();
  2958. const pass = document.getElementById('pptp-modal-pass').value;
  2959. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2960. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2961. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2962. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2963. try {
  2964. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2965. method: 'POST',
  2966. headers: { 'Content-Type': 'application/json' },
  2967. body: JSON.stringify({
  2968. name,
  2969. connect_to: server,
  2970. username: user,
  2971. password: pass,
  2972. profile: profile,
  2973. require_mppe: mppe,
  2974. default_route: defRoute,
  2975. auto_reconnect: true,
  2976. disabled
  2977. })
  2978. });
  2979. if (res.ok) {
  2980. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2981. closePPTPModal();
  2982. loadPPTP(false);
  2983. fetchData(false);
  2984. }
  2985. } catch (err) {
  2986. showToast('Error', err.message, 'error');
  2987. }
  2988. }
  2989. async function connectPPTPInstance(name) {
  2990. try {
  2991. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2992. if (res.ok) {
  2993. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2994. setTimeout(() => loadPPTP(false), 2000);
  2995. }
  2996. } catch (err) {
  2997. showToast('Error', err.message, 'error');
  2998. }
  2999. }
  3000. async function disconnectPPTPInstance(name) {
  3001. try {
  3002. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3003. if (res.ok) {
  3004. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3005. loadPPTP(false);
  3006. }
  3007. } catch (err) {
  3008. showToast('Error', err.message, 'error');
  3009. }
  3010. }
  3011. async function togglePPTPState(name, enable) {
  3012. try {
  3013. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3014. method: 'POST',
  3015. headers: { 'Content-Type': 'application/json' },
  3016. body: JSON.stringify({ enabled: enable })
  3017. });
  3018. if (res.ok) {
  3019. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3020. loadPPTP(false);
  3021. }
  3022. } catch (err) {
  3023. showToast('Error', err.message, 'error');
  3024. }
  3025. }
  3026. async function deletePPTPInstance(name) {
  3027. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3028. try {
  3029. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3030. if (res.ok) {
  3031. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3032. loadPPTP(false);
  3033. fetchData(false);
  3034. }
  3035. } catch (err) {
  3036. showToast('Error', err.message, 'error');
  3037. }
  3038. }
  3039. // ---------------- Modal & Helper Functions ----------------
  3040. function openVlanModal(defaultParent = '') {
  3041. const select = document.getElementById('vlan-parent');
  3042. select.innerHTML = '';
  3043. const allIfaces = state.interfaces || [];
  3044. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3045. if (eligible.length === 0) {
  3046. const opt = document.createElement('option');
  3047. opt.value = '';
  3048. opt.innerText = 'No VLAN-capable interfaces available';
  3049. select.appendChild(opt);
  3050. } else {
  3051. eligible.forEach(i => {
  3052. const opt = document.createElement('option');
  3053. opt.value = i.name;
  3054. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3055. if (i.name === defaultParent) opt.selected = true;
  3056. select.appendChild(opt);
  3057. });
  3058. }
  3059. document.getElementById('vlan-id').value = '';
  3060. document.getElementById('vlan-name').value = '';
  3061. document.getElementById('vlan-ip').value = '';
  3062. document.getElementById('vlan-desc').value = '';
  3063. populateRoleSelects('LAN');
  3064. autoSuggestVlanName();
  3065. document.getElementById('vlan-modal').classList.remove('hidden');
  3066. }
  3067. function closeVlanModal() {
  3068. document.getElementById('vlan-modal').classList.add('hidden');
  3069. }
  3070. function autoSuggestVlanName() {
  3071. const parent = document.getElementById('vlan-parent').value;
  3072. if (!parent) return;
  3073. const id = document.getElementById('vlan-id').value;
  3074. const nameInput = document.getElementById('vlan-name');
  3075. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3076. }
  3077. function setSubnetPreset(cidr) {
  3078. const ipInput = document.getElementById('vlan-ip');
  3079. const id = document.getElementById('vlan-id').value || '10';
  3080. ipInput.value = `192.168.${id}.1${cidr}`;
  3081. }
  3082. async function submitCreateVlan(e) {
  3083. e.preventDefault();
  3084. const btn = document.getElementById('vlan-submit-btn');
  3085. btn.disabled = true;
  3086. btn.innerText = 'Creating...';
  3087. const parent = document.getElementById('vlan-parent').value;
  3088. if (!parent) {
  3089. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3090. btn.disabled = false;
  3091. btn.innerText = 'Create VLAN';
  3092. return;
  3093. }
  3094. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3095. const name = document.getElementById('vlan-name').value.trim();
  3096. const ip = document.getElementById('vlan-ip').value.trim();
  3097. const role = document.getElementById('vlan-role').value;
  3098. const desc = document.getElementById('vlan-desc').value.trim();
  3099. try {
  3100. const res = await fetch(`${API_BASE}/vlans`, {
  3101. method: 'POST',
  3102. headers: { 'Content-Type': 'application/json' },
  3103. body: JSON.stringify({
  3104. parent_name: parent,
  3105. vlan_id: id,
  3106. name: name,
  3107. ip_address: ip,
  3108. role: role,
  3109. description: desc,
  3110. mtu: 1500,
  3111. auto_up: true
  3112. })
  3113. });
  3114. const data = await res.json();
  3115. if (res.ok) {
  3116. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3117. state.expandedParents.add(parent);
  3118. closeVlanModal();
  3119. await fetchData(true);
  3120. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3121. } else {
  3122. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3123. }
  3124. } catch (err) {
  3125. showToast('Error', err.message, 'error');
  3126. } finally {
  3127. btn.disabled = false;
  3128. btn.innerText = 'Create VLAN';
  3129. }
  3130. }
  3131. async function confirmDeleteVlan(name) {
  3132. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3133. try {
  3134. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3135. if (res.ok) {
  3136. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3137. closeIfaceModal();
  3138. fetchData(true);
  3139. }
  3140. } catch (err) {
  3141. showToast('Error', err.message, 'error');
  3142. }
  3143. }
  3144. function openIfaceModal(name) {
  3145. const iface = (state.interfaces || []).find(i => i.name === name);
  3146. if (!iface) return;
  3147. state.currentModalIface = iface.name;
  3148. document.getElementById('modal-iface-name').innerText = iface.name;
  3149. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3150. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3151. populateRoleSelects(iface.role || 'LAN');
  3152. document.getElementById('modal-iface-desc').value = iface.description || '';
  3153. const nameInput = document.getElementById('modal-iface-new-name');
  3154. const renameBtn = document.getElementById('modal-btn-rename');
  3155. const renameHelp = document.getElementById('modal-iface-rename-help');
  3156. if (nameInput) {
  3157. nameInput.value = iface.name;
  3158. if (iface.name === 'lo' || iface.type === 'loopback') {
  3159. nameInput.disabled = true;
  3160. if (renameBtn) renameBtn.disabled = true;
  3161. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3162. } else {
  3163. nameInput.disabled = false;
  3164. if (renameBtn) renameBtn.disabled = false;
  3165. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3166. }
  3167. }
  3168. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3169. if (iface.is_vlan) {
  3170. delBtn.classList.remove('hidden');
  3171. } else {
  3172. delBtn.classList.add('hidden');
  3173. }
  3174. renderModalIPs(iface);
  3175. document.getElementById('iface-modal').classList.remove('hidden');
  3176. }
  3177. function renderModalIPs(iface) {
  3178. const container = document.getElementById('modal-ip-list');
  3179. container.innerHTML = '';
  3180. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3181. if (addrs.length === 0) {
  3182. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3183. return;
  3184. }
  3185. addrs.forEach(addr => {
  3186. const row = document.createElement('div');
  3187. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3188. row.innerHTML = `
  3189. <span class="text-white">${addr}</span>
  3190. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3191. `;
  3192. container.appendChild(row);
  3193. });
  3194. }
  3195. function closeIfaceModal() {
  3196. document.getElementById('iface-modal').classList.add('hidden');
  3197. state.currentModalIface = null;
  3198. }
  3199. async function setIfaceState(name, newState) {
  3200. const target = name || state.currentModalIface;
  3201. if (!target) return;
  3202. await toggleInterfaceState(target, newState);
  3203. const updated = (state.interfaces || []).find(i => i.name === target);
  3204. if (updated) openIfaceModal(target);
  3205. }
  3206. async function applyMTU() {
  3207. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3208. try {
  3209. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3210. method: 'POST',
  3211. headers: { 'Content-Type': 'application/json' },
  3212. body: JSON.stringify({ mtu })
  3213. });
  3214. if (res.ok) {
  3215. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3216. fetchData(false);
  3217. }
  3218. } catch (err) {
  3219. showToast('Error', err.message, 'error');
  3220. }
  3221. }
  3222. async function addInterfaceIP() {
  3223. const ip = document.getElementById('modal-new-ip').value.trim();
  3224. if (!ip) return;
  3225. try {
  3226. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3227. method: 'POST',
  3228. headers: { 'Content-Type': 'application/json' },
  3229. body: JSON.stringify({ ip })
  3230. });
  3231. if (res.ok) {
  3232. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3233. document.getElementById('modal-new-ip').value = '';
  3234. await fetchData(false);
  3235. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3236. if (iface) renderModalIPs(iface);
  3237. } else {
  3238. const err = await res.json();
  3239. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3240. }
  3241. } catch (err) {
  3242. showToast('Error', err.message, 'error');
  3243. }
  3244. }
  3245. async function removeInterfaceIP(ip) {
  3246. if (!confirm(`Remove IP ${ip}?`)) return;
  3247. try {
  3248. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3249. method: 'DELETE',
  3250. headers: { 'Content-Type': 'application/json' },
  3251. body: JSON.stringify({ ip })
  3252. });
  3253. if (res.ok) {
  3254. showToast('IP Removed', `Removed ${ip}`, 'success');
  3255. await fetchData(false);
  3256. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3257. if (iface) renderModalIPs(iface);
  3258. }
  3259. } catch (err) {
  3260. showToast('Error', err.message, 'error');
  3261. }
  3262. }
  3263. async function renameInterface() {
  3264. const oldName = state.currentModalIface;
  3265. const newNameInput = document.getElementById('modal-iface-new-name');
  3266. const newName = (newNameInput?.value || '').trim();
  3267. if (!oldName) return;
  3268. if (!newName) {
  3269. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3270. return;
  3271. }
  3272. if (newName === oldName) {
  3273. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3274. return;
  3275. }
  3276. if (newName.length > 15) {
  3277. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3278. return;
  3279. }
  3280. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3281. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3282. return;
  3283. }
  3284. const renameBtn = document.getElementById('modal-btn-rename');
  3285. if (renameBtn) {
  3286. renameBtn.disabled = true;
  3287. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3288. }
  3289. try {
  3290. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3291. method: 'POST',
  3292. headers: { 'Content-Type': 'application/json' },
  3293. body: JSON.stringify({ new_name: newName })
  3294. });
  3295. const data = await res.json();
  3296. if (!res.ok) {
  3297. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3298. return;
  3299. }
  3300. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3301. state.currentModalIface = newName;
  3302. document.getElementById('modal-iface-name').innerText = newName;
  3303. // Refresh application state
  3304. await fetchData(false);
  3305. const updated = (state.interfaces || []).find(i => i.name === newName);
  3306. if (updated) {
  3307. openIfaceModal(newName);
  3308. } else {
  3309. closeIfaceModal();
  3310. }
  3311. } catch (err) {
  3312. showToast('Error', err.message, 'error');
  3313. } finally {
  3314. if (renameBtn) {
  3315. renameBtn.disabled = false;
  3316. renameBtn.innerHTML = `
  3317. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3318. <span>Rename</span>
  3319. `;
  3320. }
  3321. }
  3322. }
  3323. async function saveInterfaceMetadata() {
  3324. const oldName = state.currentModalIface;
  3325. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3326. const role = document.getElementById('modal-iface-role').value;
  3327. const desc = document.getElementById('modal-iface-desc').value.trim();
  3328. let targetName = oldName;
  3329. // If user changed the name before clicking Save Changes, execute rename first
  3330. if (newName && newName !== oldName && oldName !== 'lo') {
  3331. try {
  3332. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3333. method: 'POST',
  3334. headers: { 'Content-Type': 'application/json' },
  3335. body: JSON.stringify({ new_name: newName })
  3336. });
  3337. const data = await renameRes.json();
  3338. if (!renameRes.ok) {
  3339. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3340. return;
  3341. }
  3342. targetName = newName;
  3343. state.currentModalIface = newName;
  3344. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. return;
  3348. }
  3349. }
  3350. try {
  3351. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3352. method: 'POST',
  3353. headers: { 'Content-Type': 'application/json' },
  3354. body: JSON.stringify({ role, description: desc })
  3355. });
  3356. if (res.ok) {
  3357. showToast('Saved', 'Interface configuration updated', 'success');
  3358. closeIfaceModal();
  3359. fetchData(false);
  3360. } else {
  3361. const err = await res.json();
  3362. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3363. }
  3364. } catch (err) {
  3365. showToast('Error', err.message, 'error');
  3366. }
  3367. }
  3368. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function renderRuleFlag(disabled, hasComment) {
  3372. let flags = '';
  3373. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3374. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3375. return flags || '<span class="text-slate-600">-</span>';
  3376. }
  3377. function renderActionBadge(action) {
  3378. const act = (action || '').toLowerCase();
  3379. let color = 'bg-slate-800 text-slate-300';
  3380. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3381. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3382. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3383. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3384. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3385. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3386. }
  3387. function switchFWSubTab(tab) {
  3388. state.fwSubTab = tab;
  3389. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3390. tabs.forEach(t => {
  3391. const panel = document.getElementById(`fw-subtab-${t}`);
  3392. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3393. if (panel) {
  3394. if (t === tab) panel.classList.remove('hidden');
  3395. else panel.classList.add('hidden');
  3396. }
  3397. if (btn) {
  3398. if (t === tab) {
  3399. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3400. } else {
  3401. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3402. }
  3403. }
  3404. });
  3405. const addBtn = document.getElementById('fw-primary-add-btn');
  3406. if (addBtn) {
  3407. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3408. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3409. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3410. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3411. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3412. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3413. }
  3414. if (tab === 'filter') renderFilterRules();
  3415. else if (tab === 'nat') renderNATRules();
  3416. else if (tab === 'mangle') renderMangleRules();
  3417. else if (tab === 'addrlist') renderAddressLists();
  3418. else if (tab === 'geo') loadGeoIP();
  3419. else if (tab === 'connections') loadConnections();
  3420. setTimeout(initTableSorting, 50);
  3421. }
  3422. function openCurrentFWModal() {
  3423. if (state.fwSubTab === 'filter') openAddFilterModal();
  3424. else if (state.fwSubTab === 'nat') openAddNATModal();
  3425. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3426. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3427. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3428. else if (state.fwSubTab === 'connections') loadConnections();
  3429. }
  3430. async function loadFirewall(populateDropdowns = true) {
  3431. try {
  3432. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3433. fetch(`${API_BASE}/firewall/summary`),
  3434. fetch(`${API_BASE}/firewall/filter`),
  3435. fetch(`${API_BASE}/firewall/nat`),
  3436. fetch(`${API_BASE}/firewall/mangle`),
  3437. fetch(`${API_BASE}/firewall/address-lists`),
  3438. fetch(`${API_BASE}/firewall/geoip/status`),
  3439. fetch(`${API_BASE}/firewall/geoip/countries`)
  3440. ]);
  3441. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3442. const applyError = document.getElementById('fw-apply-error');
  3443. if (applyError) {
  3444. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3445. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3446. }
  3447. if (filterRes.ok) state.filterRules = await filterRes.json();
  3448. if (natRes.ok) state.natRules = await natRes.json();
  3449. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3450. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3451. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3452. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3453. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3454. // Badges
  3455. const bFilter = document.getElementById('fw-badge-filter');
  3456. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3457. const bNat = document.getElementById('fw-badge-nat');
  3458. if (bNat) bNat.innerText = (state.natRules || []).length;
  3459. const bMangle = document.getElementById('fw-badge-mangle');
  3460. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3461. const bAddr = document.getElementById('fw-badge-addrlist');
  3462. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3463. const bGeo = document.getElementById('fw-badge-geo');
  3464. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3465. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3466. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3467. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3468. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3469. const tbodyFilter = document.getElementById('filter-table-body');
  3470. if (tbodyFilter) {
  3471. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3472. tbodyFilter.dataset.sig = sigFilter;
  3473. renderFilterRules();
  3474. } else {
  3475. // In-place live stats update (ZERO flicker)
  3476. (state.filterRules || []).forEach(r => {
  3477. const p = document.getElementById(`filter-pkts-${r.id}`);
  3478. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3479. const b = document.getElementById(`filter-bytes-${r.id}`);
  3480. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3481. });
  3482. }
  3483. }
  3484. const tbodyNat = document.getElementById('nat-table-body');
  3485. if (tbodyNat) {
  3486. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3487. tbodyNat.dataset.sig = sigNat;
  3488. renderNATRules();
  3489. } else {
  3490. (state.natRules || []).forEach(r => {
  3491. const p = document.getElementById(`nat-pkts-${r.id}`);
  3492. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3493. const b = document.getElementById(`nat-bytes-${r.id}`);
  3494. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3495. });
  3496. }
  3497. }
  3498. const tbodyMangle = document.getElementById('mangle-table-body');
  3499. if (tbodyMangle) {
  3500. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3501. tbodyMangle.dataset.sig = sigMangle;
  3502. renderMangleRules();
  3503. } else {
  3504. (state.mangleRules || []).forEach(r => {
  3505. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3506. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3507. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3508. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3509. });
  3510. }
  3511. }
  3512. const tbodyAddr = document.getElementById('addrlist-table-body');
  3513. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3514. tbodyAddr.dataset.sig = sigAddr;
  3515. renderAddressLists();
  3516. }
  3517. renderGeoCountries();
  3518. if (state.fwSubTab === 'connections') {
  3519. loadConnections();
  3520. }
  3521. } catch (err) {
  3522. console.error('Failed to load firewall:', err);
  3523. }
  3524. }
  3525. // ----------------- Filter Rules -----------------
  3526. function renderFilterRules() {
  3527. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3528. const tbody = document.getElementById('filter-table-body');
  3529. const empty = document.getElementById('filter-empty');
  3530. if (!tbody) return;
  3531. tbody.innerHTML = '';
  3532. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3533. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3534. if (rules.length === 0) {
  3535. empty?.classList.remove('hidden');
  3536. return;
  3537. }
  3538. empty?.classList.add('hidden');
  3539. rules.forEach((raw, idx) => {
  3540. const r = safeFirewallRow(raw);
  3541. const tr = document.createElement('tr');
  3542. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3543. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3544. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3545. let actionExtra = '';
  3546. if (r.action === 'reject') {
  3547. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3548. } else if (r.action === 'jump') {
  3549. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3550. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3551. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3552. } else if (r.action === 'log' && r.log_prefix) {
  3553. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3554. }
  3555. tr.innerHTML = `
  3556. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3557. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3558. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3559. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3560. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3561. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3562. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3563. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3564. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3565. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3566. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3567. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3568. </td>
  3569. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3570. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3571. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3572. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3573. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3574. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3575. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3576. </td>
  3577. `;
  3578. tbody.appendChild(tr);
  3579. });
  3580. }
  3581. function formatTarget(addr, list, geo) {
  3582. const parts = [];
  3583. if (addr) parts.push(`<span>${addr}</span>`);
  3584. if (list) {
  3585. const inv = list.startsWith('!') ? '!' : '';
  3586. const clean = list.replace(/^!/, '');
  3587. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3588. }
  3589. if (geo) {
  3590. const inv = geo.startsWith('!') ? '!' : '';
  3591. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3592. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3593. }
  3594. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3595. return parts.join(' ');
  3596. }
  3597. function populateInterfaceSelect(selectId, currentVal = '') {
  3598. const sel = document.getElementById(selectId);
  3599. if (!sel) return;
  3600. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3601. (state.interfaces || []).forEach(i => {
  3602. const opt = document.createElement('option');
  3603. opt.value = i.name;
  3604. opt.innerText = `${i.name} (${i.role || i.type})`;
  3605. if (i.name === currentVal) opt.selected = true;
  3606. sel.appendChild(opt);
  3607. });
  3608. }
  3609. function populateAddressListSelect(selectId, currentVal = '') {
  3610. const sel = document.getElementById(selectId);
  3611. if (!sel) return;
  3612. sel.innerHTML = '<option value="">(None)</option>';
  3613. const cleanVal = (currentVal || '').replace(/^!/, '');
  3614. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3615. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3616. customNames.forEach(name => {
  3617. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3618. const opt = document.createElement('option');
  3619. opt.value = name;
  3620. opt.innerText = `${name} (${count} entries)`;
  3621. if (name === cleanVal) opt.selected = true;
  3622. sel.appendChild(opt);
  3623. });
  3624. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3625. const opt = document.createElement('option');
  3626. opt.value = cleanVal;
  3627. opt.innerText = cleanVal;
  3628. opt.selected = true;
  3629. sel.appendChild(opt);
  3630. }
  3631. populateCommonAddrListDatalist();
  3632. }
  3633. function populateCommonAddrListDatalist() {
  3634. const dl = document.getElementById('fw-addrlist-datalist');
  3635. if (!dl) return;
  3636. dl.innerHTML = '';
  3637. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3638. names.forEach(name => {
  3639. const opt = document.createElement('option');
  3640. opt.value = name;
  3641. dl.appendChild(opt);
  3642. });
  3643. }
  3644. function populateGeoIPSelect(selectId, currentVal = '') {
  3645. const sel = document.getElementById(selectId);
  3646. if (!sel) return;
  3647. sel.innerHTML = '<option value="">(None)</option>';
  3648. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3649. // Presets optgroup
  3650. const grpPresets = document.createElement('optgroup');
  3651. grpPresets.label = '⚡ Regional Presets';
  3652. const presets = [
  3653. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3654. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3655. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3656. ];
  3657. presets.forEach(p => {
  3658. const opt = document.createElement('option');
  3659. opt.value = p.code;
  3660. opt.innerText = p.label;
  3661. if (p.code === cleanVal) opt.selected = true;
  3662. grpPresets.appendChild(opt);
  3663. });
  3664. sel.appendChild(grpPresets);
  3665. // All Countries optgroup
  3666. const grpCountries = document.createElement('optgroup');
  3667. grpCountries.label = '🌍 All Countries';
  3668. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3669. countries.forEach(c => {
  3670. const opt = document.createElement('option');
  3671. opt.value = c.code;
  3672. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3673. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3674. if (c.code === cleanVal) opt.selected = true;
  3675. grpCountries.appendChild(opt);
  3676. });
  3677. sel.appendChild(grpCountries);
  3678. }
  3679. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3680. function switchFwRuleTab(tab) {
  3681. state.activeFwRuleTab = tab;
  3682. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3683. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3684. btn.classList.add('text-slate-400', 'border-transparent');
  3685. });
  3686. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3687. if (activeBtn) {
  3688. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3689. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3690. }
  3691. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3692. const activePane = document.getElementById(`fw-pane-${tab}`);
  3693. if (activePane) activePane.classList.remove('hidden');
  3694. if (tab === 'statistics') {
  3695. startFwStatPolling();
  3696. } else {
  3697. stopFwStatPolling();
  3698. }
  3699. }
  3700. function toggleFwField(fieldKey, expand) {
  3701. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3702. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3703. if (!plusBtn || !fieldBox) return;
  3704. if (expand) {
  3705. plusBtn.classList.add('hidden');
  3706. fieldBox.classList.remove('hidden');
  3707. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3708. if (valInput) valInput.focus();
  3709. } else {
  3710. fieldBox.classList.add('hidden');
  3711. plusBtn.classList.remove('hidden');
  3712. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3713. if (valInput) {
  3714. if (valInput.tagName === 'SELECT') {
  3715. valInput.selectedIndex = 0;
  3716. } else {
  3717. valInput.value = '';
  3718. }
  3719. }
  3720. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3721. if (invInput) invInput.checked = false;
  3722. if (fieldKey === 'cs') {
  3723. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3724. const el = document.getElementById(id);
  3725. if (el) el.checked = false;
  3726. });
  3727. }
  3728. if (fieldKey === 'natstate') {
  3729. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3730. const el = document.getElementById(id);
  3731. if (el) el.checked = false;
  3732. });
  3733. }
  3734. if (fieldKey === 'days') {
  3735. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3736. const el = document.getElementById(`fw-day-${d}`);
  3737. if (el) el.checked = true;
  3738. });
  3739. }
  3740. }
  3741. }
  3742. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3743. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3744. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3745. toggleFwField(fieldKey, true);
  3746. let strVal = String(value);
  3747. if (hasInvert) {
  3748. const inv = strVal.startsWith('!');
  3749. if (inv) strVal = strVal.slice(1);
  3750. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3751. if (invEl) invEl.checked = inv;
  3752. else if (inv) strVal = '!'+strVal;
  3753. }
  3754. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3755. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3756. } else {
  3757. toggleFwField(fieldKey, false);
  3758. }
  3759. }
  3760. function getFwFieldVal(fieldKey, hasInvert = false) {
  3761. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3762. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3763. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3764. let v = valEl ? valEl.value.trim() : '';
  3765. if (!v) return '';
  3766. if (hasInvert) {
  3767. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3768. if (invEl && invEl.checked) {
  3769. v = '!' + v.replace(/^!/, '');
  3770. }
  3771. }
  3772. return v;
  3773. }
  3774. function toggleMaximizeFilterModal() {
  3775. const win = document.getElementById('filter-modal-window');
  3776. if (!win) return;
  3777. if (win.classList.contains('max-w-[720px]')) {
  3778. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3779. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3780. } else {
  3781. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3782. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3783. }
  3784. }
  3785. function openAddFilterModal() {
  3786. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3787. switchFwRuleTab('general');
  3788. setFirewallDays('fw', '');
  3789. const badge = document.getElementById('fw-modal-badge');
  3790. if (badge) badge.innerText = 'New...';
  3791. document.getElementById('filter-modal-id').value = '';
  3792. document.getElementById('filter-modal-family').value = '4';
  3793. document.getElementById('filter-modal-enabled').checked = true;
  3794. document.getElementById('filter-modal-comment').value = '';
  3795. document.getElementById('filter-modal-chain').value = 'forward';
  3796. document.getElementById('filter-modal-action').value = 'accept';
  3797. document.getElementById('filter-modal-log').checked = false;
  3798. populateInterfaceSelect('fw-val-iniface');
  3799. populateInterfaceSelect('fw-val-outiface');
  3800. populateAddressListSelect('fw-val-srclist');
  3801. populateAddressListSelect('fw-val-dstlist');
  3802. populateGeoIPSelect('fw-val-srcgeo');
  3803. populateGeoIPSelect('fw-val-dstgeo');
  3804. const allFieldKeys = [
  3805. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3806. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3807. 'routingmark', 'conntype', 'cs', 'natstate',
  3808. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3809. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3810. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3811. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3812. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3813. ];
  3814. allFieldKeys.forEach(k => toggleFwField(k, false));
  3815. resetRuleCounterDisplay();
  3816. toggleFilterActionFields();
  3817. refreshFirewallRejectTypes();
  3818. document.getElementById('filter-modal').classList.remove('hidden');
  3819. }
  3820. function openEditFilterModal(id) {
  3821. id = decodeURIComponent(id);
  3822. const r = (state.filterRules || []).find(rule => rule.id === id);
  3823. if (!r) return;
  3824. switchFwRuleTab('general');
  3825. const badge = document.getElementById('fw-modal-badge');
  3826. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3827. document.getElementById('filter-modal-id').value = r.id;
  3828. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  3829. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3830. document.getElementById('filter-modal-comment').value = r.comment || '';
  3831. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3832. setFirewallActionSelection('filter', r.action || 'accept');
  3833. document.getElementById('filter-modal-log').checked = !!r.log;
  3834. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3835. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3836. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3837. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3838. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3839. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3840. setFwFieldVal('src', r.src_address, true);
  3841. setFwFieldVal('dst', r.dst_address, true);
  3842. setFwFieldVal('srclist', r.src_address_list, true);
  3843. setFwFieldVal('dstlist', r.dst_address_list, true);
  3844. setFwFieldVal('srcgeo', r.src_geoip, true);
  3845. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3846. if (r.protocol && r.protocol !== 'all') {
  3847. setFwFieldVal('proto', r.protocol, true);
  3848. } else {
  3849. toggleFwField('proto', false);
  3850. }
  3851. setFwFieldVal('sport', r.src_port, true);
  3852. setFwFieldVal('dport', r.dst_port, true);
  3853. setFwFieldVal('anyport', r.any_port, true);
  3854. setFwFieldVal('iniface', r.in_interface, true);
  3855. setFwFieldVal('outiface', r.out_interface, true);
  3856. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3857. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3858. setFwFieldVal('pktmark', r.packet_mark, true);
  3859. setFwFieldVal('connmark', r.connection_mark, true);
  3860. setFwFieldVal('routingmark', r.routing_mark, true);
  3861. setFwFieldVal('conntype', r.connection_type, false);
  3862. const states = r.connection_state || [];
  3863. if (states.length > 0) {
  3864. toggleFwField('cs', true);
  3865. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3866. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3867. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3868. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3869. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3870. } else {
  3871. toggleFwField('cs', false);
  3872. }
  3873. const natStates = r.connection_nat_state || [];
  3874. if (natStates.length > 0) {
  3875. toggleFwField('natstate', true);
  3876. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3877. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3878. } else {
  3879. toggleFwField('natstate', false);
  3880. }
  3881. // Advanced tab fields
  3882. setFwFieldVal('layer7', r.layer7_protocol, false);
  3883. setFwFieldVal('content', r.content, false);
  3884. setFwFieldVal('connbytes', r.connection_bytes, false);
  3885. setFwFieldVal('connrate', r.connection_rate, false);
  3886. setFwFieldVal('pcc', r.pcc, false);
  3887. setFwFieldVal('srcmac', r.src_mac_address, true);
  3888. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3889. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3890. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3891. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3892. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3893. setFwFieldVal('tlshost', r.tls_host, false);
  3894. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3895. setFwFieldVal('priority', r.priority, false);
  3896. setFwFieldVal('dscp', r.dscp, false);
  3897. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3898. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  3899. setFwFieldVal('pktsize', r.packet_size, false);
  3900. setFwFieldVal('random', r.random, false);
  3901. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3902. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3903. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3904. setFwFieldVal('ttl', r.ttl, false);
  3905. // Extra tab fields
  3906. setFwFieldVal('time', r.time, false);
  3907. if (r.days) {
  3908. toggleFwField('days', true);
  3909. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3910. const chk = document.getElementById(`fw-day-${d}`);
  3911. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  3912. });
  3913. } else {
  3914. toggleFwField('days', false);
  3915. }
  3916. setFwFieldVal('limit', r.limit, false);
  3917. setFwFieldVal('dstlimit', r.dst_limit, false);
  3918. setFwFieldVal('psd', r.psd, false);
  3919. // Action fields
  3920. if (r.reject_with) {
  3921. const rwEl = document.getElementById('filter-modal-rejectwith');
  3922. if (rwEl) rwEl.value = r.reject_with;
  3923. }
  3924. if (r.jump_target) {
  3925. const jtEl = document.getElementById('filter-modal-jumptarget');
  3926. if (jtEl) jtEl.value = r.jump_target;
  3927. }
  3928. if (r.address_list) {
  3929. const alEl = document.getElementById('filter-modal-action-addrlist');
  3930. if (alEl) alEl.value = r.address_list;
  3931. }
  3932. if (r.address_list_timeout) {
  3933. const toEl = document.getElementById('filter-modal-action-timeout');
  3934. if (toEl) toEl.value = r.address_list_timeout;
  3935. }
  3936. setFwFieldVal('logprefix', r.log_prefix, false);
  3937. // Statistics
  3938. const bEl = document.getElementById('fw-stat-bytes');
  3939. const pEl = document.getElementById('fw-stat-packets');
  3940. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3941. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3942. state.fwLastBytes = r.bytes || 0;
  3943. state.fwLastPackets = r.packets || 0;
  3944. state.fwLastTimestamp = Date.now();
  3945. state.fwStatRateHistory = new Array(30).fill(0);
  3946. state.fwStatPktHistory = new Array(30).fill(0);
  3947. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3948. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3949. toggleFilterActionFields();
  3950. refreshFirewallRejectTypes();
  3951. document.getElementById('filter-modal').classList.remove('hidden');
  3952. }
  3953. function closeFilterModal() {
  3954. stopFwStatPolling();
  3955. document.getElementById('filter-modal').classList.add('hidden');
  3956. }
  3957. function toggleFilterActionFields() {
  3958. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3959. const rejectBox = document.getElementById('filter-action-reject-box');
  3960. const jumpBox = document.getElementById('filter-action-jump-box');
  3961. const addrBox = document.getElementById('filter-action-addrlist-box');
  3962. if (rejectBox) {
  3963. if (act === 'reject') rejectBox.classList.remove('hidden');
  3964. else rejectBox.classList.add('hidden');
  3965. }
  3966. if (jumpBox) {
  3967. if (act === 'jump') jumpBox.classList.remove('hidden');
  3968. else jumpBox.classList.add('hidden');
  3969. }
  3970. if (addrBox) {
  3971. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3972. addrBox.classList.remove('hidden');
  3973. } else {
  3974. addrBox.classList.add('hidden');
  3975. }
  3976. }
  3977. if (act === 'log') {
  3978. const logEl = document.getElementById('filter-modal-log');
  3979. if (logEl) logEl.checked = true;
  3980. toggleFwField('logprefix', true);
  3981. }
  3982. }
  3983. function toggleFwLogPrefix() {
  3984. const isLog = document.getElementById('filter-modal-log')?.checked;
  3985. toggleFwField('logprefix', !!isLog);
  3986. }
  3987. function copyFilterRule() {
  3988. document.getElementById('filter-modal-id').value = '';
  3989. const badge = document.getElementById('fw-modal-badge');
  3990. if (badge) badge.innerText = 'New...';
  3991. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3992. }
  3993. function resetRuleCounterDisplay() {
  3994. state.fwStatRateHistory = new Array(30).fill(0);
  3995. state.fwStatPktHistory = new Array(30).fill(0);
  3996. state.fwLastBytes = 0;
  3997. state.fwLastPackets = 0;
  3998. state.fwLastTimestamp = Date.now();
  3999. const bEl = document.getElementById('fw-stat-bytes');
  4000. const pEl = document.getElementById('fw-stat-packets');
  4001. const rEl = document.getElementById('fw-stat-rate');
  4002. const prEl = document.getElementById('fw-stat-pktrate');
  4003. if (bEl) bEl.value = '0 B';
  4004. if (pEl) pEl.value = '0';
  4005. if (rEl) rEl.value = '0 bps';
  4006. if (prEl) prEl.value = '0 p/s';
  4007. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4008. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4009. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4010. }
  4011. async function resetAllFwCounters() {
  4012. try {
  4013. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4014. if (res.ok) {
  4015. resetRuleCounterDisplay();
  4016. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4017. loadFirewall(false);
  4018. }
  4019. } catch (err) {
  4020. showToast('Error', err.message, 'error');
  4021. }
  4022. }
  4023. async function applyFilterRule(closeAfter = false) {
  4024. const id = document.getElementById('filter-modal-id').value;
  4025. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4026. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4027. const chain = document.getElementById('filter-modal-chain').value;
  4028. const action = document.getElementById('filter-modal-action').value;
  4029. const comment = document.getElementById('filter-modal-comment').value.trim();
  4030. const enabled = document.getElementById('filter-modal-enabled').checked;
  4031. const src = getFwFieldVal('src', true);
  4032. const dst = getFwFieldVal('dst', true);
  4033. const srclist = getFwFieldVal('srclist', true);
  4034. const dstlist = getFwFieldVal('dstlist', true);
  4035. const srcgeo = getFwFieldVal('srcgeo', true);
  4036. const dstgeo = getFwFieldVal('dstgeo', true);
  4037. const proto = getFwFieldVal('proto', true);
  4038. const sport = getFwFieldVal('sport', true);
  4039. const dport = getFwFieldVal('dport', true);
  4040. const anyport = getFwFieldVal('anyport', true);
  4041. const iniface = getFwFieldVal('iniface', true);
  4042. const outiface = getFwFieldVal('outiface', true);
  4043. const inifacelist = getFwFieldVal('inifacelist', true);
  4044. const outifacelist = getFwFieldVal('outifacelist', true);
  4045. const pktmark = getFwFieldVal('pktmark', true);
  4046. const connmark = getFwFieldVal('connmark', true);
  4047. const routingmark = getFwFieldVal('routingmark', true);
  4048. const conntype = getFwFieldVal('conntype', false);
  4049. const states = [];
  4050. const csBox = document.getElementById('fw-field-cs');
  4051. if (csBox && !csBox.classList.contains('hidden')) {
  4052. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4053. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4054. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4055. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4056. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4057. }
  4058. const natStates = [];
  4059. const natBox = document.getElementById('fw-field-natstate');
  4060. if (natBox && !natBox.classList.contains('hidden')) {
  4061. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4062. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4063. }
  4064. const payload = {
  4065. ip_version: Number(document.getElementById('filter-modal-family').value),
  4066. id,
  4067. chain,
  4068. action,
  4069. protocol: proto || 'all',
  4070. src_address: src,
  4071. dst_address: dst,
  4072. src_port: sport,
  4073. dst_port: dport,
  4074. any_port: anyport,
  4075. in_interface: iniface,
  4076. out_interface: outiface,
  4077. in_interface_list: inifacelist,
  4078. out_interface_list: outifacelist,
  4079. packet_mark: pktmark,
  4080. connection_mark: connmark,
  4081. routing_mark: routingmark,
  4082. connection_type: conntype,
  4083. connection_state: states,
  4084. connection_nat_state: natStates,
  4085. src_address_list: srclist,
  4086. dst_address_list: dstlist,
  4087. src_geoip: srcgeo,
  4088. dst_geoip: dstgeo,
  4089. comment,
  4090. disabled: !enabled,
  4091. // Advanced tab
  4092. content: getFwFieldVal('content', false),
  4093. src_mac_address: getFwFieldVal('srcmac', true),
  4094. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4095. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4096. ipsec_policy: getFwFieldVal('ipsec', false),
  4097. dscp: getFwFieldVal('dscp', false),
  4098. tcp_mss: getFwFieldVal('tcpmss', false),
  4099. tos: document.getElementById('fw-val-tos')?.value || '',
  4100. packet_size: getFwFieldVal('pktsize', false),
  4101. random: getFwFieldVal('random', false),
  4102. tcp_flags: getFwFieldVal('tcpflags', false),
  4103. icmp_options: getFwFieldVal('icmpoptions', false),
  4104. ttl: getFwFieldVal('ttl', false),
  4105. days: selectedDays,
  4106. // Extra tab
  4107. time: getFwFieldVal('time', false),
  4108. limit: getFwFieldVal('limit', false),
  4109. // Action tab
  4110. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4111. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4112. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4113. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4114. log: document.getElementById('filter-modal-log')?.checked || false,
  4115. log_prefix: getFwFieldVal('logprefix', false)
  4116. };
  4117. try {
  4118. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4119. method: 'POST',
  4120. headers: { 'Content-Type': 'application/json' },
  4121. body: JSON.stringify(payload)
  4122. });
  4123. if (res.ok) {
  4124. const data = await res.json();
  4125. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4126. loadFirewall(false);
  4127. if (closeAfter) {
  4128. closeFilterModal();
  4129. } else {
  4130. if (data.id) {
  4131. document.getElementById('filter-modal-id').value = data.id;
  4132. const badge = document.getElementById('fw-modal-badge');
  4133. if (badge) badge.innerText = `#${data.id}`;
  4134. }
  4135. }
  4136. } else {
  4137. const err = await res.json();
  4138. showToast('Error', err.message || 'Failed to save rule', 'error');
  4139. }
  4140. } catch (err) {
  4141. showToast('Error', err.message, 'error');
  4142. }
  4143. }
  4144. function submitSaveFilterRule(e) {
  4145. if (e && e.preventDefault) e.preventDefault();
  4146. return applyFilterRule(true);
  4147. }
  4148. function startFwStatPolling() {
  4149. stopFwStatPolling();
  4150. pollRuleStats();
  4151. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4152. }
  4153. function stopFwStatPolling() {
  4154. if (state.fwStatInterval) {
  4155. clearInterval(state.fwStatInterval);
  4156. state.fwStatInterval = null;
  4157. }
  4158. }
  4159. async function pollRuleStats() {
  4160. const id = document.getElementById('filter-modal-id')?.value;
  4161. if (!id) {
  4162. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4163. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4164. return;
  4165. }
  4166. try {
  4167. const res = await fetch(`${API_BASE}/firewall/filter`);
  4168. if (!res.ok) return;
  4169. const rules = await res.json();
  4170. const r = rules.find(x => x.id === id);
  4171. if (!r) return;
  4172. const now = Date.now();
  4173. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4174. state.fwLastTimestamp = now;
  4175. const curBytes = r.bytes || 0;
  4176. const curPackets = r.packets || 0;
  4177. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4178. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4179. state.fwLastBytes = curBytes;
  4180. state.fwLastPackets = curPackets;
  4181. const rateBps = Math.round((deltaBytes * 8) / dt);
  4182. const ratePkt = Math.round(deltaPkts / dt);
  4183. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4184. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4185. state.fwStatRateHistory.push(rateBps);
  4186. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4187. state.fwStatPktHistory.push(ratePkt);
  4188. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4189. const bEl = document.getElementById('fw-stat-bytes');
  4190. const pEl = document.getElementById('fw-stat-packets');
  4191. const rEl = document.getElementById('fw-stat-rate');
  4192. const prEl = document.getElementById('fw-stat-pktrate');
  4193. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4194. if (pEl) pEl.value = curPackets.toLocaleString();
  4195. if (rEl) rEl.value = formatBps(rateBps);
  4196. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4197. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4198. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4199. } catch (e) {
  4200. console.error('Error polling rule stats', e);
  4201. }
  4202. }
  4203. function formatBps(bps) {
  4204. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4205. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4206. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4207. return bps + ' bps';
  4208. }
  4209. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4210. const svg = document.getElementById(svgId);
  4211. if (!svg) return;
  4212. const w = 500;
  4213. const h = 100;
  4214. const paddingRight = 45;
  4215. const graphWidth = w - paddingRight;
  4216. const maxVal = Math.max(5, ...dataArray);
  4217. const currentVal = dataArray[dataArray.length - 1] || 0;
  4218. const leg = document.getElementById(legendId);
  4219. if (leg) {
  4220. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4221. }
  4222. let gridLines = '';
  4223. for (let i = 0; i <= 5; i++) {
  4224. const y = 8 + (i * (h - 18) / 5);
  4225. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4226. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4227. gridLines += `
  4228. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4229. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4230. `;
  4231. }
  4232. const step = graphWidth / (dataArray.length - 1);
  4233. const points = dataArray.map((val, idx) => {
  4234. const x = idx * step;
  4235. const y = (h - 10) - (val / maxVal) * (h - 20);
  4236. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4237. });
  4238. const polylineStr = points.join(' ');
  4239. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4240. svg.innerHTML = `
  4241. ${gridLines}
  4242. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4243. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4244. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4245. `;
  4246. }
  4247. async function moveFilterRule(id, dir) {
  4248. id = decodeURIComponent(id);
  4249. try {
  4250. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4251. method: 'POST',
  4252. headers: { 'Content-Type': 'application/json' },
  4253. body: JSON.stringify({ direction: dir })
  4254. });
  4255. if (res.ok) loadFirewall(false);
  4256. } catch (err) {
  4257. showToast('Error', err.message, 'error');
  4258. }
  4259. }
  4260. async function toggleFilterRuleState(id, disabled) {
  4261. id = decodeURIComponent(id);
  4262. try {
  4263. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4264. method: 'POST',
  4265. headers: { 'Content-Type': 'application/json' },
  4266. body: JSON.stringify({ disabled })
  4267. });
  4268. if (res.ok) loadFirewall(false);
  4269. } catch (err) {
  4270. showToast('Error', err.message, 'error');
  4271. }
  4272. }
  4273. async function deleteFilterRule(id) {
  4274. id = decodeURIComponent(id);
  4275. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4276. try {
  4277. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4278. if (res.ok) {
  4279. showToast('Deleted', 'Filter rule removed', 'success');
  4280. loadFirewall(false);
  4281. }
  4282. } catch (err) {
  4283. showToast('Error', err.message, 'error');
  4284. }
  4285. }
  4286. // ----------------- NAT Rules -----------------
  4287. function renderNATRules() {
  4288. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4289. const tbody = document.getElementById('nat-table-body');
  4290. const empty = document.getElementById('nat-empty');
  4291. if (!tbody) return;
  4292. tbody.innerHTML = '';
  4293. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4294. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4295. if (rules.length === 0) {
  4296. empty?.classList.remove('hidden');
  4297. return;
  4298. }
  4299. empty?.classList.add('hidden');
  4300. rules.forEach((raw, idx) => {
  4301. const r = safeFirewallRow(raw);
  4302. const tr = document.createElement('tr');
  4303. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4304. let toTarget = '-';
  4305. if (r.action === 'jump') {
  4306. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4307. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4308. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4309. } else if (r.action === 'redirect') {
  4310. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4311. } else if (r.action === 'masquerade') {
  4312. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  4313. } else if (r.action === 'log') {
  4314. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4315. } else {
  4316. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4317. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4318. }
  4319. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4320. tr.innerHTML = `
  4321. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4322. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4323. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4324. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4325. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4326. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4327. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4328. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4329. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4330. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4331. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4332. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4333. </td>
  4334. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4335. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4336. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4337. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4338. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4339. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4340. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4341. </td>
  4342. `;
  4343. tbody.appendChild(tr);
  4344. });
  4345. }
  4346. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4347. function switchNATRuleTab(tab) {
  4348. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4349. state.activeNATRuleTab = tab;
  4350. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4351. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4352. btn.classList.add('text-slate-400', 'border-transparent');
  4353. });
  4354. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4355. if (activeBtn) {
  4356. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4357. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4358. }
  4359. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4360. const activePane = document.getElementById(`nat-pane-${tab}`);
  4361. if (activePane) activePane.classList.remove('hidden');
  4362. if (tab === 'statistics') {
  4363. startNATStatPolling();
  4364. } else {
  4365. stopNATStatPolling();
  4366. }
  4367. }
  4368. function toggleNATField(fieldKey, expand) {
  4369. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4370. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4371. if (!plusBtn || !fieldBox) return;
  4372. if (expand) {
  4373. plusBtn.classList.add('hidden');
  4374. fieldBox.classList.remove('hidden');
  4375. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4376. if (valInput) valInput.focus();
  4377. } else {
  4378. fieldBox.classList.add('hidden');
  4379. plusBtn.classList.remove('hidden');
  4380. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4381. if (valInput) {
  4382. if (valInput.tagName === 'SELECT') {
  4383. valInput.selectedIndex = 0;
  4384. } else {
  4385. valInput.value = '';
  4386. }
  4387. }
  4388. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4389. if (invInput) invInput.checked = false;
  4390. if (fieldKey === 'days') {
  4391. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4392. const el = document.getElementById(`nat-day-${d}`);
  4393. if (el) el.checked = true;
  4394. });
  4395. }
  4396. }
  4397. }
  4398. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4399. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4400. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4401. toggleNATField(fieldKey, true);
  4402. let strVal = String(value);
  4403. if (hasInvert) {
  4404. const inv = strVal.startsWith('!');
  4405. if (inv) strVal = strVal.slice(1);
  4406. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4407. if (invEl) invEl.checked = inv;
  4408. else if (inv) strVal = '!'+strVal;
  4409. }
  4410. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4411. 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; }
  4412. } else {
  4413. toggleNATField(fieldKey, false);
  4414. }
  4415. }
  4416. function getNATFieldVal(fieldKey, hasInvert = false) {
  4417. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4418. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4419. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4420. let v = valEl ? valEl.value.trim() : '';
  4421. if (!v) return '';
  4422. if (hasInvert) {
  4423. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4424. if (invEl && invEl.checked) {
  4425. v = '!' + v.replace(/^!/, '');
  4426. }
  4427. }
  4428. return v;
  4429. }
  4430. function toggleMaximizeNATModal() {
  4431. const win = document.getElementById('nat-modal-window');
  4432. if (!win) return;
  4433. if (win.classList.contains('max-w-[720px]')) {
  4434. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4435. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4436. } else {
  4437. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4438. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4439. }
  4440. }
  4441. function handleNATChainChange() {
  4442. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4443. const actSel = document.getElementById('nat-modal-action');
  4444. if (actSel) {
  4445. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4446. actSel.value = 'masquerade';
  4447. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4448. actSel.value = 'dst-nat';
  4449. }
  4450. }
  4451. toggleNATActionFields();
  4452. }
  4453. function toggleNATActionFields() {
  4454. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4455. const rowAddr = document.getElementById('nat-row-toaddr');
  4456. const rowPort = document.getElementById('nat-row-toport');
  4457. const jumpBox = document.getElementById('nat-action-jump-box');
  4458. const addrBox = document.getElementById('nat-action-addrlist-box');
  4459. // Hide all dynamic rows first
  4460. if (rowAddr) rowAddr.classList.add('hidden');
  4461. if (rowPort) rowPort.classList.add('hidden');
  4462. if (jumpBox) jumpBox.classList.add('hidden');
  4463. if (addrBox) addrBox.classList.add('hidden');
  4464. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4465. if (rowAddr) rowAddr.classList.remove('hidden');
  4466. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4467. } else if (act === 'redirect' || act === 'masquerade') {
  4468. if (rowPort) rowPort.classList.remove('hidden');
  4469. } else if (act === 'jump') {
  4470. if (jumpBox) jumpBox.classList.remove('hidden');
  4471. } else if (act.includes('address-list') || act.includes('address list')) {
  4472. if (addrBox) addrBox.classList.remove('hidden');
  4473. }
  4474. if (act === 'log') {
  4475. const logEl = document.getElementById('nat-modal-log');
  4476. if (logEl) logEl.checked = true;
  4477. toggleNATField('logprefix', true);
  4478. }
  4479. }
  4480. function handleNATActionChange() {
  4481. const action = document.getElementById('nat-modal-action')?.value;
  4482. const chain = document.getElementById('nat-modal-chain');
  4483. if (action === 'dst-nat' && chain && ['srcnat', 'postrouting', 'input'].includes(chain.value.toLowerCase())) chain.value = 'dstnat';
  4484. toggleNATActionFields();
  4485. }
  4486. function toggleNATLogPrefix() {
  4487. const isLog = document.getElementById('nat-modal-log')?.checked;
  4488. toggleNATField('logprefix', !!isLog);
  4489. }
  4490. function openAddNATModal() {
  4491. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4492. switchNATRuleTab('general');
  4493. setFirewallDays('nat', '');
  4494. const badge = document.getElementById('nat-modal-badge');
  4495. if (badge) badge.innerText = 'New...';
  4496. document.getElementById('nat-modal-id').value = '';
  4497. document.getElementById('nat-modal-family').value = '4';
  4498. document.getElementById('nat-modal-enabled').checked = true;
  4499. document.getElementById('nat-modal-comment').value = '';
  4500. document.getElementById('nat-modal-chain').value = 'srcnat';
  4501. document.getElementById('nat-modal-action').value = 'masquerade';
  4502. document.getElementById('nat-modal-toaddr').value = '';
  4503. document.getElementById('nat-modal-toport').value = '';
  4504. document.getElementById('nat-modal-log').checked = false;
  4505. populateInterfaceSelect('nat-val-iniface');
  4506. populateInterfaceSelect('nat-val-outiface');
  4507. populateAddressListSelect('nat-val-srclist');
  4508. populateAddressListSelect('nat-val-dstlist');
  4509. populateGeoIPSelect('nat-val-srcgeo');
  4510. populateGeoIPSelect('nat-val-dstgeo');
  4511. const allFieldKeys = [
  4512. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4513. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4514. 'routingmark', 'conntype',
  4515. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4516. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4517. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4518. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4519. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4520. ];
  4521. allFieldKeys.forEach(k => toggleNATField(k, false));
  4522. resetNATCounterDisplay();
  4523. toggleNATActionFields();
  4524. document.getElementById('nat-modal').classList.remove('hidden');
  4525. }
  4526. function openEditNATModal(id) {
  4527. id = decodeURIComponent(id);
  4528. const r = (state.natRules || []).find(rule => rule.id === id);
  4529. if (!r) return;
  4530. setFirewallDays('nat', r.days || '');
  4531. switchNATRuleTab('general');
  4532. const badge = document.getElementById('nat-modal-badge');
  4533. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4534. document.getElementById('nat-modal-id').value = r.id;
  4535. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4536. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4537. document.getElementById('nat-modal-comment').value = r.comment || '';
  4538. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4539. setFirewallActionSelection('nat', r.action || 'accept');
  4540. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4541. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4542. document.getElementById('nat-modal-log').checked = !!r.log;
  4543. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4544. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4545. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4546. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4547. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4548. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4549. setNATFieldVal('src', r.src_address, true);
  4550. setNATFieldVal('dst', r.dst_address, true);
  4551. setNATFieldVal('srclist', r.src_address_list, true);
  4552. setNATFieldVal('dstlist', r.dst_address_list, true);
  4553. setNATFieldVal('srcgeo', r.src_geoip, true);
  4554. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4555. if (r.protocol && r.protocol !== 'all') {
  4556. setNATFieldVal('proto', r.protocol, true);
  4557. } else {
  4558. toggleNATField('proto', false);
  4559. }
  4560. setNATFieldVal('sport', r.src_port, true);
  4561. setNATFieldVal('dport', r.dst_port, true);
  4562. setNATFieldVal('anyport', r.any_port, true);
  4563. setNATFieldVal('iniface', r.in_interface, true);
  4564. setNATFieldVal('outiface', r.out_interface, true);
  4565. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4566. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4567. setNATFieldVal('pktmark', r.packet_mark, true);
  4568. setNATFieldVal('connmark', r.connection_mark, true);
  4569. setNATFieldVal('routingmark', r.routing_mark, true);
  4570. setNATFieldVal('conntype', r.connection_type, false);
  4571. // Advanced tab fields
  4572. setNATFieldVal('layer7', r.layer7_protocol, false);
  4573. setNATFieldVal('content', r.content, false);
  4574. setNATFieldVal('connbytes', r.connection_bytes, false);
  4575. setNATFieldVal('connrate', r.connection_rate, false);
  4576. setNATFieldVal('pcc', r.pcc, false);
  4577. setNATFieldVal('srcmac', r.src_mac_address, true);
  4578. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4579. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4580. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4581. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4582. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4583. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4584. setNATFieldVal('priority', r.priority, false);
  4585. setNATFieldVal('dscp', r.dscp, false);
  4586. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4587. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4588. setNATFieldVal('pktsize', r.packet_size, false);
  4589. setNATFieldVal('random', r.random, false);
  4590. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4591. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4592. setNATFieldVal('ttl', r.ttl, false);
  4593. // Extra tab fields
  4594. setNATFieldVal('time', r.time, false);
  4595. if (r.days) {
  4596. toggleNATField('days', true);
  4597. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4598. const chk = document.getElementById(`nat-day-${d}`);
  4599. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4600. });
  4601. } else {
  4602. toggleNATField('days', false);
  4603. }
  4604. setNATFieldVal('limit', r.limit, false);
  4605. setNATFieldVal('dstlimit', r.dst_limit, false);
  4606. setNATFieldVal('psd', r.psd, false);
  4607. // Action fields
  4608. if (r.jump_target) {
  4609. const jtEl = document.getElementById('nat-modal-jumptarget');
  4610. if (jtEl) jtEl.value = r.jump_target;
  4611. }
  4612. if (r.address_list) {
  4613. const alEl = document.getElementById('nat-modal-action-addrlist');
  4614. if (alEl) alEl.value = r.address_list;
  4615. }
  4616. if (r.address_list_timeout) {
  4617. const toEl = document.getElementById('nat-modal-action-timeout');
  4618. if (toEl) toEl.value = r.address_list_timeout;
  4619. }
  4620. setNATFieldVal('logprefix', r.log_prefix, false);
  4621. // Statistics
  4622. const bEl = document.getElementById('nat-stat-bytes');
  4623. const pEl = document.getElementById('nat-stat-packets');
  4624. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4625. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4626. state.natLastBytes = r.bytes || 0;
  4627. state.natLastPackets = r.packets || 0;
  4628. state.natLastTimestamp = Date.now();
  4629. state.natStatRateHistory = new Array(30).fill(0);
  4630. state.natStatPktHistory = new Array(30).fill(0);
  4631. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4632. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4633. toggleNATActionFields();
  4634. document.getElementById('nat-modal').classList.remove('hidden');
  4635. }
  4636. function closeNATModal() {
  4637. stopNATStatPolling();
  4638. document.getElementById('nat-modal').classList.add('hidden');
  4639. }
  4640. function copyNATRule() {
  4641. document.getElementById('nat-modal-id').value = '';
  4642. const badge = document.getElementById('nat-modal-badge');
  4643. if (badge) badge.innerText = 'New...';
  4644. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4645. }
  4646. function resetNATCounterDisplay() {
  4647. state.natStatRateHistory = new Array(30).fill(0);
  4648. state.natStatPktHistory = new Array(30).fill(0);
  4649. state.natLastBytes = 0;
  4650. state.natLastPackets = 0;
  4651. state.natLastTimestamp = Date.now();
  4652. const bEl = document.getElementById('nat-stat-bytes');
  4653. const pEl = document.getElementById('nat-stat-packets');
  4654. const rEl = document.getElementById('nat-stat-rate');
  4655. const prEl = document.getElementById('nat-stat-pktrate');
  4656. if (bEl) bEl.value = '0 B';
  4657. if (pEl) pEl.value = '0';
  4658. if (rEl) rEl.value = '0 bps';
  4659. if (prEl) prEl.value = '0 p/s';
  4660. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4661. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4662. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4663. }
  4664. async function applyNATRule(closeAfter = false) {
  4665. const id = document.getElementById('nat-modal-id').value;
  4666. if (!reviewLegacyFirewallSettings('nat', id)) return;
  4667. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4668. const chain = document.getElementById('nat-modal-chain').value;
  4669. const action = document.getElementById('nat-modal-action').value;
  4670. const comment = document.getElementById('nat-modal-comment').value.trim();
  4671. const enabled = document.getElementById('nat-modal-enabled').checked;
  4672. const src = getNATFieldVal('src', true);
  4673. const dst = getNATFieldVal('dst', true);
  4674. const srclist = getNATFieldVal('srclist', true);
  4675. const dstlist = getNATFieldVal('dstlist', true);
  4676. const srcgeo = getNATFieldVal('srcgeo', true);
  4677. const dstgeo = getNATFieldVal('dstgeo', true);
  4678. const proto = getNATFieldVal('proto', true);
  4679. const sport = getNATFieldVal('sport', true);
  4680. const dport = getNATFieldVal('dport', true);
  4681. const anyport = getNATFieldVal('anyport', true);
  4682. const iniface = getNATFieldVal('iniface', true);
  4683. const outiface = getNATFieldVal('outiface', true);
  4684. const inifacelist = getNATFieldVal('inifacelist', true);
  4685. const outifacelist = getNATFieldVal('outifacelist', true);
  4686. const pktmark = getNATFieldVal('pktmark', true);
  4687. const connmark = getNATFieldVal('connmark', true);
  4688. const routingmark = getNATFieldVal('routingmark', true);
  4689. const conntype = getNATFieldVal('conntype', false);
  4690. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  4691. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  4692. if (!chain.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  4693. 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; }
  4694. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  4695. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  4696. 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;
  4697. }
  4698. const payload = {
  4699. ip_version: Number(document.getElementById('nat-modal-family').value),
  4700. id,
  4701. chain,
  4702. action,
  4703. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4704. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4705. protocol: proto || 'all',
  4706. src_address: src,
  4707. dst_address: dst,
  4708. src_port: sport,
  4709. dst_port: dport,
  4710. any_port: anyport,
  4711. in_interface: iniface,
  4712. out_interface: outiface,
  4713. in_interface_list: inifacelist,
  4714. out_interface_list: outifacelist,
  4715. packet_mark: pktmark,
  4716. connection_mark: connmark,
  4717. routing_mark: routingmark,
  4718. connection_type: conntype,
  4719. src_address_list: srclist,
  4720. dst_address_list: dstlist,
  4721. src_geoip: srcgeo,
  4722. dst_geoip: dstgeo,
  4723. comment,
  4724. disabled: !enabled,
  4725. // Advanced tab
  4726. content: getNATFieldVal('content', false),
  4727. src_mac_address: getNATFieldVal('srcmac', true),
  4728. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4729. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4730. ipsec_policy: getNATFieldVal('ipsec', false),
  4731. dscp: getNATFieldVal('dscp', false),
  4732. tcp_mss: getNATFieldVal('tcpmss', false),
  4733. tos: document.getElementById('nat-val-tos')?.value || '',
  4734. packet_size: getNATFieldVal('pktsize', false),
  4735. random: getNATFieldVal('random', false),
  4736. icmp_options: getNATFieldVal('icmpoptions', false),
  4737. ttl: getNATFieldVal('ttl', false),
  4738. days: selectedDays,
  4739. // Extra tab
  4740. time: getNATFieldVal('time', false),
  4741. limit: getNATFieldVal('limit', false),
  4742. // Action tab
  4743. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4744. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4745. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4746. log: document.getElementById('nat-modal-log')?.checked || false,
  4747. log_prefix: getNATFieldVal('logprefix', false)
  4748. };
  4749. try {
  4750. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4751. method: 'POST',
  4752. headers: { 'Content-Type': 'application/json' },
  4753. body: JSON.stringify(payload)
  4754. });
  4755. if (res.ok) {
  4756. const data = await res.json();
  4757. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4758. loadFirewall(false);
  4759. if (closeAfter) {
  4760. closeNATModal();
  4761. } else {
  4762. if (data.id) {
  4763. document.getElementById('nat-modal-id').value = data.id;
  4764. const badge = document.getElementById('nat-modal-badge');
  4765. if (badge) badge.innerText = `#${data.id}`;
  4766. }
  4767. }
  4768. } else {
  4769. const err = await res.json();
  4770. showToast('Error', err.message || 'Failed to save rule', 'error');
  4771. }
  4772. } catch (err) {
  4773. showToast('Error', err.message, 'error');
  4774. }
  4775. }
  4776. function submitSaveNATRule(e) {
  4777. if (e && e.preventDefault) e.preventDefault();
  4778. return applyNATRule(true);
  4779. }
  4780. function startNATStatPolling() {
  4781. stopNATStatPolling();
  4782. pollNATRuleStats();
  4783. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4784. }
  4785. function stopNATStatPolling() {
  4786. if (state.natStatInterval) {
  4787. clearInterval(state.natStatInterval);
  4788. state.natStatInterval = null;
  4789. }
  4790. }
  4791. async function pollNATRuleStats() {
  4792. const id = document.getElementById('nat-modal-id')?.value;
  4793. if (!id) {
  4794. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4795. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4796. return;
  4797. }
  4798. try {
  4799. const res = await fetch(`${API_BASE}/firewall/nat`);
  4800. if (!res.ok) return;
  4801. const rules = await res.json();
  4802. const r = rules.find(x => x.id === id);
  4803. if (!r) return;
  4804. const now = Date.now();
  4805. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4806. state.natLastTimestamp = now;
  4807. const curBytes = r.bytes || 0;
  4808. const curPackets = r.packets || 0;
  4809. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  4810. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  4811. state.natLastBytes = curBytes;
  4812. state.natLastPackets = curPackets;
  4813. const rateBps = Math.round((deltaBytes * 8) / dt);
  4814. const ratePkt = Math.round(deltaPkts / dt);
  4815. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4816. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4817. state.natStatRateHistory.push(rateBps);
  4818. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4819. state.natStatPktHistory.push(ratePkt);
  4820. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4821. const bEl = document.getElementById('nat-stat-bytes');
  4822. const pEl = document.getElementById('nat-stat-packets');
  4823. const rEl = document.getElementById('nat-stat-rate');
  4824. const prEl = document.getElementById('nat-stat-pktrate');
  4825. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4826. if (pEl) pEl.value = curPackets.toLocaleString();
  4827. if (rEl) rEl.value = formatBps(rateBps);
  4828. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4829. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4830. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4831. } catch (e) {
  4832. console.error('Error polling NAT rule stats', e);
  4833. }
  4834. }
  4835. async function moveNATRule(id, dir) {
  4836. id = decodeURIComponent(id);
  4837. try {
  4838. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4839. method: 'POST',
  4840. headers: { 'Content-Type': 'application/json' },
  4841. body: JSON.stringify({ direction: dir })
  4842. });
  4843. if (res.ok) loadFirewall(false);
  4844. } catch (err) {
  4845. showToast('Error', err.message, 'error');
  4846. }
  4847. }
  4848. async function toggleNATRuleState(id, disabled) {
  4849. id = decodeURIComponent(id);
  4850. try {
  4851. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4852. method: 'POST',
  4853. headers: { 'Content-Type': 'application/json' },
  4854. body: JSON.stringify({ disabled })
  4855. });
  4856. if (res.ok) loadFirewall(false);
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. async function deleteNATRule(id) {
  4862. id = decodeURIComponent(id);
  4863. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4864. try {
  4865. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4866. if (res.ok) {
  4867. showToast('Deleted', 'NAT rule removed', 'success');
  4868. loadFirewall(false);
  4869. }
  4870. } catch (err) {
  4871. showToast('Error', err.message, 'error');
  4872. }
  4873. }
  4874. // ----------------- Mangle Rules -----------------
  4875. function renderMangleRules() {
  4876. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4877. const tbody = document.getElementById('mangle-table-body');
  4878. const empty = document.getElementById('mangle-empty');
  4879. if (!tbody) return;
  4880. tbody.innerHTML = '';
  4881. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4882. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4883. if (rules.length === 0) {
  4884. empty?.classList.remove('hidden');
  4885. return;
  4886. }
  4887. empty?.classList.add('hidden');
  4888. rules.forEach((raw, idx) => {
  4889. const r = safeFirewallRow(raw);
  4890. const tr = document.createElement('tr');
  4891. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4892. let markVal = '<span class="text-slate-500">-</span>';
  4893. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4894. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4895. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4896. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4897. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4898. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4899. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4900. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4901. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4902. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4903. 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>`;
  4904. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4905. tr.innerHTML = `
  4906. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4907. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4908. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4909. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4910. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4911. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4912. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4913. <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>
  4914. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4915. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4916. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4917. </td>
  4918. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4919. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4920. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4921. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4922. <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>
  4923. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4924. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4925. </td>
  4926. `;
  4927. tbody.appendChild(tr);
  4928. });
  4929. }
  4930. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4931. function switchMangleRuleTab(tab) {
  4932. state.activeMangleRuleTab = tab;
  4933. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4934. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4935. btn.classList.add('text-slate-400', 'border-transparent');
  4936. });
  4937. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4938. if (activeBtn) {
  4939. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4940. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4941. }
  4942. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4943. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4944. if (activePane) activePane.classList.remove('hidden');
  4945. if (tab === 'statistics') {
  4946. startMangleStatPolling();
  4947. } else {
  4948. stopMangleStatPolling();
  4949. }
  4950. }
  4951. function toggleMangleField(fieldKey, expand) {
  4952. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4953. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4954. if (!plusBtn || !fieldBox) return;
  4955. if (expand) {
  4956. plusBtn.classList.add('hidden');
  4957. fieldBox.classList.remove('hidden');
  4958. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4959. if (valInput) valInput.focus();
  4960. } else {
  4961. fieldBox.classList.add('hidden');
  4962. plusBtn.classList.remove('hidden');
  4963. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4964. if (valInput) {
  4965. if (valInput.tagName === 'SELECT') {
  4966. valInput.selectedIndex = 0;
  4967. } else {
  4968. valInput.value = '';
  4969. }
  4970. }
  4971. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4972. if (invInput) invInput.checked = false;
  4973. if (fieldKey === 'cs') {
  4974. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4975. const el = document.getElementById(id);
  4976. if (el) el.checked = false;
  4977. });
  4978. }
  4979. if (fieldKey === 'natstate') {
  4980. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4981. const el = document.getElementById(id);
  4982. if (el) el.checked = false;
  4983. });
  4984. }
  4985. }
  4986. }
  4987. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4988. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4989. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4990. toggleMangleField(fieldKey, true);
  4991. let strVal = String(value);
  4992. if (hasInvert) {
  4993. const inv = strVal.startsWith('!');
  4994. if (inv) strVal = strVal.slice(1);
  4995. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4996. if (invEl) invEl.checked = inv;
  4997. else if (inv) strVal = '!'+strVal;
  4998. }
  4999. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5000. 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; }
  5001. } else {
  5002. toggleMangleField(fieldKey, false);
  5003. }
  5004. }
  5005. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5006. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5007. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5008. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5009. let v = valEl ? valEl.value.trim() : '';
  5010. if (!v) return '';
  5011. if (hasInvert) {
  5012. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5013. if (invEl && invEl.checked) {
  5014. v = '!' + v.replace(/^!/, '');
  5015. }
  5016. }
  5017. return v;
  5018. }
  5019. function toggleMaximizeMangleModal() {
  5020. const win = document.getElementById('mangle-modal-window');
  5021. if (!win) return;
  5022. if (win.classList.contains('max-w-[720px]')) {
  5023. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5024. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5025. } else {
  5026. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5027. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5028. }
  5029. }
  5030. function toggleMangleActionFields() {
  5031. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5032. // Hide all dynamic rows first
  5033. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5034. const el = document.getElementById(`mangle-row-${id}`);
  5035. if (el) el.classList.add('hidden');
  5036. });
  5037. const jumpBox = document.getElementById('mangle-action-jump-box');
  5038. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5039. if (jumpBox) jumpBox.classList.add('hidden');
  5040. if (addrBox) addrBox.classList.add('hidden');
  5041. // Activate matching rows
  5042. if (act === 'mark-connection') {
  5043. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5044. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5045. } else if (act === 'mark-routing') {
  5046. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5047. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5048. } else if (act === 'mark-packet') {
  5049. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5050. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5051. } else if (act === 'change-mss') {
  5052. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5053. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5054. } else if (act === 'change-dscp') {
  5055. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5056. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5057. } else if (act === 'change-ttl') {
  5058. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5059. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5060. } else if (act === 'set-priority') {
  5061. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5062. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5063. } else if (act === 'route') {
  5064. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5065. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5066. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5067. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5068. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5069. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5070. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5071. } else if (act === 'jump') {
  5072. if (jumpBox) jumpBox.classList.remove('hidden');
  5073. } else if (act.includes('address-list') || act.includes('address list')) {
  5074. if (addrBox) addrBox.classList.remove('hidden');
  5075. }
  5076. if (act === 'log') {
  5077. const logEl = document.getElementById('mangle-modal-log');
  5078. if (logEl) logEl.checked = true;
  5079. toggleMangleField('logprefix', true);
  5080. }
  5081. }
  5082. function toggleMangleLogPrefix() {
  5083. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5084. toggleMangleField('logprefix', !!isLog);
  5085. }
  5086. const allMangleFieldKeys = [
  5087. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5088. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5089. 'routingmark', 'conntype', 'cs', 'natstate',
  5090. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5091. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5092. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5093. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5094. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5095. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5096. ];
  5097. function openAddMangleModal() {
  5098. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5099. switchMangleRuleTab('general');
  5100. const badge = document.getElementById('mangle-modal-badge');
  5101. if (badge) badge.innerText = 'New...';
  5102. document.getElementById('mangle-modal-id').value = '';
  5103. document.getElementById('mangle-modal-family').value = '4';
  5104. document.getElementById('mangle-modal-enabled').checked = true;
  5105. document.getElementById('mangle-modal-comment').value = '';
  5106. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5107. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5108. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5109. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5110. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5111. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5112. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5113. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5114. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5115. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5116. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5117. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5118. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5119. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5120. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5121. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5122. populateInterfaceSelect('mangle-val-iniface');
  5123. populateInterfaceSelect('mangle-val-outiface');
  5124. populateAddressListSelect('mangle-val-srclist');
  5125. populateAddressListSelect('mangle-val-dstlist');
  5126. populateGeoIPSelect('mangle-val-srcgeo');
  5127. populateGeoIPSelect('mangle-val-dstgeo');
  5128. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5129. resetMangleCounterDisplay();
  5130. toggleMangleActionFields();
  5131. document.getElementById('mangle-modal').classList.remove('hidden');
  5132. }
  5133. function openEditMangleModal(id) {
  5134. id = decodeURIComponent(id);
  5135. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5136. if (!r) return;
  5137. switchMangleRuleTab('general');
  5138. const badge = document.getElementById('mangle-modal-badge');
  5139. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5140. document.getElementById('mangle-modal-id').value = r.id;
  5141. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5142. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5143. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5144. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5145. setFirewallActionSelection('mangle', r.action || 'accept');
  5146. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5147. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5148. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5149. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5150. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5151. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5152. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5153. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5154. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5155. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5156. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5157. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5158. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5159. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5160. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5161. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5162. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5163. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5164. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5165. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5166. setMangleFieldVal('src', r.src_address, true);
  5167. setMangleFieldVal('dst', r.dst_address, true);
  5168. setMangleFieldVal('srclist', r.src_address_list, true);
  5169. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5170. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5171. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5172. if (r.protocol && r.protocol !== 'all') {
  5173. setMangleFieldVal('proto', r.protocol, true);
  5174. } else {
  5175. toggleMangleField('proto', false);
  5176. }
  5177. setMangleFieldVal('sport', r.src_port, true);
  5178. setMangleFieldVal('dport', r.dst_port, true);
  5179. setMangleFieldVal('anyport', r.any_port, true);
  5180. setMangleFieldVal('iniface', r.in_interface, true);
  5181. setMangleFieldVal('outiface', r.out_interface, true);
  5182. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5183. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5184. setMangleFieldVal('pktmark', r.packet_mark, true);
  5185. setMangleFieldVal('connmark', r.connection_mark, true);
  5186. setMangleFieldVal('routingmark', r.routing_mark, true);
  5187. setMangleFieldVal('conntype', r.connection_type, false);
  5188. // Connection State
  5189. const states = r.connection_state || [];
  5190. if (states.length > 0) {
  5191. toggleMangleField('cs', true);
  5192. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5193. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5194. if (el) el.checked = states.includes(s);
  5195. });
  5196. } else {
  5197. toggleMangleField('cs', false);
  5198. }
  5199. // Connection NAT State
  5200. const natStates = r.connection_nat_state || [];
  5201. if (natStates.length > 0) {
  5202. toggleMangleField('natstate', true);
  5203. ['srcnat', 'dstnat'].forEach(s => {
  5204. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5205. if (el) el.checked = natStates.includes(s);
  5206. });
  5207. } else {
  5208. toggleMangleField('natstate', false);
  5209. }
  5210. // Advanced tab fields
  5211. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5212. setMangleFieldVal('content', r.content, false);
  5213. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5214. setMangleFieldVal('connrate', r.connection_rate, false);
  5215. setMangleFieldVal('pcc', r.pcc, false);
  5216. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5217. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5218. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5219. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5220. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5221. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5222. setMangleFieldVal('tlshost', r.tls_host, false);
  5223. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5224. setMangleFieldVal('priority', r.priority, false);
  5225. setMangleFieldVal('dscp', r.dscp, false);
  5226. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5227. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5228. setMangleFieldVal('pktsize', r.packet_size, false);
  5229. setMangleFieldVal('random', r.random, false);
  5230. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5231. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5232. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5233. setMangleFieldVal('ttl', r.ttl, false);
  5234. // Extra tab fields
  5235. setMangleFieldVal('nth', r.nth, false);
  5236. setMangleFieldVal('connlimit', r.connection_limit, false);
  5237. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5238. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5239. setMangleFieldVal('hotspot', r.hotspot, false);
  5240. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5241. setMangleFieldVal('limit', r.limit, false);
  5242. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5243. setMangleFieldVal('time', r.time, false);
  5244. setMangleFieldVal('psd', r.psd, false);
  5245. // Action fields
  5246. if (r.jump_target) {
  5247. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5248. if (jtEl) jtEl.value = r.jump_target;
  5249. }
  5250. if (r.address_list) {
  5251. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5252. if (alEl) alEl.value = r.address_list;
  5253. }
  5254. if (r.address_list_timeout) {
  5255. const toEl = document.getElementById('mangle-modal-action-timeout');
  5256. if (toEl) toEl.value = r.address_list_timeout;
  5257. }
  5258. setMangleFieldVal('logprefix', r.log_prefix, false);
  5259. // Statistics
  5260. const bEl = document.getElementById('mangle-stat-bytes');
  5261. const pEl = document.getElementById('mangle-stat-packets');
  5262. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5263. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5264. state.mangleLastBytes = r.bytes || 0;
  5265. state.mangleLastPackets = r.packets || 0;
  5266. state.mangleLastTimestamp = Date.now();
  5267. state.mangleStatRateHistory = new Array(30).fill(0);
  5268. state.mangleStatPktHistory = new Array(30).fill(0);
  5269. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5270. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5271. toggleMangleActionFields();
  5272. document.getElementById('mangle-modal').classList.remove('hidden');
  5273. }
  5274. function closeMangleModal() {
  5275. stopMangleStatPolling();
  5276. document.getElementById('mangle-modal').classList.add('hidden');
  5277. }
  5278. function copyMangleRule() {
  5279. document.getElementById('mangle-modal-id').value = '';
  5280. const badge = document.getElementById('mangle-modal-badge');
  5281. if (badge) badge.innerText = 'New...';
  5282. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5283. }
  5284. function resetMangleCounterDisplay() {
  5285. state.mangleStatRateHistory = new Array(30).fill(0);
  5286. state.mangleStatPktHistory = new Array(30).fill(0);
  5287. state.mangleLastBytes = 0;
  5288. state.mangleLastPackets = 0;
  5289. state.mangleLastTimestamp = Date.now();
  5290. const bEl = document.getElementById('mangle-stat-bytes');
  5291. const pEl = document.getElementById('mangle-stat-packets');
  5292. const rEl = document.getElementById('mangle-stat-rate');
  5293. const prEl = document.getElementById('mangle-stat-pktrate');
  5294. if (bEl) bEl.value = '0 B';
  5295. if (pEl) pEl.value = '0';
  5296. if (rEl) rEl.value = '0 bps';
  5297. if (prEl) prEl.value = '0 p/s';
  5298. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5299. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5300. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5301. }
  5302. async function applyMangleRule(closeAfter = false) {
  5303. const id = document.getElementById('mangle-modal-id').value;
  5304. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5305. const chain = document.getElementById('mangle-modal-chain').value;
  5306. const action = document.getElementById('mangle-modal-action').value;
  5307. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5308. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5309. const src = getMangleFieldVal('src', true);
  5310. const dst = getMangleFieldVal('dst', true);
  5311. const srclist = getMangleFieldVal('srclist', true);
  5312. const dstlist = getMangleFieldVal('dstlist', true);
  5313. const srcgeo = getMangleFieldVal('srcgeo', true);
  5314. const dstgeo = getMangleFieldVal('dstgeo', true);
  5315. const proto = getMangleFieldVal('proto', true);
  5316. const sport = getMangleFieldVal('sport', true);
  5317. const dport = getMangleFieldVal('dport', true);
  5318. const anyport = getMangleFieldVal('anyport', true);
  5319. const iniface = getMangleFieldVal('iniface', true);
  5320. const outiface = getMangleFieldVal('outiface', true);
  5321. const inifacelist = getMangleFieldVal('inifacelist', true);
  5322. const outifacelist = getMangleFieldVal('outifacelist', true);
  5323. const pktmark = getMangleFieldVal('pktmark', true);
  5324. const connmark = getMangleFieldVal('connmark', true);
  5325. const routingmark = getMangleFieldVal('routingmark', true);
  5326. const conntype = getMangleFieldVal('conntype', false);
  5327. const states = [];
  5328. const csBox = document.getElementById('mangle-field-cs');
  5329. if (csBox && !csBox.classList.contains('hidden')) {
  5330. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5331. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5332. });
  5333. }
  5334. const natStates = [];
  5335. const natBox = document.getElementById('mangle-field-natstate');
  5336. if (natBox && !natBox.classList.contains('hidden')) {
  5337. ['srcnat', 'dstnat'].forEach(s => {
  5338. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5339. });
  5340. }
  5341. const payload = {
  5342. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5343. id,
  5344. chain,
  5345. action,
  5346. protocol: proto || 'all',
  5347. src_address: src,
  5348. dst_address: dst,
  5349. src_port: sport,
  5350. dst_port: dport,
  5351. any_port: anyport,
  5352. in_interface: iniface,
  5353. out_interface: outiface,
  5354. in_interface_list: inifacelist,
  5355. out_interface_list: outifacelist,
  5356. packet_mark: pktmark,
  5357. connection_mark: connmark,
  5358. routing_mark: routingmark,
  5359. connection_type: conntype,
  5360. connection_state: states,
  5361. connection_nat_state: natStates,
  5362. src_address_list: srclist,
  5363. dst_address_list: dstlist,
  5364. src_geoip: srcgeo,
  5365. dst_geoip: dstgeo,
  5366. comment,
  5367. disabled: !enabled,
  5368. // Advanced tab
  5369. content: getMangleFieldVal('content', false),
  5370. src_mac_address: getMangleFieldVal('srcmac', true),
  5371. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5372. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5373. ipsec_policy: getMangleFieldVal('ipsec', false),
  5374. dscp: getMangleFieldVal('dscp', false),
  5375. tcp_mss: getMangleFieldVal('tcpmss', false),
  5376. tos: document.getElementById('mangle-val-tos')?.value || '',
  5377. packet_size: getMangleFieldVal('pktsize', false),
  5378. random: getMangleFieldVal('random', false),
  5379. tcp_flags: getMangleFieldVal('tcpflags', false),
  5380. icmp_options: getMangleFieldVal('icmpoptions', false),
  5381. ttl: getMangleFieldVal('ttl', false),
  5382. // Extra tab
  5383. nth: getMangleFieldVal('nth', false),
  5384. connection_limit: getMangleFieldVal('connlimit', false),
  5385. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5386. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5387. ip_fragment: getMangleFieldVal('ipfragment', false),
  5388. limit: getMangleFieldVal('limit', false),
  5389. time: getMangleFieldVal('time', false),
  5390. // Action tab
  5391. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5392. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5393. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5394. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5395. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5396. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5397. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5398. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5399. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5400. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5401. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5402. log: document.getElementById('mangle-modal-log')?.checked || false,
  5403. log_prefix: getMangleFieldVal('logprefix', false)
  5404. };
  5405. try {
  5406. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5407. method: 'POST',
  5408. headers: { 'Content-Type': 'application/json' },
  5409. body: JSON.stringify(payload)
  5410. });
  5411. if (res.ok) {
  5412. const data = await res.json();
  5413. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5414. loadFirewall(false);
  5415. if (closeAfter) {
  5416. closeMangleModal();
  5417. } else {
  5418. if (data.id) {
  5419. document.getElementById('mangle-modal-id').value = data.id;
  5420. const badge = document.getElementById('mangle-modal-badge');
  5421. if (badge) badge.innerText = `#${data.id}`;
  5422. }
  5423. }
  5424. } else {
  5425. const err = await res.json();
  5426. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5427. }
  5428. } catch (err) {
  5429. showToast('Error', err.message, 'error');
  5430. }
  5431. }
  5432. function submitSaveMangleRule(e) {
  5433. if (e && e.preventDefault) e.preventDefault();
  5434. return applyMangleRule(true);
  5435. }
  5436. function startMangleStatPolling() {
  5437. stopMangleStatPolling();
  5438. pollMangleRuleStats();
  5439. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5440. }
  5441. function stopMangleStatPolling() {
  5442. if (state.mangleStatInterval) {
  5443. clearInterval(state.mangleStatInterval);
  5444. state.mangleStatInterval = null;
  5445. }
  5446. }
  5447. async function pollMangleRuleStats() {
  5448. const id = document.getElementById('mangle-modal-id')?.value;
  5449. if (!id) {
  5450. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5451. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5452. return;
  5453. }
  5454. try {
  5455. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5456. if (!res.ok) return;
  5457. const rules = await res.json();
  5458. const r = rules.find(x => x.id === id);
  5459. if (!r) return;
  5460. const now = Date.now();
  5461. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5462. state.mangleLastTimestamp = now;
  5463. const curBytes = r.bytes || 0;
  5464. const curPackets = r.packets || 0;
  5465. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5466. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5467. state.mangleLastBytes = curBytes;
  5468. state.mangleLastPackets = curPackets;
  5469. const rateBps = Math.round((deltaBytes * 8) / dt);
  5470. const ratePkt = Math.round(deltaPkts / dt);
  5471. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5472. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5473. state.mangleStatRateHistory.push(rateBps);
  5474. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5475. state.mangleStatPktHistory.push(ratePkt);
  5476. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5477. const bEl = document.getElementById('mangle-stat-bytes');
  5478. const pEl = document.getElementById('mangle-stat-packets');
  5479. const rEl = document.getElementById('mangle-stat-rate');
  5480. const prEl = document.getElementById('mangle-stat-pktrate');
  5481. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5482. if (pEl) pEl.value = curPackets.toLocaleString();
  5483. if (rEl) rEl.value = formatBps(rateBps);
  5484. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5485. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5486. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5487. } catch (e) {
  5488. console.error('Error polling Mangle rule stats', e);
  5489. }
  5490. }
  5491. async function moveMangleRule(id, dir) {
  5492. id = decodeURIComponent(id);
  5493. try {
  5494. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5495. method: 'POST',
  5496. headers: { 'Content-Type': 'application/json' },
  5497. body: JSON.stringify({ direction: dir })
  5498. });
  5499. if (res.ok) loadFirewall(false);
  5500. } catch (err) {
  5501. showToast('Error', err.message, 'error');
  5502. }
  5503. }
  5504. async function toggleMangleRuleState(id, disabled) {
  5505. id = decodeURIComponent(id);
  5506. try {
  5507. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5508. method: 'POST',
  5509. headers: { 'Content-Type': 'application/json' },
  5510. body: JSON.stringify({ disabled })
  5511. });
  5512. if (res.ok) loadFirewall(false);
  5513. } catch (err) {
  5514. showToast('Error', err.message, 'error');
  5515. }
  5516. }
  5517. async function deleteMangleRule(id) {
  5518. id = decodeURIComponent(id);
  5519. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5520. try {
  5521. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5522. if (res.ok) {
  5523. showToast('Deleted', 'Mangle rule removed', 'success');
  5524. loadFirewall(false);
  5525. }
  5526. } catch (err) {
  5527. showToast('Error', err.message, 'error');
  5528. }
  5529. }
  5530. // ----------------- Address Lists -----------------
  5531. function renderAddressLists() {
  5532. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5533. const tbody = document.getElementById('addrlist-table-body');
  5534. const empty = document.getElementById('addrlist-empty');
  5535. if (!tbody) return;
  5536. tbody.innerHTML = '';
  5537. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5538. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  5539. // Update filter select
  5540. const sel = document.getElementById('addrlist-filter-name');
  5541. if (sel) {
  5542. const cur = sel.value;
  5543. sel.innerHTML = '<option value="">All Lists</option>';
  5544. const set = new Set((state.addressLists || []).map(a => a.name));
  5545. set.forEach(n => {
  5546. const opt = document.createElement('option');
  5547. opt.value = n;
  5548. opt.innerText = n;
  5549. if (n === cur) opt.selected = true;
  5550. sel.appendChild(opt);
  5551. });
  5552. }
  5553. if (entries.length === 0) {
  5554. empty?.classList.remove('hidden');
  5555. return;
  5556. }
  5557. empty?.classList.add('hidden');
  5558. entries.forEach((raw, idx) => {
  5559. const e = safeFirewallRow(raw);
  5560. const tr = document.createElement('tr');
  5561. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5562. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5563. tr.innerHTML = `
  5564. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5565. <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>
  5566. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5567. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5568. <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>
  5569. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5570. ${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>
  5571. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5572. `}
  5573. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5574. </td>
  5575. `;
  5576. tbody.appendChild(tr);
  5577. });
  5578. populateCommonAddrListDatalist();
  5579. }
  5580. function openAddAddrListModal() {
  5581. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5582. document.getElementById('addrlist-modal-id').value = '';
  5583. document.getElementById('addrlist-modal-name').value = '';
  5584. document.getElementById('addrlist-modal-addr').value = '';
  5585. document.getElementById('addrlist-modal-comment').value = '';
  5586. document.getElementById('addrlist-modal-disabled').checked = false;
  5587. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5588. if (submitBtn) submitBtn.innerText = 'Add to List';
  5589. document.getElementById('addrlist-modal').classList.remove('hidden');
  5590. }
  5591. function openEditAddrListModal(id) {
  5592. id = decodeURIComponent(id);
  5593. const e = (state.addressLists || []).find(item => item.id === id);
  5594. if (!e) return;
  5595. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5596. document.getElementById('addrlist-modal-id').value = e.id;
  5597. document.getElementById('addrlist-modal-name').value = e.name;
  5598. document.getElementById('addrlist-modal-addr').value = e.address;
  5599. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5600. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5601. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5602. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5603. document.getElementById('addrlist-modal').classList.remove('hidden');
  5604. }
  5605. function closeAddrListModal() {
  5606. document.getElementById('addrlist-modal').classList.add('hidden');
  5607. }
  5608. async function submitSaveAddrList(e) {
  5609. e.preventDefault();
  5610. const id = document.getElementById('addrlist-modal-id').value;
  5611. const name = document.getElementById('addrlist-modal-name').value.trim();
  5612. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5613. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5614. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5615. try {
  5616. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5617. method: 'POST',
  5618. headers: { 'Content-Type': 'application/json' },
  5619. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5620. });
  5621. if (res.ok) {
  5622. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5623. closeAddrListModal();
  5624. loadFirewall(false);
  5625. } else {
  5626. const err = await res.json();
  5627. showToast('Error', err.message || 'Failed to save address list', 'error');
  5628. }
  5629. } catch (err) {
  5630. showToast('Error', err.message, 'error');
  5631. }
  5632. }
  5633. async function toggleAddrListState(id, disabled) {
  5634. id = decodeURIComponent(id);
  5635. try {
  5636. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5637. method: 'POST',
  5638. headers: { 'Content-Type': 'application/json' },
  5639. body: JSON.stringify({ disabled })
  5640. });
  5641. if (res.ok) {
  5642. loadFirewall(false);
  5643. }
  5644. } catch (err) {
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. }
  5648. async function deleteAddrList(id) {
  5649. id = decodeURIComponent(id);
  5650. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5651. try {
  5652. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5653. if (res.ok) {
  5654. showToast('Deleted', 'Address list item removed', 'info');
  5655. loadFirewall(false);
  5656. }
  5657. } catch (err) {
  5658. showToast('Error', err.message, 'error');
  5659. }
  5660. }
  5661. // ----------------- Geo-Location IP Management -----------------
  5662. async function loadGeoIP() {
  5663. try {
  5664. const [statusRes, countriesRes] = await Promise.all([
  5665. fetch(`${API_BASE}/firewall/geoip/status`),
  5666. fetch(`${API_BASE}/firewall/geoip/countries`)
  5667. ]);
  5668. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5669. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5670. updateGeoHeader();
  5671. renderGeoCountries();
  5672. } catch (err) {
  5673. console.error('Failed to load GeoIP:', err);
  5674. }
  5675. }
  5676. function getGeoUsageMap() {
  5677. const usage = {};
  5678. const checkRule = (r, type) => {
  5679. ['src_geoip', 'dst_geoip'].forEach(field => {
  5680. let val = (r && r[field]) || '';
  5681. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5682. if (code) {
  5683. if (!usage[code]) usage[code] = [];
  5684. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5685. if (!usage[code].includes(label)) usage[code].push(label);
  5686. }
  5687. });
  5688. };
  5689. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5690. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5691. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5692. return usage;
  5693. }
  5694. function updateGeoHeader() {
  5695. const s = state.geoStatus || {};
  5696. const statusBadge = document.getElementById('geo-status-badge');
  5697. if (statusBadge) {
  5698. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5699. statusBadge.className = s.auto_update
  5700. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5701. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5702. }
  5703. const intervalLabel = document.getElementById('geo-interval-label');
  5704. if (intervalLabel) {
  5705. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5706. }
  5707. const usageMap = getGeoUsageMap();
  5708. const inUseCount = Object.keys(usageMap).length;
  5709. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5710. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5711. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5712. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5713. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5714. if (lastSyncEl) {
  5715. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5716. const d = new Date(s.last_updated);
  5717. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5718. } else {
  5719. lastSyncEl.innerText = 'Never (Sync Pending)';
  5720. }
  5721. }
  5722. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5723. if (nextSyncEl) {
  5724. if (s.next_update && !s.next_update.startsWith('0001')) {
  5725. const d = new Date(s.next_update);
  5726. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5727. } else {
  5728. nextSyncEl.innerText = '-';
  5729. }
  5730. }
  5731. const badge = document.getElementById('fw-badge-geo');
  5732. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5733. }
  5734. function renderGeoCountries() {
  5735. const tbody = document.getElementById('geo-table-body');
  5736. const empty = document.getElementById('geo-empty');
  5737. if (!tbody) return;
  5738. tbody.innerHTML = '';
  5739. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5740. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5741. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5742. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5743. const usageMap = getGeoUsageMap();
  5744. const countries = (state.geoCountries || []).filter(c => {
  5745. const isUsed = !!usageMap[c.code];
  5746. if (inUseOnly && !isUsed) return false;
  5747. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5748. if (continent && c.continent !== continent) return false;
  5749. if (q) {
  5750. const matchCode = c.code.toLowerCase().includes(q);
  5751. const matchName = c.name.toLowerCase().includes(q);
  5752. if (!matchCode && !matchName) return false;
  5753. }
  5754. return true;
  5755. });
  5756. if (countries.length === 0) {
  5757. empty?.classList.remove('hidden');
  5758. return;
  5759. }
  5760. empty?.classList.add('hidden');
  5761. countries.forEach(c => {
  5762. const tr = document.createElement('tr');
  5763. const isUsed = !!usageMap[c.code];
  5764. const rulesUsing = usageMap[c.code] || [];
  5765. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5766. let statusHtml = '';
  5767. if (isUsed) {
  5768. 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>`;
  5769. } else if (c.subnet_count > 0) {
  5770. 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>';
  5771. } else {
  5772. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5773. }
  5774. tr.innerHTML = `
  5775. <td class="py-2.5 px-3 text-center">
  5776. <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'}">
  5777. ${c.code}
  5778. </span>
  5779. </td>
  5780. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5781. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5782. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5783. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5784. </td>
  5785. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5786. <td class="py-2.5 px-3">
  5787. ${statusHtml}
  5788. </td>
  5789. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5790. <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>
  5791. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5792. </td>
  5793. `;
  5794. tbody.appendChild(tr);
  5795. });
  5796. }
  5797. function quickFilterGeo(preset) {
  5798. const searchInput = document.getElementById('geo-search-input');
  5799. const continentSel = document.getElementById('geo-continent-filter');
  5800. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5801. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5802. if (searchInput) searchInput.value = '';
  5803. if (continentSel) continentSel.value = '';
  5804. if (inUseCheck) inUseCheck.checked = false;
  5805. if (cachedCheck) cachedCheck.checked = false;
  5806. if (preset === 'GR') {
  5807. if (searchInput) searchInput.value = 'Greece';
  5808. } else if (preset === 'Europe') {
  5809. if (continentSel) continentSel.value = 'Europe';
  5810. } else if (preset === 'HIGHRISK') {
  5811. if (searchInput) searchInput.value = 'China';
  5812. }
  5813. renderGeoCountries();
  5814. }
  5815. async function toggleGeoCountry(code, enabled) {
  5816. try {
  5817. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5818. method: 'POST',
  5819. headers: { 'Content-Type': 'application/json' },
  5820. body: JSON.stringify({ enabled })
  5821. });
  5822. if (res.ok) {
  5823. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5824. loadGeoIP();
  5825. } else {
  5826. const err = await res.json();
  5827. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5828. }
  5829. } catch (err) {
  5830. showToast('Error', err.message, 'error');
  5831. }
  5832. }
  5833. async function updateGeoCountry(code) {
  5834. try {
  5835. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5836. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5837. if (res.ok) {
  5838. const data = await res.json();
  5839. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5840. loadGeoIP();
  5841. } else {
  5842. const err = await res.json();
  5843. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5844. }
  5845. } catch (err) {
  5846. showToast('Error', err.message, 'error');
  5847. }
  5848. }
  5849. async function triggerGeoUpdateNow() {
  5850. const spinner = document.getElementById('geo-update-spinner');
  5851. if (spinner) spinner.classList.remove('hidden');
  5852. try {
  5853. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5854. if (res.ok) {
  5855. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5856. setTimeout(() => {
  5857. loadGeoIP();
  5858. if (spinner) spinner.classList.add('hidden');
  5859. }, 2500);
  5860. } else {
  5861. const err = await res.json();
  5862. showToast('Notice', err.message || 'Update in progress', 'info');
  5863. if (spinner) spinner.classList.add('hidden');
  5864. }
  5865. } catch (err) {
  5866. showToast('Error', err.message, 'error');
  5867. if (spinner) spinner.classList.add('hidden');
  5868. }
  5869. }
  5870. async function applyGeoPreset(preset) {
  5871. try {
  5872. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5873. method: 'POST',
  5874. headers: { 'Content-Type': 'application/json' },
  5875. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5876. });
  5877. if (res.ok) {
  5878. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5879. loadGeoIP();
  5880. }
  5881. } catch (err) {
  5882. showToast('Error', err.message, 'error');
  5883. }
  5884. }
  5885. function openGeoIntervalModal() {
  5886. const s = state.geoStatus || {};
  5887. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5888. const sel = document.getElementById('geo-cfg-interval');
  5889. const customBox = document.getElementById('geo-cfg-custom-box');
  5890. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5891. const curHours = s.interval_hours || 24;
  5892. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5893. if (matchOption) {
  5894. sel.value = String(curHours);
  5895. customBox.classList.add('hidden');
  5896. } else {
  5897. sel.value = 'custom';
  5898. customHoursInput.value = curHours;
  5899. customBox.classList.remove('hidden');
  5900. }
  5901. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5902. }
  5903. function closeGeoIntervalModal() {
  5904. document.getElementById('geo-interval-modal').classList.add('hidden');
  5905. }
  5906. function toggleCustomGeoInterval() {
  5907. const val = document.getElementById('geo-cfg-interval').value;
  5908. const customBox = document.getElementById('geo-cfg-custom-box');
  5909. if (val === 'custom') {
  5910. customBox.classList.remove('hidden');
  5911. } else {
  5912. customBox.classList.add('hidden');
  5913. }
  5914. }
  5915. async function submitGeoIntervalSettings(e) {
  5916. e.preventDefault();
  5917. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5918. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5919. let hours = 24;
  5920. if (intervalVal === 'custom') {
  5921. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5922. } else {
  5923. hours = parseInt(intervalVal, 10) || 24;
  5924. }
  5925. try {
  5926. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5927. method: 'POST',
  5928. headers: { 'Content-Type': 'application/json' },
  5929. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5930. });
  5931. if (res.ok) {
  5932. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5933. closeGeoIntervalModal();
  5934. loadGeoIP();
  5935. } else {
  5936. const err = await res.json();
  5937. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5938. }
  5939. } catch (err) {
  5940. showToast('Error', err.message, 'error');
  5941. }
  5942. }
  5943. async function viewGeoSubnets(code, name) {
  5944. if (!name) {
  5945. const found = (state.geoCountries || []).find(x => x.code === code);
  5946. name = found ? found.name : code;
  5947. }
  5948. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5949. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5950. const listEl = document.getElementById('geo-subnets-list');
  5951. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5952. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5953. try {
  5954. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5955. if (res.ok) {
  5956. const data = await res.json();
  5957. const subnets = data.subnets || [];
  5958. if (subnets.length === 0) {
  5959. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5960. } else {
  5961. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5962. }
  5963. } else {
  5964. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5965. }
  5966. } catch (err) {
  5967. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5968. }
  5969. }
  5970. function closeGeoSubnetsModal() {
  5971. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5972. }
  5973. // ----------------- Active Connections Tracking -----------------
  5974. async function loadConnections() {
  5975. try {
  5976. const res = await fetch(`${API_BASE}/firewall/connections`);
  5977. const data = await res.json();
  5978. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  5979. state.connections = Array.isArray(data) ? data : [];
  5980. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5981. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5982. renderConnections();
  5983. } catch (err) {
  5984. console.error('Failed to load connections:', err);
  5985. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  5986. }
  5987. }
  5988. function renderConnections() {
  5989. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5990. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5991. const tbody = document.getElementById('conns-table-body');
  5992. const empty = document.getElementById('conns-empty');
  5993. if (!tbody) return;
  5994. tbody.innerHTML = '';
  5995. const conns = (state.connections || []).filter(c => {
  5996. if (protoFilter && c.protocol !== protoFilter) return false;
  5997. if (search) {
  5998. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5999. if (!line.includes(search)) return false;
  6000. }
  6001. return true;
  6002. });
  6003. if (conns.length === 0) {
  6004. empty?.classList.remove('hidden');
  6005. return;
  6006. }
  6007. empty?.classList.add('hidden');
  6008. conns.slice(0, 150).forEach(c => {
  6009. const tr = document.createElement('tr');
  6010. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6011. let stateColor = 'text-slate-400';
  6012. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6013. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6014. tr.innerHTML = `
  6015. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6016. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6017. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6018. <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>
  6019. <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>
  6020. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6021. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6022. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6023. <td class="py-2.5 px-3 text-right font-sans">
  6024. ${['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>` : ''}
  6025. </td>
  6026. `;
  6027. tbody.appendChild(tr);
  6028. });
  6029. }
  6030. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6031. try {
  6032. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6033. method: 'POST',
  6034. headers: { 'Content-Type': 'application/json' },
  6035. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6036. });
  6037. if (res.ok) {
  6038. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6039. loadConnections();
  6040. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6041. } catch (err) {
  6042. showToast('Error', err.message, 'error');
  6043. }
  6044. }
  6045. async function resetFirewallCounters() {
  6046. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6047. try {
  6048. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6049. if (res.ok) {
  6050. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6051. loadFirewall(false);
  6052. }
  6053. } catch (err) {
  6054. showToast('Error', err.message, 'error');
  6055. }
  6056. }
  6057. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6058. function switchRoutesSubTab(tab) {
  6059. state.routesSubTab = tab;
  6060. const tabs = ['routes', 'rules', 'tables'];
  6061. tabs.forEach(t => {
  6062. const panel = document.getElementById(`routes-subtab-${t}`);
  6063. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6064. if (panel) {
  6065. if (t === tab) panel.classList.remove('hidden');
  6066. else panel.classList.add('hidden');
  6067. }
  6068. if (btn) {
  6069. if (t === tab) {
  6070. 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';
  6071. } else {
  6072. 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';
  6073. }
  6074. }
  6075. });
  6076. setTimeout(initTableSorting, 50);
  6077. }
  6078. async function loadRoutes() {
  6079. try {
  6080. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6081. fetch(`${API_BASE}/routes`),
  6082. fetch(`${API_BASE}/routing/rules`),
  6083. fetch(`${API_BASE}/routing/tables`)
  6084. ]);
  6085. if (routesRes.ok) state.routes = await routesRes.json();
  6086. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6087. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6088. const bRoutes = document.getElementById('routes-badge-routes');
  6089. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6090. const showSystem = document.getElementById('prule-show-system')?.checked;
  6091. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6092. const bRules = document.getElementById('routes-badge-rules');
  6093. if (bRules) bRules.innerText = userRules.length;
  6094. const bTables = document.getElementById('routes-badge-tables');
  6095. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6096. const bRoutesCount = document.getElementById('badge-routes-count');
  6097. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6098. renderRoutesList();
  6099. renderPolicyRules();
  6100. renderRoutingTables();
  6101. } catch (err) {
  6102. console.error('Failed to load routing:', err);
  6103. }
  6104. }
  6105. function getRouteProtocolBadge(proto) {
  6106. const p = (proto || 'static').toLowerCase();
  6107. switch (p) {
  6108. case 'bgp':
  6109. 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>`;
  6110. case 'ibgp':
  6111. 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>`;
  6112. case 'ospf':
  6113. 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>`;
  6114. case 'rip':
  6115. 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>`;
  6116. case 'static':
  6117. 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>`;
  6118. case 'connected':
  6119. 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>`;
  6120. case 'dhcp':
  6121. 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>`;
  6122. case 'multicast':
  6123. 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>`;
  6124. default:
  6125. 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>`;
  6126. }
  6127. }
  6128. function renderRoutesList() {
  6129. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6130. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6131. const tbody = document.getElementById('routes-table-body');
  6132. const empty = document.getElementById('routes-empty');
  6133. if (!tbody) return;
  6134. // Update table filter select
  6135. const sel = document.getElementById('routes-filter-table');
  6136. if (sel) {
  6137. const cur = sel.value;
  6138. sel.innerHTML = '<option value="">All Tables</option>';
  6139. (state.routingTables || []).forEach(t => {
  6140. const opt = document.createElement('option');
  6141. opt.value = t.name;
  6142. opt.innerText = t.name;
  6143. if (t.name === cur) opt.selected = true;
  6144. sel.appendChild(opt);
  6145. });
  6146. }
  6147. const routes = (state.routes || []).filter(r => {
  6148. if (tableFilter && r.routing_table !== tableFilter) return false;
  6149. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6150. if (typeFilter === 'multicast' && !r.multicast) return false;
  6151. if (typeFilter === 'static' && !r.static) return false;
  6152. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6153. if (typeFilter === 'connected' && !r.connect) return false;
  6154. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6155. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6156. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6157. return true;
  6158. });
  6159. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6160. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6161. let summaryText = `${routes.length} Routes`;
  6162. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6163. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6164. const badgeEl = document.getElementById('routes-count-badge');
  6165. if (badgeEl) badgeEl.innerText = summaryText;
  6166. if (routes.length === 0) {
  6167. empty?.classList.remove('hidden');
  6168. tbody.innerHTML = '';
  6169. return;
  6170. }
  6171. empty?.classList.add('hidden');
  6172. 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(';');
  6173. if (tbody.dataset.sig === sig) {
  6174. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6175. }
  6176. tbody.dataset.sig = sig;
  6177. tbody.innerHTML = '';
  6178. routes.forEach(r => {
  6179. const tr = document.createElement('tr');
  6180. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6181. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6182. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6183. let flags = '';
  6184. if (r.dynamic) flags += 'D';
  6185. if (r.active) flags += 'A';
  6186. if (r.connect) flags += 'C';
  6187. if (r.static) flags += 'S';
  6188. if (r.ecmp) flags += 'E';
  6189. if (r.multicast) flags += 'M';
  6190. if (r.disabled) flags += 'X';
  6191. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6192. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6193. if (r.check_gateway === 'internet') {
  6194. if (r.health_status === 'online') {
  6195. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6196. healthCell = `
  6197. <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)">
  6198. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6199. <span>Internet OK (${ms}ms)</span>
  6200. </span>
  6201. `;
  6202. } else if (r.health_status === 'offline') {
  6203. healthCell = `
  6204. <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.">
  6205. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6206. <span>Internet Down</span>
  6207. </span>
  6208. `;
  6209. } else {
  6210. healthCell = `
  6211. <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">
  6212. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6213. <span>Checking...</span>
  6214. </span>
  6215. `;
  6216. }
  6217. } else if (r.check_gateway === 'ping') {
  6218. if (r.health_status === 'online') {
  6219. healthCell = `
  6220. <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">
  6221. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6222. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6223. </span>
  6224. `;
  6225. } else if (r.health_status === 'offline') {
  6226. healthCell = `
  6227. <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">
  6228. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6229. <span>Gateway Dead</span>
  6230. </span>
  6231. `;
  6232. }
  6233. }
  6234. const flagDescriptions = [];
  6235. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6236. if (r.active) flagDescriptions.push('Active (A)');
  6237. if (r.connect) flagDescriptions.push('Connected (C)');
  6238. if (r.static) flagDescriptions.push('Static (S)');
  6239. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6240. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6241. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6242. tr.innerHTML = `
  6243. <td class="py-2.5 px-3 text-center">
  6244. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6245. 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')
  6246. }" title="Flags: ${flagDescriptions.join(', ')}">
  6247. ${flags || '-'}
  6248. </span>
  6249. </td>
  6250. <td class="py-2.5 px-3">
  6251. <div class="flex items-center gap-1.5 flex-wrap">
  6252. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6253. ${r.ecmp ? `
  6254. <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)">
  6255. <span>⚡ ECMP</span>
  6256. </span>
  6257. ` : ''}
  6258. ${r.multicast ? `
  6259. <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">
  6260. <span>IGMP</span>
  6261. </span>
  6262. ` : ''}
  6263. </div>
  6264. </td>
  6265. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6266. <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>
  6267. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6268. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6269. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6270. <td class="py-2.5 px-3">${healthCell}</td>
  6271. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6272. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6273. ${r.static ? `
  6274. <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>
  6275. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6276. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6277. ` : `
  6278. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6279. `}
  6280. </td>
  6281. `;
  6282. tbody.appendChild(tr);
  6283. });
  6284. }
  6285. function openAddRouteModal() {
  6286. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6287. document.getElementById('route-modal-id').value = '';
  6288. document.getElementById('route-modal-old-dst').value = '';
  6289. document.getElementById('route-modal-old-gw').value = '';
  6290. document.getElementById('route-modal-old-distance').value = '';
  6291. document.getElementById('route-modal-old-table').value = '';
  6292. document.getElementById('route-modal-old-iface').value = '';
  6293. const dstInput = document.getElementById('route-modal-dst');
  6294. const gwInput = document.getElementById('route-modal-gw');
  6295. const distInput = document.getElementById('route-modal-distance');
  6296. const ifaceSelect = document.getElementById('route-modal-iface');
  6297. const tableSelect = document.getElementById('route-modal-table');
  6298. const commentInput = document.getElementById('route-modal-comment');
  6299. const disCheck = document.getElementById('route-modal-disabled');
  6300. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6301. dstInput.disabled = false;
  6302. dstInput.value = '0.0.0.0/0';
  6303. gwInput.disabled = false;
  6304. gwInput.value = '';
  6305. distInput.disabled = false;
  6306. distInput.value = '1';
  6307. ifaceSelect.disabled = false;
  6308. tableSelect.disabled = false;
  6309. commentInput.disabled = false;
  6310. commentInput.value = '';
  6311. disCheck.disabled = false;
  6312. disCheck.checked = false;
  6313. if (saveBtn) saveBtn.classList.remove('hidden');
  6314. const checkGw = document.getElementById('route-modal-check-gw');
  6315. if (checkGw) checkGw.value = 'internet';
  6316. const checkTarget = document.getElementById('route-modal-check-target');
  6317. if (checkTarget) checkTarget.value = '1.1.1.1';
  6318. const checkInterval = document.getElementById('route-modal-check-interval');
  6319. if (checkInterval) checkInterval.value = '5';
  6320. const checkThresh = document.getElementById('route-modal-check-threshold');
  6321. if (checkThresh) checkThresh.value = '3';
  6322. toggleRouteCheckModeUI();
  6323. populateInterfaceSelect('route-modal-iface');
  6324. // Populate tables
  6325. tableSelect.innerHTML = '';
  6326. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6327. const opt = document.createElement('option');
  6328. opt.value = t.name;
  6329. opt.innerText = t.name;
  6330. if (t.name === 'main') opt.selected = true;
  6331. tableSelect.appendChild(opt);
  6332. });
  6333. document.getElementById('route-modal').classList.remove('hidden');
  6334. }
  6335. function openEditRouteModal(id) {
  6336. const r = (state.routes || []).find(route => route.id === id);
  6337. if (!r) return;
  6338. const isStatic = !!r.static;
  6339. document.getElementById('route-modal-title').innerText = isStatic
  6340. ? `Edit Route: ${r.dst_address}`
  6341. : `Route Properties (Read Only): ${r.dst_address}`;
  6342. document.getElementById('route-modal-id').value = r.id;
  6343. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6344. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6345. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6346. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6347. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6348. const dstInput = document.getElementById('route-modal-dst');
  6349. const gwInput = document.getElementById('route-modal-gw');
  6350. const distInput = document.getElementById('route-modal-distance');
  6351. const ifaceSelect = document.getElementById('route-modal-iface');
  6352. const tableSelect = document.getElementById('route-modal-table');
  6353. const commentInput = document.getElementById('route-modal-comment');
  6354. const disCheck = document.getElementById('route-modal-disabled');
  6355. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6356. dstInput.value = r.dst_address;
  6357. gwInput.value = r.gateway || '';
  6358. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6359. commentInput.value = r.comment || '';
  6360. disCheck.checked = !!r.disabled;
  6361. const checkGw = document.getElementById('route-modal-check-gw');
  6362. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6363. const checkTarget = document.getElementById('route-modal-check-target');
  6364. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6365. const checkInterval = document.getElementById('route-modal-check-interval');
  6366. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6367. const checkThresh = document.getElementById('route-modal-check-threshold');
  6368. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6369. toggleRouteCheckModeUI();
  6370. dstInput.disabled = !isStatic;
  6371. gwInput.disabled = !isStatic;
  6372. distInput.disabled = !isStatic;
  6373. ifaceSelect.disabled = !isStatic;
  6374. tableSelect.disabled = !isStatic;
  6375. commentInput.disabled = !isStatic;
  6376. disCheck.disabled = !isStatic;
  6377. if (checkGw) checkGw.disabled = !isStatic;
  6378. if (checkTarget) checkTarget.disabled = !isStatic;
  6379. if (checkInterval) checkInterval.disabled = !isStatic;
  6380. if (checkThresh) checkThresh.disabled = !isStatic;
  6381. if (saveBtn) {
  6382. if (isStatic) {
  6383. saveBtn.classList.remove('hidden');
  6384. } else {
  6385. saveBtn.classList.add('hidden');
  6386. }
  6387. }
  6388. populateInterfaceSelect('route-modal-iface', r.interface);
  6389. tableSelect.innerHTML = '';
  6390. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6391. const opt = document.createElement('option');
  6392. opt.value = t.name;
  6393. opt.innerText = t.name;
  6394. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6395. tableSelect.appendChild(opt);
  6396. });
  6397. document.getElementById('route-modal').classList.remove('hidden');
  6398. }
  6399. function closeRouteModal() {
  6400. document.getElementById('route-modal').classList.add('hidden');
  6401. }
  6402. function setRouteCheckTarget(ip) {
  6403. const inp = document.getElementById('route-modal-check-target');
  6404. if (inp) inp.value = ip;
  6405. }
  6406. function toggleRouteCheckModeUI() {
  6407. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6408. const targetRow = document.getElementById('route-row-check-target');
  6409. const paramsRow = document.getElementById('route-row-check-params');
  6410. if (mode === 'none') {
  6411. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6412. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6413. } else if (mode === 'ping') {
  6414. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6415. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6416. } else { // internet
  6417. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6418. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6419. }
  6420. }
  6421. async function submitSaveRoute(e) {
  6422. e.preventDefault();
  6423. const id = document.getElementById('route-modal-id').value;
  6424. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6425. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6426. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6427. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6428. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6429. const dst = document.getElementById('route-modal-dst').value.trim();
  6430. const gw = document.getElementById('route-modal-gw').value.trim();
  6431. const table = document.getElementById('route-modal-table').value;
  6432. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6433. const iface = document.getElementById('route-modal-iface').value;
  6434. const comment = document.getElementById('route-modal-comment').value.trim();
  6435. const disabled = document.getElementById('route-modal-disabled').checked;
  6436. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6437. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6438. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6439. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6440. if (!dst) {
  6441. showToast('Error', 'Destination address is required', 'error');
  6442. return;
  6443. }
  6444. if (!gw && !iface) {
  6445. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6446. return;
  6447. }
  6448. const payload = {
  6449. id,
  6450. old_dst_address: oldDst,
  6451. old_gateway: oldGw,
  6452. old_routing_table: oldTable,
  6453. old_interface: oldIface,
  6454. dst_address: dst,
  6455. gateway: gw || iface,
  6456. routing_table: table,
  6457. distance,
  6458. interface: iface,
  6459. comment,
  6460. disabled,
  6461. check_gateway,
  6462. check_target,
  6463. check_interval,
  6464. check_threshold
  6465. };
  6466. if (oldDistStr !== undefined && oldDistStr !== '') {
  6467. payload.old_distance = parseInt(oldDistStr, 10);
  6468. }
  6469. try {
  6470. const res = await fetch(`${API_BASE}/routes`, {
  6471. method: 'POST',
  6472. headers: { 'Content-Type': 'application/json' },
  6473. body: JSON.stringify(payload)
  6474. });
  6475. if (res.ok) {
  6476. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6477. closeRouteModal();
  6478. loadRoutes();
  6479. } else {
  6480. const err = await res.json();
  6481. showToast('Error', err.message || 'Failed to save route', 'error');
  6482. }
  6483. } catch (err) {
  6484. showToast('Error', err.message, 'error');
  6485. }
  6486. }
  6487. async function toggleRouteState(id, disabled) {
  6488. try {
  6489. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6490. method: 'POST',
  6491. headers: { 'Content-Type': 'application/json' },
  6492. body: JSON.stringify({ disabled })
  6493. });
  6494. if (res.ok) loadRoutes();
  6495. } catch (err) {
  6496. showToast('Error', err.message, 'error');
  6497. }
  6498. }
  6499. async function deleteRoute(id) {
  6500. if (!confirm('Are you sure you want to delete this route?')) return;
  6501. try {
  6502. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6503. if (res.ok) {
  6504. showToast('Deleted', 'Route removed', 'success');
  6505. loadRoutes();
  6506. }
  6507. } catch (err) {
  6508. showToast('Error', err.message, 'error');
  6509. }
  6510. }
  6511. // ----------------- Policy Rules (/ip route rule) -----------------
  6512. function renderPolicyRules() {
  6513. const tbody = document.getElementById('rules-table-body');
  6514. const empty = document.getElementById('rules-empty');
  6515. if (!tbody) return;
  6516. const showSystem = document.getElementById('prule-show-system')?.checked;
  6517. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6518. const countBadge = document.getElementById('rules-count-badge');
  6519. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6520. const bRules = document.getElementById('routes-badge-rules');
  6521. if (bRules) bRules.innerText = filtered.length;
  6522. if (filtered.length === 0) {
  6523. empty?.classList.remove('hidden');
  6524. tbody.innerHTML = '';
  6525. return;
  6526. }
  6527. empty?.classList.add('hidden');
  6528. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6529. if (tbody.dataset.sig === sig) return;
  6530. tbody.dataset.sig = sig;
  6531. tbody.innerHTML = '';
  6532. filtered.forEach(pr => {
  6533. const isSys = pr.is_default || pr.is_system;
  6534. const tr = document.createElement('tr');
  6535. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6536. tr.innerHTML = `
  6537. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6538. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6539. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6540. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6541. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6542. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6543. <td class="py-2.5 px-3 text-right font-sans">
  6544. ${!pr.is_default ? `
  6545. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6546. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6547. </td>
  6548. `;
  6549. tbody.appendChild(tr);
  6550. });
  6551. }
  6552. function openAddPolicyRuleModal() {
  6553. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6554. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6555. document.getElementById('prule-modal-mark').value = '';
  6556. document.getElementById('prule-modal-src').value = '';
  6557. document.getElementById('prule-modal-dst').value = '';
  6558. const sel = document.getElementById('prule-modal-table');
  6559. sel.innerHTML = '';
  6560. (state.routingTables || []).forEach(t => {
  6561. const opt = document.createElement('option');
  6562. opt.value = t.name;
  6563. opt.innerText = t.name;
  6564. sel.appendChild(opt);
  6565. });
  6566. document.getElementById('prule-modal').classList.remove('hidden');
  6567. }
  6568. function closePolicyRuleModal() {
  6569. document.getElementById('prule-modal').classList.add('hidden');
  6570. }
  6571. async function submitSavePolicyRule(e) {
  6572. e.preventDefault();
  6573. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6574. const mark = document.getElementById('prule-modal-mark').value.trim();
  6575. const src = document.getElementById('prule-modal-src').value.trim();
  6576. const dst = document.getElementById('prule-modal-dst').value.trim();
  6577. const table = document.getElementById('prule-modal-table').value;
  6578. const action = document.getElementById('prule-modal-action').value;
  6579. try {
  6580. const res = await fetch(`${API_BASE}/routing/rules`, {
  6581. method: 'POST',
  6582. headers: { 'Content-Type': 'application/json' },
  6583. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6584. });
  6585. if (res.ok) {
  6586. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6587. closePolicyRuleModal();
  6588. loadRoutes();
  6589. } else {
  6590. const err = await res.json();
  6591. showToast('Error', err.message, 'error');
  6592. }
  6593. } catch (err) {
  6594. showToast('Error', err.message, 'error');
  6595. }
  6596. }
  6597. async function deletePolicyRule(id) {
  6598. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6599. try {
  6600. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6601. if (res.ok) {
  6602. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6603. loadRoutes();
  6604. }
  6605. } catch (err) {
  6606. showToast('Error', err.message, 'error');
  6607. }
  6608. }
  6609. // ----------------- Routing Tables -----------------
  6610. function renderRoutingTables() {
  6611. const tbody = document.getElementById('tables-table-body');
  6612. if (!tbody) return;
  6613. const tables = state.routingTables || [];
  6614. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6615. if (tbody.dataset.sig === sig) return;
  6616. tbody.dataset.sig = sig;
  6617. tbody.innerHTML = '';
  6618. (state.routingTables || []).forEach(t => {
  6619. const tr = document.createElement('tr');
  6620. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6621. tr.innerHTML = `
  6622. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6623. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6624. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6625. `;
  6626. tbody.appendChild(tr);
  6627. });
  6628. }
  6629. function openAddTableModal() {
  6630. document.getElementById('table-modal-name').value = '';
  6631. document.getElementById('table-modal-id').value = '';
  6632. document.getElementById('table-modal-comment').value = '';
  6633. document.getElementById('table-modal').classList.remove('hidden');
  6634. }
  6635. function closeTableModal() {
  6636. document.getElementById('table-modal').classList.add('hidden');
  6637. }
  6638. async function submitSaveTable(e) {
  6639. e.preventDefault();
  6640. const name = document.getElementById('table-modal-name').value.trim();
  6641. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6642. const comment = document.getElementById('table-modal-comment').value.trim();
  6643. try {
  6644. const res = await fetch(`${API_BASE}/routing/tables`, {
  6645. method: 'POST',
  6646. headers: { 'Content-Type': 'application/json' },
  6647. body: JSON.stringify({ name, table_id: id, comment })
  6648. });
  6649. if (res.ok) {
  6650. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6651. closeTableModal();
  6652. loadRoutes();
  6653. } else {
  6654. const err = await res.json();
  6655. showToast('Error', err.message, 'error');
  6656. }
  6657. } catch (err) {
  6658. showToast('Error', err.message, 'error');
  6659. }
  6660. }
  6661. async function loadDebianConfig() {
  6662. const view = document.getElementById('debian-config-view');
  6663. view.innerText = 'Generating live configuration...';
  6664. try {
  6665. const res = await fetch(`${API_BASE}/debian/config`);
  6666. const data = await res.json();
  6667. view.innerText = data.content || '# Empty config';
  6668. } catch (err) {
  6669. view.innerText = 'Failed to generate Debian network config.';
  6670. }
  6671. }
  6672. async function saveDebianConfig() {
  6673. try {
  6674. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6675. const data = await res.json();
  6676. if (res.ok) {
  6677. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6678. loadDebianConfig();
  6679. }
  6680. } catch (err) {
  6681. showToast('Error', err.message, 'error');
  6682. }
  6683. }
  6684. function showToast(title, message, type = 'info') {
  6685. const container = document.getElementById('toast-container');
  6686. const toast = document.createElement('div');
  6687. const borderColors = {
  6688. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6689. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6690. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6691. };
  6692. 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}`;
  6693. toast.innerHTML = `
  6694. <div class="flex-1">
  6695. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  6696. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  6697. </div>
  6698. `;
  6699. container.appendChild(toast);
  6700. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6701. setTimeout(() => {
  6702. toast.classList.add('opacity-0', 'translate-y-2');
  6703. setTimeout(() => toast.remove(), 300);
  6704. }, 4000);
  6705. }
  6706. function formatTraffic(bytesPerSec) {
  6707. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6708. const kb = bytesPerSec / 1024;
  6709. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6710. const mb = kb / 1024;
  6711. return `${mb.toFixed(2)} MB/s`;
  6712. }
  6713. function toggleSidebar() {
  6714. const sb = document.getElementById('sidebar');
  6715. sb.classList.toggle('-translate-x-full');
  6716. }
  6717. // ======================== EoIP (Ethernet over IP) ========================
  6718. async function loadEoIP(populate = true) {
  6719. try {
  6720. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6721. const data = await res.json();
  6722. state.eoipTunnels = Array.isArray(data) ? data : [];
  6723. const badge = document.getElementById('eoip-count-badge');
  6724. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6725. const sideBadge = document.getElementById('badge-eoip-count');
  6726. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6727. renderEoIPTunnels();
  6728. } catch (err) {
  6729. console.error('Failed to load EoIP:', err);
  6730. }
  6731. }
  6732. function renderEoIPTunnels() {
  6733. const tbody = document.getElementById('eoip-table-body');
  6734. const empty = document.getElementById('eoip-empty');
  6735. if (!tbody) return;
  6736. tbody.innerHTML = '';
  6737. const tunnels = state.eoipTunnels || [];
  6738. if (tunnels.length === 0) {
  6739. empty?.classList.remove('hidden');
  6740. return;
  6741. }
  6742. empty?.classList.add('hidden');
  6743. tunnels.forEach(t => {
  6744. const tr = document.createElement('tr');
  6745. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6746. tr.innerHTML = `
  6747. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6748. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6749. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6750. <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>
  6751. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6752. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6753. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6754. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6755. <td class="py-2.5 px-3 font-mono text-[11px]">
  6756. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6757. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6758. </td>
  6759. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6760. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6761. <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>
  6762. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6763. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6764. </td>
  6765. `;
  6766. tbody.appendChild(tr);
  6767. });
  6768. }
  6769. function openAddEoIPModal() {
  6770. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6771. document.getElementById('eoip-modal-id').value = '';
  6772. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6773. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6774. document.getElementById('eoip-modal-remote').value = '';
  6775. document.getElementById('eoip-modal-ip').value = '';
  6776. document.getElementById('eoip-modal-local').value = '';
  6777. document.getElementById('eoip-modal-mac').value = '';
  6778. document.getElementById('eoip-modal-mtu').value = '1500';
  6779. document.getElementById('eoip-modal-comment').value = '';
  6780. document.getElementById('eoip-modal-clampmss').checked = true;
  6781. document.getElementById('eoip-modal-disabled').checked = false;
  6782. document.getElementById('eoip-modal').classList.remove('hidden');
  6783. }
  6784. function openEditEoIPModal(id) {
  6785. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6786. if (!t) return;
  6787. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6788. document.getElementById('eoip-modal-id').value = t.id;
  6789. document.getElementById('eoip-modal-name').value = t.name;
  6790. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6791. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6792. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6793. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6794. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6795. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6796. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6797. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6798. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6799. document.getElementById('eoip-modal').classList.remove('hidden');
  6800. }
  6801. function closeEoIPModal() {
  6802. document.getElementById('eoip-modal').classList.add('hidden');
  6803. }
  6804. async function submitSaveEoIP(e) {
  6805. e.preventDefault();
  6806. const id = document.getElementById('eoip-modal-id').value;
  6807. const name = document.getElementById('eoip-modal-name').value.trim();
  6808. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6809. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6810. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6811. const local = document.getElementById('eoip-modal-local').value.trim();
  6812. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6813. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6814. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6815. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6816. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6817. try {
  6818. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6819. method: 'POST',
  6820. headers: { 'Content-Type': 'application/json' },
  6821. body: JSON.stringify({
  6822. id,
  6823. name,
  6824. tunnel_id: tunnelId,
  6825. remote_address: remote,
  6826. ip_address: ipAddress,
  6827. local_address: local,
  6828. mac_address: mac,
  6829. mtu,
  6830. clamp_mss: clampMss,
  6831. comment,
  6832. disabled
  6833. })
  6834. });
  6835. if (res.ok) {
  6836. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6837. closeEoIPModal();
  6838. loadEoIP(false);
  6839. fetchData(false);
  6840. } else {
  6841. const err = await res.json();
  6842. showToast('Error', err.message, 'error');
  6843. }
  6844. } catch (err) {
  6845. showToast('Error', err.message, 'error');
  6846. }
  6847. }
  6848. async function toggleEoIPState(id, disabled) {
  6849. try {
  6850. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6851. method: 'POST',
  6852. headers: { 'Content-Type': 'application/json' },
  6853. body: JSON.stringify({ disabled })
  6854. });
  6855. if (res.ok) {
  6856. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6857. loadEoIP(false);
  6858. fetchData(false);
  6859. }
  6860. } catch (err) {
  6861. showToast('Error', err.message, 'error');
  6862. }
  6863. }
  6864. async function deleteEoIP(id) {
  6865. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6866. try {
  6867. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6868. if (res.ok) {
  6869. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6870. loadEoIP(false);
  6871. fetchData(false);
  6872. }
  6873. } catch (err) {
  6874. showToast('Error', err.message, 'error');
  6875. }
  6876. }
  6877. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6878. async function loadAeroTUN(populate = true) {
  6879. try {
  6880. const [tunnelsRes, statsRes] = await Promise.all([
  6881. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6882. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6883. ]);
  6884. if (tunnelsRes.ok) {
  6885. const data = await tunnelsRes.json();
  6886. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6887. }
  6888. if (statsRes.ok) {
  6889. state.aerotunStats = await statsRes.json();
  6890. }
  6891. const countBadge = document.getElementById('aerotun-count-badge');
  6892. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6893. const sideBadge = document.getElementById('badge-aerotun-count');
  6894. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6895. renderAeroTUN();
  6896. } catch (err) {
  6897. console.error('Failed to load AeroTUN:', err);
  6898. }
  6899. }
  6900. function renderAeroTUN() {
  6901. const tbody = document.getElementById('aerotun-table-body');
  6902. const empty = document.getElementById('aerotun-empty');
  6903. // Update summary cards
  6904. const stats = state.aerotunStats || {};
  6905. const tunnels = state.aerotunTunnels || [];
  6906. const statActive = document.getElementById('aerotun-stat-active');
  6907. if (statActive) {
  6908. const activeCount = tunnels.filter(t => t.connected).length;
  6909. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6910. }
  6911. const statSaved = document.getElementById('aerotun-stat-saved');
  6912. if (statSaved) {
  6913. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6914. }
  6915. const statRatio = document.getElementById('aerotun-stat-ratio');
  6916. if (statRatio) {
  6917. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6918. }
  6919. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6920. if (statTraffic) {
  6921. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6922. }
  6923. if (!tbody) return;
  6924. tbody.innerHTML = '';
  6925. if (tunnels.length === 0) {
  6926. empty?.classList.remove('hidden');
  6927. return;
  6928. }
  6929. empty?.classList.add('hidden');
  6930. tunnels.forEach(t => {
  6931. const tr = document.createElement('tr');
  6932. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6933. const modeBadge = t.mode === 'server'
  6934. ? `<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>`
  6935. : `<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>`;
  6936. const endpointInfo = t.mode === 'server'
  6937. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6938. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6939. const compBadge = t.compression
  6940. ? `<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>`
  6941. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6942. const activePeer = t.connected && t.active_peer_endpoint
  6943. ? `<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>`
  6944. : `<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>`;
  6945. const rawRx = formatBytes(t.rx_bytes || 0);
  6946. const rawTx = formatBytes(t.tx_bytes || 0);
  6947. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6948. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6949. tr.innerHTML = `
  6950. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6951. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6952. <span>${escapeHtml(t.name)}</span>
  6953. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6954. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6955. </td>
  6956. <td class="py-2.5 px-3">${modeBadge}</td>
  6957. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6958. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6959. <td class="py-2.5 px-3">${compBadge}</td>
  6960. <td class="py-2.5 px-3">${activePeer}</td>
  6961. <td class="py-2.5 px-3 font-mono text-[11px]">
  6962. <span class="text-emerald-400">↓ ${rawRx}</span>
  6963. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6964. </td>
  6965. <td class="py-2.5 px-3 font-mono text-[11px]">
  6966. <span class="text-slate-400">↓ ${wireRx}</span>
  6967. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6968. </td>
  6969. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6970. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6971. ${t.running
  6972. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6973. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6974. }
  6975. <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>
  6976. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6977. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6978. </td>
  6979. `;
  6980. tbody.appendChild(tr);
  6981. });
  6982. }
  6983. function onAeroTUNModeChange() {
  6984. const mode = document.getElementById('aerotun-modal-mode').value;
  6985. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6986. const portInput = document.getElementById('aerotun-modal-port');
  6987. if (mode === 'server') {
  6988. if (!portInput.value) portInput.value = '51830';
  6989. endpointInput.placeholder = 'Optional / learned roaming peer';
  6990. } else {
  6991. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6992. if (!portInput.value) portInput.value = '';
  6993. }
  6994. }
  6995. async function generateAeroTUNKey() {
  6996. try {
  6997. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6998. if (!res.ok) throw new Error(await responseError(res));
  6999. const data = await res.json();
  7000. document.getElementById('aerotun-modal-psk').value = data.key;
  7001. showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7002. } catch (err) {
  7003. showToast('Key Generation Failed', err.message, 'error');
  7004. }
  7005. }
  7006. function updateAeroTUNSetupHint() {
  7007. const version = document.getElementById('aerotun-modal-protocol').value;
  7008. const key = document.getElementById('aerotun-modal-public').value;
  7009. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7010. const hint = document.getElementById('aerotun-setup-hint');
  7011. if (!hint) return;
  7012. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? '1. Save disabled to create the local identity. 2. Exchange public keys and share the same PSK. 3. Set allowed peer prefixes, then enable.' : !peer ? 'Local identity saved. Copy the public key to the peer and paste its public key here. Use the same PSK on both endpoints.' : 'Peer identity configured. Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7013. }
  7014. async function copyAeroTUNPublicKey() {
  7015. const input = document.getElementById('aerotun-modal-public');
  7016. if (!input.value) { showToast('Save First', 'Save the disabled tunnel to create its public key', 'info'); return; }
  7017. try {
  7018. await navigator.clipboard.writeText(input.value);
  7019. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7020. } catch {
  7021. input.focus(); input.select();
  7022. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7023. }
  7024. }
  7025. function openAddAeroTUNModal() {
  7026. const tunnels = state.aerotunTunnels || [];
  7027. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7028. document.getElementById('aerotun-modal-id').value = '';
  7029. document.getElementById('aerotun-modal-protocol').value='3';
  7030. document.getElementById('aerotun-modal-public').value='';
  7031. document.getElementById('aerotun-modal-peerkey').value='';
  7032. document.getElementById('aerotun-modal-allowed').value=`10.99.${tunnels.length}.2/32`;
  7033. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  7034. document.getElementById('aerotun-modal-mode').value = 'server';
  7035. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  7036. document.getElementById('aerotun-modal-endpoint').value = '';
  7037. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  7038. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  7039. document.getElementById('aerotun-modal-psk').value = '';
  7040. document.getElementById('aerotun-modal-mtu').value = '1420';
  7041. document.getElementById('aerotun-modal-comment').value = '';
  7042. document.getElementById('aerotun-modal-compression').checked = false;
  7043. document.getElementById('aerotun-modal-defroute').checked = false;
  7044. document.getElementById('aerotun-modal-disabled').checked = true;
  7045. generateAeroTUNKey();
  7046. onAeroTUNModeChange();
  7047. updateAeroTUNSetupHint();
  7048. document.getElementById('aerotun-modal').classList.remove('hidden');
  7049. }
  7050. function openEditAeroTUNModal(id) {
  7051. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7052. if (!t) return;
  7053. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7054. document.getElementById('aerotun-modal-id').value = t.id;
  7055. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7056. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7057. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7058. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7059. document.getElementById('aerotun-modal-name').value = t.name;
  7060. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7061. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7062. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7063. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7064. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7065. document.getElementById('aerotun-modal-psk').value = '';
  7066. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7067. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7068. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7069. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7070. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7071. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7072. onAeroTUNModeChange();
  7073. updateAeroTUNSetupHint();
  7074. document.getElementById('aerotun-modal').classList.remove('hidden');
  7075. }
  7076. function closeAeroTUNModal() {
  7077. document.getElementById('aerotun-modal').classList.add('hidden');
  7078. }
  7079. async function submitSaveAeroTUN(e) {
  7080. e.preventDefault();
  7081. const id = document.getElementById('aerotun-modal-id').value;
  7082. const name = document.getElementById('aerotun-modal-name').value.trim();
  7083. const mode = document.getElementById('aerotun-modal-mode').value;
  7084. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7085. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7086. const local = document.getElementById('aerotun-modal-local').value.trim();
  7087. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7088. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7089. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  7090. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7091. const compression = document.getElementById('aerotun-modal-compression').checked;
  7092. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7093. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7094. if (mode === 'client' && !endpoint) {
  7095. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7096. return;
  7097. }
  7098. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7099. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7100. showToast('Peer Key Required', 'Save disabled first, exchange public keys, then enable', 'error');
  7101. return;
  7102. }
  7103. if (!psk && !id) {
  7104. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7105. return;
  7106. }
  7107. try {
  7108. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7109. method: 'POST',
  7110. headers: { 'Content-Type': 'application/json' },
  7111. body: JSON.stringify({
  7112. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7113. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7114. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7115. id,
  7116. name,
  7117. mode,
  7118. listen_port: port,
  7119. remote_endpoint: endpoint,
  7120. local_address: local,
  7121. peer_address: peer,
  7122. psk,
  7123. mtu,
  7124. compression,
  7125. default_route: defaultRoute,
  7126. comment,
  7127. disabled
  7128. })
  7129. });
  7130. if (res.ok) {
  7131. const saved = await res.json();
  7132. await loadAeroTUN(false);
  7133. if (!id && version === 3) {
  7134. openEditAeroTUNModal(saved.id);
  7135. showToast('Identity Saved', 'Copy the local public key and exchange keys with the peer', 'success');
  7136. } else {
  7137. closeAeroTUNModal();
  7138. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7139. }
  7140. fetchData(false);
  7141. } else {
  7142. const err = await res.text();
  7143. showToast('Error Saving Tunnel', err, 'error');
  7144. }
  7145. } catch (err) {
  7146. showToast('Network Error', err.message, 'error');
  7147. }
  7148. }
  7149. async function startAeroTUNTunnel(id) {
  7150. try {
  7151. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7152. if (res.ok) {
  7153. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7154. loadAeroTUN(false);
  7155. fetchData(false);
  7156. } else {
  7157. const err = await res.text();
  7158. showToast('Failed to Start', err, 'error');
  7159. }
  7160. } catch (err) {
  7161. showToast('Error', err.message, 'error');
  7162. }
  7163. }
  7164. async function stopAeroTUNTunnel(id) {
  7165. try {
  7166. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7167. if (res.ok) {
  7168. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7169. loadAeroTUN(false);
  7170. fetchData(false);
  7171. } else {
  7172. const err = await res.text();
  7173. showToast('Failed to Stop', err, 'error');
  7174. }
  7175. } catch (err) {
  7176. showToast('Error', err.message, 'error');
  7177. }
  7178. }
  7179. async function toggleAeroTUNState(id, disabled) {
  7180. try {
  7181. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7182. method: 'POST',
  7183. headers: { 'Content-Type': 'application/json' },
  7184. body: JSON.stringify({ disabled })
  7185. });
  7186. if (res.ok) {
  7187. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7188. loadAeroTUN(false);
  7189. fetchData(false);
  7190. }
  7191. } catch (err) {
  7192. showToast('Error', err.message, 'error');
  7193. }
  7194. }
  7195. async function deleteAeroTUN(id) {
  7196. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7197. try {
  7198. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7199. if (res.ok) {
  7200. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7201. loadAeroTUN(false);
  7202. fetchData(false);
  7203. }
  7204. } catch (err) {
  7205. showToast('Error', err.message, 'error');
  7206. }
  7207. }
  7208. // ======================== PPP Central Hub & Servers ========================
  7209. function switchPPPSubTab(tab) {
  7210. state.pppSubTab = tab;
  7211. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7212. tabs.forEach(t => {
  7213. const panel = document.getElementById(`ppp-subtab-${t}`);
  7214. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7215. if (panel) {
  7216. if (t === tab) panel.classList.remove('hidden');
  7217. else panel.classList.add('hidden');
  7218. }
  7219. if (btn) {
  7220. if (t === tab) {
  7221. 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';
  7222. } else {
  7223. 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';
  7224. }
  7225. }
  7226. });
  7227. const addBtn = document.getElementById('ppp-primary-add-btn');
  7228. if (addBtn) {
  7229. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7230. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7231. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7232. else addBtn.innerHTML = '<span>Save Config</span>';
  7233. }
  7234. if (tab === 'active') loadPPPSessions();
  7235. }
  7236. function openCurrentPPPModal() {
  7237. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7238. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7239. else if (state.pppSubTab === 'active') loadPPPSessions();
  7240. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7241. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7242. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7243. }
  7244. async function loadPPP(populateDropdowns = true) {
  7245. await Promise.all([
  7246. loadPPPSecrets(),
  7247. loadPPPProfiles(),
  7248. loadPPPServers(),
  7249. loadPPPSessions()
  7250. ]);
  7251. }
  7252. async function loadPPPSecrets() {
  7253. try {
  7254. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7255. const data = await res.json();
  7256. state.pppSecrets = Array.isArray(data) ? data : [];
  7257. const b = document.getElementById('ppp-badge-secrets');
  7258. if (b) b.innerText = state.pppSecrets.length;
  7259. const b2 = document.getElementById('secrets-count-badge');
  7260. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7261. renderPPPSecrets();
  7262. } catch (err) {
  7263. console.error('Failed to load PPP secrets:', err);
  7264. }
  7265. }
  7266. function renderPPPSecrets() {
  7267. const tbody = document.getElementById('secrets-table-body');
  7268. const empty = document.getElementById('secrets-empty');
  7269. if (!tbody) return;
  7270. tbody.innerHTML = '';
  7271. const secrets = state.pppSecrets || [];
  7272. if (secrets.length === 0) {
  7273. empty?.classList.remove('hidden');
  7274. return;
  7275. }
  7276. empty?.classList.add('hidden');
  7277. secrets.forEach(s => {
  7278. const tr = document.createElement('tr');
  7279. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7280. tr.innerHTML = `
  7281. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7282. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7283. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7284. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7285. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7286. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7287. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7288. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7289. <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>
  7290. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7291. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7292. </td>
  7293. `;
  7294. tbody.appendChild(tr);
  7295. });
  7296. }
  7297. async function loadPPPProfiles() {
  7298. try {
  7299. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7300. const data = await res.json();
  7301. state.pppProfiles = Array.isArray(data) ? data : [];
  7302. const b = document.getElementById('ppp-badge-profiles');
  7303. if (b) b.innerText = state.pppProfiles.length;
  7304. const b2 = document.getElementById('profiles-count-badge');
  7305. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7306. // Populate profile selects across modals
  7307. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7308. selects.forEach(sid => {
  7309. const el = document.getElementById(sid);
  7310. if (!el) return;
  7311. const cur = el.value;
  7312. el.innerHTML = '';
  7313. state.pppProfiles.forEach(p => {
  7314. const opt = document.createElement('option');
  7315. opt.value = p.name;
  7316. opt.innerText = `${p.name} (${p.remote_address})`;
  7317. if (p.name === cur) opt.selected = true;
  7318. el.appendChild(opt);
  7319. });
  7320. });
  7321. renderPPPProfiles();
  7322. } catch (err) {
  7323. console.error('Failed to load PPP profiles:', err);
  7324. }
  7325. }
  7326. function renderPPPProfiles() {
  7327. const tbody = document.getElementById('profiles-table-body');
  7328. if (!tbody) return;
  7329. tbody.innerHTML = '';
  7330. (state.pppProfiles || []).forEach(p => {
  7331. const isDefault = p.name.startsWith('default');
  7332. const tr = document.createElement('tr');
  7333. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7334. tr.innerHTML = `
  7335. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7336. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7337. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7338. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7339. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7340. <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>
  7341. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7342. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7343. ${!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>`}
  7344. </td>
  7345. `;
  7346. tbody.appendChild(tr);
  7347. });
  7348. }
  7349. async function loadPPPServers() {
  7350. try {
  7351. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7352. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7353. fetch(`${API_BASE}/vpn/servers/pptp`),
  7354. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7355. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7356. ]);
  7357. if (pppoeRes.ok) {
  7358. state.pppoeServer = await pppoeRes.json();
  7359. const s = state.pppoeServer;
  7360. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7361. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7362. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7363. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7364. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7365. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7366. const pill = document.getElementById('pppoe-server-status-pill');
  7367. if (pill) {
  7368. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7369. 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';
  7370. }
  7371. setDotBadge('ppp-badge-pppoe-state', s.running);
  7372. }
  7373. if (pptpRes.ok) {
  7374. state.pptpServer = await pptpRes.json();
  7375. const s = state.pptpServer;
  7376. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7377. document.getElementById('pptp-server-port').value = s.port || 1723;
  7378. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7379. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7380. const pill = document.getElementById('pptp-server-status-pill');
  7381. if (pill) {
  7382. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7383. 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';
  7384. }
  7385. setDotBadge('ppp-badge-pptp-state', s.running);
  7386. }
  7387. if (l2tpRes.ok) {
  7388. state.l2tpServer = await l2tpRes.json();
  7389. const s = state.l2tpServer;
  7390. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7391. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7392. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7393. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7394. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7395. const pill = document.getElementById('l2tp-server-status-pill');
  7396. if (pill) {
  7397. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7398. 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';
  7399. }
  7400. setDotBadge('ppp-badge-l2tp-state', s.running);
  7401. }
  7402. if (ipsecRes.ok) {
  7403. state.ipsecServer = await ipsecRes.json();
  7404. const s = state.ipsecServer;
  7405. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7406. if (modalEn) modalEn.checked = !!s.enabled;
  7407. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7408. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7409. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7410. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7411. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7412. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7413. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7414. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7415. const pill = document.getElementById('modal-ipsec-server-status');
  7416. if (pill) {
  7417. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7418. 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';
  7419. }
  7420. }
  7421. } catch (err) {
  7422. console.error('Failed to load VPN servers:', err);
  7423. }
  7424. }
  7425. async function loadPPPSessions() {
  7426. try {
  7427. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7428. const data = await res.json();
  7429. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7430. const b = document.getElementById('ppp-badge-active');
  7431. if (b) b.innerText = state.pppActiveSessions.length;
  7432. const sideB = document.getElementById('badge-ppp-sessions');
  7433. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7434. renderPPPSessions();
  7435. } catch (err) {
  7436. console.error('Failed to load active PPP sessions:', err);
  7437. }
  7438. }
  7439. function renderPPPSessions() {
  7440. const tbody = document.getElementById('active-ppp-table-body');
  7441. const empty = document.getElementById('active-ppp-empty');
  7442. if (!tbody) return;
  7443. tbody.innerHTML = '';
  7444. const list = state.pppActiveSessions || [];
  7445. if (list.length === 0) {
  7446. empty?.classList.remove('hidden');
  7447. return;
  7448. }
  7449. empty?.classList.add('hidden');
  7450. list.forEach(s => {
  7451. const tr = document.createElement('tr');
  7452. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7453. tr.innerHTML = `
  7454. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7455. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7456. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7457. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7458. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7459. <td class="py-2.5 px-3 text-[11px]">
  7460. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7461. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7462. </td>
  7463. <td class="py-2.5 px-3 text-right font-sans">
  7464. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7465. </td>
  7466. `;
  7467. tbody.appendChild(tr);
  7468. });
  7469. }
  7470. async function disconnectPPPSession(iface) {
  7471. if (!confirm(`Disconnect session ${iface}?`)) return;
  7472. try {
  7473. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7474. if (res.ok) {
  7475. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7476. loadPPPSessions();
  7477. }
  7478. } catch (err) {
  7479. showToast('Error', err.message, 'error');
  7480. }
  7481. }
  7482. // PPP Secret Modal handlers
  7483. function openAddPPPSecretModal() {
  7484. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7485. document.getElementById('secret-modal-id').value = '';
  7486. document.getElementById('secret-modal-name').value = '';
  7487. document.getElementById('secret-modal-password').value = '';
  7488. document.getElementById('secret-modal-service').value = 'any';
  7489. document.getElementById('secret-modal-profile').value = 'default';
  7490. document.getElementById('secret-modal-local').value = '';
  7491. document.getElementById('secret-modal-remote').value = '';
  7492. document.getElementById('secret-modal-comment').value = '';
  7493. document.getElementById('secret-modal-disabled').checked = false;
  7494. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7495. }
  7496. function openEditPPPSecretModal(id) {
  7497. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7498. if (!s) return;
  7499. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7500. document.getElementById('secret-modal-id').value = s.id;
  7501. document.getElementById('secret-modal-name').value = s.name;
  7502. document.getElementById('secret-modal-password').value = s.password;
  7503. document.getElementById('secret-modal-service').value = s.service || 'any';
  7504. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7505. document.getElementById('secret-modal-local').value = s.local_address || '';
  7506. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7507. document.getElementById('secret-modal-comment').value = s.comment || '';
  7508. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7509. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7510. }
  7511. function closePPPSecretModal() {
  7512. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7513. }
  7514. async function submitSavePPPSecret(e) {
  7515. e.preventDefault();
  7516. const id = document.getElementById('secret-modal-id').value;
  7517. const name = document.getElementById('secret-modal-name').value.trim();
  7518. const password = document.getElementById('secret-modal-password').value.trim();
  7519. const service = document.getElementById('secret-modal-service').value;
  7520. const profile = document.getElementById('secret-modal-profile').value;
  7521. const local = document.getElementById('secret-modal-local').value.trim();
  7522. const remote = document.getElementById('secret-modal-remote').value.trim();
  7523. const comment = document.getElementById('secret-modal-comment').value.trim();
  7524. const disabled = document.getElementById('secret-modal-disabled').checked;
  7525. try {
  7526. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7527. method: 'POST',
  7528. headers: { 'Content-Type': 'application/json' },
  7529. body: JSON.stringify({
  7530. id,
  7531. name,
  7532. password,
  7533. service,
  7534. profile,
  7535. local_address: local,
  7536. remote_address: remote,
  7537. comment,
  7538. disabled
  7539. })
  7540. });
  7541. if (res.ok) {
  7542. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7543. closePPPSecretModal();
  7544. loadPPPSecrets();
  7545. } else {
  7546. const err = await res.json();
  7547. showToast('Error', err.message, 'error');
  7548. }
  7549. } catch (err) {
  7550. showToast('Error', err.message, 'error');
  7551. }
  7552. }
  7553. async function togglePPPSecretState(id, disabled) {
  7554. try {
  7555. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7556. method: 'POST',
  7557. headers: { 'Content-Type': 'application/json' },
  7558. body: JSON.stringify({ disabled })
  7559. });
  7560. if (res.ok) {
  7561. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7562. loadPPPSecrets();
  7563. }
  7564. } catch (err) {
  7565. showToast('Error', err.message, 'error');
  7566. }
  7567. }
  7568. async function deletePPPSecret(id) {
  7569. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7570. try {
  7571. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7572. if (res.ok) {
  7573. showToast('Deleted', 'Secret account removed', 'success');
  7574. loadPPPSecrets();
  7575. }
  7576. } catch (err) {
  7577. showToast('Error', err.message, 'error');
  7578. }
  7579. }
  7580. // PPP Profile Modal handlers
  7581. function openAddPPPProfileModal() {
  7582. document.getElementById('profile-modal-name').value = '';
  7583. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7584. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7585. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7586. document.getElementById('profile-modal-encryption').value = 'required';
  7587. document.getElementById('profile-modal-onlyone').checked = true;
  7588. document.getElementById('profile-modal-comment').value = '';
  7589. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7590. }
  7591. function closePPPProfileModal() {
  7592. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7593. }
  7594. async function submitSavePPPProfile(e) {
  7595. e.preventDefault();
  7596. const name = document.getElementById('profile-modal-name').value.trim();
  7597. const local = document.getElementById('profile-modal-local').value.trim();
  7598. const remote = document.getElementById('profile-modal-remote').value.trim();
  7599. const dns = document.getElementById('profile-modal-dns').value.trim();
  7600. const enc = document.getElementById('profile-modal-encryption').value;
  7601. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7602. const comment = document.getElementById('profile-modal-comment').value.trim();
  7603. try {
  7604. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7605. method: 'POST',
  7606. headers: { 'Content-Type': 'application/json' },
  7607. body: JSON.stringify({
  7608. id: name,
  7609. name,
  7610. local_address: local,
  7611. remote_address: remote,
  7612. dns_servers: dns,
  7613. use_encryption: enc,
  7614. only_one: onlyone,
  7615. comment
  7616. })
  7617. });
  7618. if (res.ok) {
  7619. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7620. closePPPProfileModal();
  7621. loadPPPProfiles();
  7622. } else {
  7623. const err = await res.json();
  7624. showToast('Error', err.message, 'error');
  7625. }
  7626. } catch (err) {
  7627. showToast('Error', err.message, 'error');
  7628. }
  7629. }
  7630. async function deletePPPProfile(name) {
  7631. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7632. try {
  7633. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7634. if (res.ok) {
  7635. showToast('Deleted', 'Profile removed', 'success');
  7636. loadPPPProfiles();
  7637. } else {
  7638. const err = await res.json();
  7639. showToast('Error', err.message, 'error');
  7640. }
  7641. } catch (err) {
  7642. showToast('Error', err.message, 'error');
  7643. }
  7644. }
  7645. // Server Config submissions
  7646. async function savePPPoEServerConfig(e) {
  7647. e.preventDefault();
  7648. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7649. const name = document.getElementById('pppoe-server-name').value.trim();
  7650. const iface = document.getElementById('pppoe-server-iface').value;
  7651. const profile = document.getElementById('pppoe-server-profile').value;
  7652. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7653. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7654. try {
  7655. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7656. method: 'POST',
  7657. headers: { 'Content-Type': 'application/json' },
  7658. body: JSON.stringify({
  7659. enabled,
  7660. service_name: name,
  7661. interface: iface,
  7662. default_profile: profile,
  7663. max_mtu: mtu,
  7664. max_mru: mtu,
  7665. one_session_per_host: onesession
  7666. })
  7667. });
  7668. if (res.ok) {
  7669. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7670. loadPPPServers();
  7671. fetchData(false);
  7672. } else {
  7673. const err = await res.json();
  7674. showToast('Error', err.message, 'error');
  7675. }
  7676. } catch (err) {
  7677. showToast('Error', err.message, 'error');
  7678. }
  7679. }
  7680. async function savePPTPServerConfig(e) {
  7681. e.preventDefault();
  7682. const enabled = document.getElementById('pptp-server-enabled').checked;
  7683. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7684. const profile = document.getElementById('pptp-server-profile').value;
  7685. const mppe = document.getElementById('pptp-server-mppe').checked;
  7686. try {
  7687. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7688. method: 'POST',
  7689. headers: { 'Content-Type': 'application/json' },
  7690. body: JSON.stringify({
  7691. enabled,
  7692. port,
  7693. default_profile: profile,
  7694. require_mppe: mppe
  7695. })
  7696. });
  7697. if (res.ok) {
  7698. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7699. loadPPPServers();
  7700. fetchData(false);
  7701. } else {
  7702. const err = await res.json();
  7703. showToast('Error', err.message, 'error');
  7704. }
  7705. } catch (err) {
  7706. showToast('Error', err.message, 'error');
  7707. }
  7708. }
  7709. async function saveL2TPServerConfig(e) {
  7710. e.preventDefault();
  7711. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7712. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7713. const profile = document.getElementById('l2tp-server-profile').value;
  7714. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7715. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7716. try {
  7717. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7718. method: 'POST',
  7719. headers: { 'Content-Type': 'application/json' },
  7720. body: JSON.stringify({
  7721. enabled,
  7722. port,
  7723. default_profile: profile,
  7724. use_ipsec: useipsec,
  7725. ipsec_secret: psk
  7726. })
  7727. });
  7728. if (res.ok) {
  7729. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7730. loadPPPServers();
  7731. fetchData(false);
  7732. } else {
  7733. const err = await res.json();
  7734. showToast('Error', err.message, 'error');
  7735. }
  7736. } catch (err) {
  7737. showToast('Error', err.message, 'error');
  7738. }
  7739. }
  7740. // IPSec Server Modal
  7741. function openIPSecServerModal() {
  7742. loadPPPServers();
  7743. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7744. }
  7745. function closeIPSecServerModal() {
  7746. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7747. }
  7748. async function submitSaveIPSecServer(e) {
  7749. e.preventDefault();
  7750. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7751. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7752. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7753. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7754. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7755. try {
  7756. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7757. method: 'POST',
  7758. headers: { 'Content-Type': 'application/json' },
  7759. body: JSON.stringify({
  7760. enabled,
  7761. preshared_key: psk,
  7762. pool_address: pool,
  7763. dns_servers: dns,
  7764. local_subnet: subnet
  7765. })
  7766. });
  7767. if (res.ok) {
  7768. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7769. closeIPSecServerModal();
  7770. loadPPPServers();
  7771. fetchData(false);
  7772. } else {
  7773. const err = await res.json();
  7774. showToast('Error', err.message, 'error');
  7775. }
  7776. } catch (err) {
  7777. showToast('Error', err.message, 'error');
  7778. }
  7779. }
  7780. // WireGuard Client Config Viewer
  7781. let currentWGClientConf = '';
  7782. async function openWGClientConfModal(iface, clientIP) {
  7783. try {
  7784. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7785. method: 'POST',
  7786. headers: { 'Content-Type': 'application/json' },
  7787. body: JSON.stringify({
  7788. interface: iface,
  7789. address: clientIP || '10.10.0.2/32',
  7790. dns: '1.1.1.1, 8.8.8.8'
  7791. })
  7792. });
  7793. if (res.ok) {
  7794. const data = await res.json();
  7795. currentWGClientConf = data.config;
  7796. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7797. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7798. } else {
  7799. const err = await res.json();
  7800. showToast('Error', err.message, 'error');
  7801. }
  7802. } catch (err) {
  7803. showToast('Error', err.message, 'error');
  7804. }
  7805. }
  7806. function closeWGClientConfModal() {
  7807. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7808. }
  7809. function copyWGClientConf() {
  7810. if (!currentWGClientConf) return;
  7811. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7812. }
  7813. function downloadWGClientConf() {
  7814. if (!currentWGClientConf) return;
  7815. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7816. const a = document.createElement('a');
  7817. a.href = URL.createObjectURL(blob);
  7818. a.download = 'wireguard-client.conf';
  7819. document.body.appendChild(a);
  7820. a.click();
  7821. document.body.removeChild(a);
  7822. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7823. }
  7824. // =========================================================================
  7825. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7826. // =========================================================================
  7827. state.activeDynSubTab = 'bgp-peers';
  7828. state.activeBgpSubTab = 'bgp-peers';
  7829. state.activeOspfTab = 'instances';
  7830. state.bgpInstance = null;
  7831. state.bgpPeers = [];
  7832. state.bgpNets = [];
  7833. state.bgpRoutes = [];
  7834. state.ospfInstance = null;
  7835. state.ospfInstances = [];
  7836. state.ospfAreas = [];
  7837. state.ospfAreaRanges = [];
  7838. state.ospfTemplates = [];
  7839. state.ospfLiveInterfaces = [];
  7840. state.ospfStaticNbrs = [];
  7841. state.ospfNeighbors = [];
  7842. state.ospfLSA = [];
  7843. state.ospfRoutes = [];
  7844. state.selectedOspfRow = {
  7845. instances: null,
  7846. areas: null,
  7847. 'area-ranges': null,
  7848. templates: null,
  7849. interfaces: null,
  7850. 'static-nbrs': null,
  7851. neighbors: null,
  7852. lsa: null,
  7853. };
  7854. state.ospfSort = {
  7855. instances: { col: 'name', asc: true },
  7856. areas: { col: 'name', asc: true },
  7857. ranges: { col: 'area', asc: true },
  7858. templates: { col: 'interfaces', asc: true },
  7859. live_ifaces: { col: 'interface', asc: true },
  7860. snbrs: { col: 'address', asc: true },
  7861. neighbors: { col: 'address', asc: true },
  7862. lsa: { col: 'instance', asc: true },
  7863. };
  7864. function switchBgpSubTab(subTab) {
  7865. state.activeBgpSubTab = subTab;
  7866. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7867. tabs.forEach(t => {
  7868. const el = document.getElementById(`dyn-subtab-${t}`);
  7869. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7870. if (el) el.classList.toggle('hidden', t !== subTab);
  7871. if (btn) {
  7872. if (t === subTab) {
  7873. 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';
  7874. } else {
  7875. 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';
  7876. }
  7877. }
  7878. });
  7879. }
  7880. function switchOspfTab(tabName) {
  7881. state.activeOspfTab = tabName;
  7882. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7883. tabs.forEach(t => {
  7884. const pane = document.getElementById(`ospf-pane-${t}`);
  7885. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7886. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7887. if (btn) {
  7888. if (t === tabName) {
  7889. 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';
  7890. } else {
  7891. 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';
  7892. }
  7893. }
  7894. });
  7895. }
  7896. function switchOspfSubTab(tab) {
  7897. // Legacy alias
  7898. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7899. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7900. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7901. else switchOspfTab('instances');
  7902. }
  7903. function switchDynSubTab(subTab) {
  7904. if (subTab.startsWith('bgp')) {
  7905. if (state.activeTab !== 'bgp') navigate('bgp');
  7906. switchBgpSubTab(subTab);
  7907. } else if (subTab.startsWith('ospf')) {
  7908. if (state.activeTab !== 'ospf') navigate('ospf');
  7909. switchOspfTab('instances');
  7910. }
  7911. }
  7912. async function loadDynamicRouting(showToastMsg = false) {
  7913. try {
  7914. const fetchSafeJson = async (url) => {
  7915. try {
  7916. const r = await fetch(url);
  7917. return r.ok ? await r.json() : null;
  7918. } catch (e) {
  7919. return null;
  7920. }
  7921. };
  7922. const [
  7923. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7924. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7925. selectRules, commLists, asLists
  7926. ] = await Promise.all([
  7927. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7928. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7929. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7930. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7931. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7932. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7933. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7934. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7935. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7936. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7937. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7938. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7939. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7940. fetchSafeJson(`${API_BASE}/routing/filters`),
  7941. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7942. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7943. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7944. ]);
  7945. if (sum) state.dynSummary = sum;
  7946. if (bgpInst) state.bgpInstance = bgpInst;
  7947. if (bgpPeers) state.bgpPeers = bgpPeers;
  7948. if (bgpNets) state.bgpNets = bgpNets;
  7949. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7950. if (ospfInsts) state.ospfInstances = ospfInsts;
  7951. if (ospfAreas) state.ospfAreas = ospfAreas;
  7952. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7953. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7954. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7955. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7956. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7957. if (ospfLsa) state.ospfLSA = ospfLsa;
  7958. if (filters) state.routingFilters = filters;
  7959. if (selectRules) state.routingSelectRules = selectRules;
  7960. if (commLists) state.routingCommunityLists = commLists;
  7961. if (asLists) state.routingASLists = asLists;
  7962. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7963. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7964. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7965. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7966. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7967. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7968. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7969. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7970. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7971. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7972. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7973. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7974. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7975. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7976. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7977. } catch (err) {
  7978. console.error('Failed to load dynamic routing:', err);
  7979. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7980. }
  7981. }
  7982. async function loadOspfAll() {
  7983. await loadDynamicRouting(true);
  7984. }
  7985. function renderBgpStatusPill() {
  7986. const pills = document.querySelectorAll('.bgp-live-status-pill');
  7987. pills.forEach(pill => {
  7988. const inst = state.bgpInstance;
  7989. if (!inst || !inst.enabled) {
  7990. 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';
  7991. pill.innerText = 'BGP DISABLED';
  7992. } else if (inst.running) {
  7993. 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';
  7994. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7995. } else {
  7996. 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';
  7997. pill.innerText = 'BGP STARTING...';
  7998. }
  7999. });
  8000. }
  8001. function renderBgpPeers() {
  8002. const tbody = document.getElementById('bgp-peers-table-body');
  8003. if (!tbody) return;
  8004. const empty = document.getElementById('bgp-peers-empty');
  8005. const countBadge = document.getElementById('bgp-peers-count-badge');
  8006. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8007. const peers = state.bgpPeers || [];
  8008. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8009. if (navBadge) navBadge.innerText = peers.length;
  8010. if (peers.length === 0) {
  8011. tbody.innerHTML = '';
  8012. if (empty) empty.classList.remove('hidden');
  8013. return;
  8014. }
  8015. if (empty) empty.classList.add('hidden');
  8016. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8017. if (tbody.dataset.sig === sig) return;
  8018. tbody.dataset.sig = sig;
  8019. tbody.innerHTML = peers.map(p => {
  8020. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8021. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8022. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8023. let stateBadge = '';
  8024. if (p.disabled) {
  8025. 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>';
  8026. } else if (p.state === 'Established') {
  8027. 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>';
  8028. } else if (p.state === 'Connect' || p.state === 'Active') {
  8029. 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>`;
  8030. } else {
  8031. 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>`;
  8032. }
  8033. return `
  8034. <tr class="hover:bg-slate-800/40 transition">
  8035. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8036. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8037. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8038. <td class="py-2.5 px-3">
  8039. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8040. ${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>`}
  8041. </td>
  8042. <td class="py-2.5 px-3">${stateBadge}</td>
  8043. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8044. <td class="py-2.5 px-3 text-slate-300">
  8045. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8046. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8047. </td>
  8048. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8049. ${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> ` : ''}
  8050. ${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>` : ''}
  8051. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8052. </td>
  8053. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8054. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8055. <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'}">
  8056. ${p.disabled ? 'Enable' : 'Disable'}
  8057. </button>
  8058. <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">
  8059. Edit
  8060. </button>
  8061. <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">
  8062. Delete
  8063. </button>
  8064. </td>
  8065. </tr>
  8066. `;
  8067. }).join('');
  8068. }
  8069. function renderBgpNetworks() {
  8070. const tbody = document.getElementById('bgp-nets-table-body');
  8071. if (!tbody) return;
  8072. const empty = document.getElementById('bgp-nets-empty');
  8073. const countBadge = document.getElementById('bgp-nets-count-badge');
  8074. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8075. const nets = state.bgpNets || [];
  8076. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8077. if (navBadge) navBadge.innerText = nets.length;
  8078. if (nets.length === 0) {
  8079. tbody.innerHTML = '';
  8080. if (empty) empty.classList.remove('hidden');
  8081. return;
  8082. }
  8083. if (empty) empty.classList.add('hidden');
  8084. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8085. if (tbody.dataset.sig === sig) return;
  8086. tbody.dataset.sig = sig;
  8087. tbody.innerHTML = nets.map(n => `
  8088. <tr class="hover:bg-slate-800/40 transition">
  8089. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8090. <td class="py-2.5 px-3">
  8091. ${n.disabled
  8092. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8093. : '<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>'}
  8094. </td>
  8095. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8096. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8097. <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">
  8098. Delete
  8099. </button>
  8100. </td>
  8101. </tr>
  8102. `).join('');
  8103. }
  8104. function renderBgpRoutes() {
  8105. const tbody = document.getElementById('bgp-routes-table-body');
  8106. if (!tbody) return;
  8107. const empty = document.getElementById('bgp-routes-empty');
  8108. const countBadge = document.getElementById('bgp-routes-count-badge');
  8109. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8110. const routes = state.bgpRoutes || [];
  8111. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8112. if (navBadge) navBadge.innerText = routes.length;
  8113. if (routes.length === 0) {
  8114. tbody.innerHTML = '';
  8115. if (empty) empty.classList.remove('hidden');
  8116. return;
  8117. }
  8118. if (empty) empty.classList.add('hidden');
  8119. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8120. if (tbody.dataset.sig === sig) return;
  8121. tbody.dataset.sig = sig;
  8122. tbody.innerHTML = routes.map(r => `
  8123. <tr class="hover:bg-slate-800/40 transition">
  8124. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8125. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8126. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8127. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8128. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8129. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8130. </tr>
  8131. `).join('');
  8132. }
  8133. // =========================================================================
  8134. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8135. // =========================================================================
  8136. function sortOspfTable(tab, col) {
  8137. if (!state.ospfSort) state.ospfSort = {};
  8138. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8139. if (state.ospfSort[tab].col === col) {
  8140. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8141. } else {
  8142. state.ospfSort[tab].col = col;
  8143. state.ospfSort[tab].asc = true;
  8144. }
  8145. const asc = state.ospfSort[tab].asc;
  8146. let list = [];
  8147. if (tab === 'instances') list = state.ospfInstances || [];
  8148. else if (tab === 'areas') list = state.ospfAreas || [];
  8149. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8150. else if (tab === 'templates') list = state.ospfTemplates || [];
  8151. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8152. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8153. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8154. else if (tab === 'lsa') list = state.ospfLSA || [];
  8155. list.sort((a, b) => {
  8156. let valA = a[col] ?? '';
  8157. let valB = b[col] ?? '';
  8158. if (typeof valA === 'number' && typeof valB === 'number') {
  8159. return asc ? valA - valB : valB - valA;
  8160. }
  8161. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8162. });
  8163. if (tab === 'instances') renderOspfInstances();
  8164. else if (tab === 'areas') renderOspfAreas();
  8165. else if (tab === 'ranges') renderOspfAreaRanges();
  8166. else if (tab === 'templates') renderOspfTemplates();
  8167. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8168. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8169. else if (tab === 'neighbors') renderOspfNeighbors();
  8170. else if (tab === 'lsa') renderOspfLSA();
  8171. }
  8172. function selectOspfRow(tab, id) {
  8173. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8174. state.selectedOspfRow[tab] = id;
  8175. if (tab === 'instances') {
  8176. renderOspfInstances();
  8177. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8178. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8179. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8180. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8181. if (btnEn) btnEn.disabled = false;
  8182. if (btnDis) btnDis.disabled = false;
  8183. if (btnRem) btnRem.disabled = false;
  8184. if (btnCom) btnCom.disabled = false;
  8185. } else if (tab === 'areas') {
  8186. renderOspfAreas();
  8187. const btnEn = document.getElementById('btn-ospf-area-enable');
  8188. const btnDis = document.getElementById('btn-ospf-area-disable');
  8189. const btnRem = document.getElementById('btn-ospf-area-remove');
  8190. const btnCom = document.getElementById('btn-ospf-area-comment');
  8191. if (btnEn) btnEn.disabled = false;
  8192. if (btnDis) btnDis.disabled = false;
  8193. if (btnRem) btnRem.disabled = false;
  8194. if (btnCom) btnCom.disabled = false;
  8195. } else if (tab === 'ranges') {
  8196. renderOspfAreaRanges();
  8197. const btnEn = document.getElementById('btn-ospf-range-enable');
  8198. const btnDis = document.getElementById('btn-ospf-range-disable');
  8199. const btnRem = document.getElementById('btn-ospf-range-remove');
  8200. const btnCom = document.getElementById('btn-ospf-range-comment');
  8201. if (btnEn) btnEn.disabled = false;
  8202. if (btnDis) btnDis.disabled = false;
  8203. if (btnRem) btnRem.disabled = false;
  8204. if (btnCom) btnCom.disabled = false;
  8205. } else if (tab === 'templates') {
  8206. renderOspfTemplates();
  8207. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8208. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8209. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8210. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8211. if (btnEn) btnEn.disabled = false;
  8212. if (btnDis) btnDis.disabled = false;
  8213. if (btnRem) btnRem.disabled = false;
  8214. if (btnCom) btnCom.disabled = false;
  8215. } else if (tab === 'snbrs') {
  8216. renderOspfStaticNbrs();
  8217. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8218. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8219. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8220. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8221. if (btnEn) btnEn.disabled = false;
  8222. if (btnDis) btnDis.disabled = false;
  8223. if (btnRem) btnRem.disabled = false;
  8224. if (btnCom) btnCom.disabled = false;
  8225. }
  8226. }
  8227. // TAB 1: INSTANCES
  8228. function renderOspfInstances() {
  8229. const tbody = document.getElementById('ospf-instances-table-body');
  8230. if (!tbody) return;
  8231. const countEl = document.getElementById('ospf-instances-footer-count');
  8232. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8233. let list = state.ospfInstances || [];
  8234. if (filter) {
  8235. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8236. }
  8237. if (countEl) countEl.innerText = list.length;
  8238. const selId = state.selectedOspfRow?.instances;
  8239. tbody.innerHTML = list.map((inst, idx) => {
  8240. const isSel = inst.id === selId;
  8241. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8242. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8243. return `
  8244. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8245. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8246. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8247. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8248. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8249. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8250. </td>
  8251. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8252. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8253. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8254. </tr>
  8255. `;
  8256. }).join('');
  8257. }
  8258. // TAB 2: AREAS
  8259. function renderOspfAreas() {
  8260. const tbody = document.getElementById('ospf-areas-table-body');
  8261. if (!tbody) return;
  8262. const countEl = document.getElementById('ospf-areas-footer-count');
  8263. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8264. let list = state.ospfAreas || [];
  8265. if (filter) {
  8266. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8267. }
  8268. if (countEl) countEl.innerText = list.length;
  8269. const selId = state.selectedOspfRow?.areas;
  8270. tbody.innerHTML = list.map((a, idx) => {
  8271. const isSel = a.id === selId;
  8272. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8273. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8274. return `
  8275. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8276. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8277. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8278. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8279. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8280. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8281. </td>
  8282. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8283. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8284. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8285. </tr>
  8286. `;
  8287. }).join('');
  8288. }
  8289. // TAB 3: AREA RANGES
  8290. function renderOspfAreaRanges() {
  8291. const tbody = document.getElementById('ospf-ranges-table-body');
  8292. if (!tbody) return;
  8293. const countEl = document.getElementById('ospf-ranges-footer-count');
  8294. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8295. let list = state.ospfAreaRanges || [];
  8296. if (filter) {
  8297. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8298. }
  8299. if (countEl) countEl.innerText = list.length;
  8300. const selId = state.selectedOspfRow?.['area-ranges'];
  8301. tbody.innerHTML = list.map((r, idx) => {
  8302. const isSel = r.id === selId;
  8303. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8304. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8305. return `
  8306. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8307. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8308. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8309. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8310. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8311. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8312. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8313. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8314. </tr>
  8315. `;
  8316. }).join('');
  8317. }
  8318. // TAB 4: INTERFACE TEMPLATES
  8319. function renderOspfTemplates() {
  8320. const tbody = document.getElementById('ospf-templates-table-body');
  8321. if (!tbody) return;
  8322. const countEl = document.getElementById('ospf-templates-footer-count');
  8323. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8324. let list = state.ospfTemplates || [];
  8325. if (filter) {
  8326. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8327. }
  8328. if (countEl) countEl.innerText = list.length;
  8329. const selId = state.selectedOspfRow?.templates;
  8330. tbody.innerHTML = list.map((t, idx) => {
  8331. const isSel = t.id === selId;
  8332. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8333. const ifaces = t.interfaces || t.interface || 'all';
  8334. const nets = t.networks || t.network || '';
  8335. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8336. return `
  8337. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8338. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8339. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8340. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8341. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8342. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8343. </td>
  8344. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8345. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8346. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8347. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8348. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8349. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8350. </tr>
  8351. `;
  8352. }).join('');
  8353. }
  8354. // TAB 5: LIVE INTERFACES
  8355. function renderOspfLiveInterfaces() {
  8356. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8357. if (!tbody) return;
  8358. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8359. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8360. let list = state.ospfLiveInterfaces || [];
  8361. if (filter) {
  8362. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8363. }
  8364. if (countEl) countEl.innerText = list.length;
  8365. tbody.innerHTML = list.map(i => `
  8366. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8367. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8368. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8369. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8370. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8371. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8372. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8373. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8374. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8375. </tr>
  8376. `).join('');
  8377. }
  8378. // TAB 6: STATIC NEIGHBORS
  8379. function renderOspfStaticNbrs() {
  8380. const tbody = document.getElementById('ospf-snbrs-table-body');
  8381. if (!tbody) return;
  8382. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8383. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8384. let list = state.ospfStaticNbrs || [];
  8385. if (filter) {
  8386. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8387. }
  8388. if (countEl) countEl.innerText = list.length;
  8389. const selId = state.selectedOspfRow?.['static-nbrs'];
  8390. tbody.innerHTML = list.map((n, idx) => {
  8391. const isSel = n.id === selId;
  8392. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8393. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8394. return `
  8395. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8396. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8397. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8398. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8399. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8400. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8401. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8402. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8403. </tr>
  8404. `;
  8405. }).join('');
  8406. }
  8407. // TAB 7: LIVE NEIGHBORS
  8408. function renderOspfNeighbors() {
  8409. const tbody = document.getElementById('ospf-neighbors-table-body');
  8410. if (!tbody) return;
  8411. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8412. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8413. let list = state.ospfNeighbors || [];
  8414. if (filter) {
  8415. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8416. }
  8417. if (countEl) countEl.innerText = list.length;
  8418. tbody.innerHTML = list.map(n => `
  8419. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8420. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8421. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8422. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8423. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8424. </td>
  8425. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8426. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8427. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8428. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8429. </tr>
  8430. `).join('');
  8431. }
  8432. // TAB 8: LINK-STATE DATABASE (LSA)
  8433. function renderOspfLSA() {
  8434. const tbody = document.getElementById('ospf-lsa-table-body');
  8435. if (!tbody) return;
  8436. const countEl = document.getElementById('ospf-lsa-footer-count');
  8437. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8438. let list = state.ospfLSA || [];
  8439. if (filter) {
  8440. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8441. }
  8442. if (countEl) countEl.innerText = list.length;
  8443. tbody.innerHTML = list.map(l => `
  8444. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8445. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8446. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8447. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8448. </td>
  8449. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8450. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8451. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8452. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8453. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8454. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8455. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8456. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8457. </tr>
  8458. `).join('');
  8459. }
  8460. function renderOspfStatusPill() {
  8461. // Maintained for backward compatibility
  8462. const pill = document.getElementById('ospf-live-status-pill');
  8463. if (!pill) return;
  8464. 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';
  8465. pill.innerText = 'OSPF ACTIVE';
  8466. }
  8467. function renderOspfInterfaces() {
  8468. renderOspfTemplates();
  8469. }
  8470. function renderOspfRoutes() {
  8471. // Routes retained in background
  8472. }
  8473. // BGP Modals & Actions
  8474. function openBgpInstanceModal() {
  8475. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8476. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8477. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8478. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8479. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8480. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8481. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8482. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8483. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8484. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8485. }
  8486. function closeBgpInstanceModal() {
  8487. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8488. }
  8489. async function submitBgpInstance(e) {
  8490. e.preventDefault();
  8491. const payload = {
  8492. enabled: document.getElementById('modal-bgp-enabled').checked,
  8493. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8494. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8495. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8496. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8497. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8498. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8499. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8500. };
  8501. try {
  8502. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8503. method: 'POST',
  8504. headers: { 'Content-Type': 'application/json' },
  8505. body: JSON.stringify(payload)
  8506. });
  8507. if (res.ok) {
  8508. closeBgpInstanceModal();
  8509. showToast('Success', 'BGP instance configuration updated', 'success');
  8510. loadDynamicRouting();
  8511. } else {
  8512. const err = await res.json();
  8513. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8514. }
  8515. } catch (err) {
  8516. showToast('Error', err.message, 'error');
  8517. }
  8518. }
  8519. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8520. function switchBgpPeerModalTab(tab) {
  8521. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8522. tabs.forEach(t => {
  8523. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8524. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8525. if (t === tab) {
  8526. if (pane) pane.classList.remove('hidden');
  8527. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8528. } else {
  8529. if (pane) pane.classList.add('hidden');
  8530. 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';
  8531. }
  8532. });
  8533. }
  8534. function addOutputNetworkRow(val = '') {
  8535. const container = document.getElementById('modal-bgp-output-networks-container');
  8536. if (!container) return;
  8537. const row = document.createElement('div');
  8538. row.className = 'flex items-center gap-2 output-net-row';
  8539. row.innerHTML = `
  8540. <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">
  8541. <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>
  8542. `;
  8543. container.appendChild(row);
  8544. }
  8545. function parseBgpTime(val) {
  8546. if (!val) return 0;
  8547. val = String(val).trim();
  8548. if (val.includes(':')) {
  8549. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8550. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8551. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8552. }
  8553. return parseInt(val, 10) || 0;
  8554. }
  8555. function formatBgpTime(secs) {
  8556. if (!secs || secs <= 0) return '00:00:00';
  8557. const h = Math.floor(secs / 3600);
  8558. const m = Math.floor((secs % 3600) / 60);
  8559. const s = secs % 60;
  8560. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8561. }
  8562. function populateBgpRoutingTables() {
  8563. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8564. if (!sel) return;
  8565. const cur = sel.value || 'main';
  8566. sel.innerHTML = '<option value="main">main</option>';
  8567. (state.routingTables || []).forEach(t => {
  8568. if (t.name !== 'main') {
  8569. const opt = document.createElement('option');
  8570. opt.value = t.name;
  8571. opt.innerText = t.name;
  8572. sel.appendChild(opt);
  8573. }
  8574. });
  8575. sel.value = cur;
  8576. }
  8577. function openAddBgpPeerModal() {
  8578. document.getElementById('bgp-peer-form').reset();
  8579. document.getElementById('modal-bgp-peer-id').value = '';
  8580. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8581. // General Tab
  8582. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8583. document.getElementById('modal-bgp-peer-comment').value = '';
  8584. document.getElementById('modal-bgp-peer-name').value = '';
  8585. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8586. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8587. document.getElementById('modal-bgp-peer-local-as').value = '';
  8588. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8589. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8590. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8591. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8592. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8593. document.getElementById('modal-bgp-peer-router-id').value = '';
  8594. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8595. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8596. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8597. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8598. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8599. document.getElementById('modal-bgp-peer-local-port').value = '';
  8600. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8601. document.getElementById('modal-bgp-peer-password').value = '';
  8602. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8603. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8604. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8605. document.getElementById('modal-bgp-peer-connect').checked = true;
  8606. document.getElementById('modal-bgp-peer-listen').checked = true;
  8607. // Extra Tab
  8608. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8609. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8610. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8611. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8612. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8613. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8614. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8615. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8616. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8617. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8618. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8619. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8620. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8621. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8622. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8623. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8624. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8625. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8626. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8627. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8628. // Attributes Tab
  8629. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8630. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8631. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8632. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8633. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8634. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8635. // Filter Tab
  8636. populateFilterChainsDatalist();
  8637. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8638. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8639. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8640. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8641. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8642. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8643. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8644. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8645. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8646. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8647. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8648. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8649. populateBgpRoutingTables();
  8650. const container = document.getElementById('modal-bgp-output-networks-container');
  8651. if (container) {
  8652. container.innerHTML = '';
  8653. addOutputNetworkRow('');
  8654. }
  8655. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8656. if (removeBtn) removeBtn.classList.add('hidden');
  8657. switchBgpPeerModalTab('general');
  8658. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8659. }
  8660. function populateFilterChainsDatalist() {
  8661. const dl = document.getElementById('filter-chains-list');
  8662. if (!dl) return;
  8663. const chains = new Set();
  8664. (state.routingFilters || []).forEach(f => {
  8665. if (f.chain) chains.add(f.chain);
  8666. });
  8667. if (chains.size === 0) {
  8668. chains.add('awmn');
  8669. chains.add('bgp-in');
  8670. chains.add('bgp-out');
  8671. }
  8672. dl.innerHTML = '';
  8673. chains.forEach(c => {
  8674. const opt = document.createElement('option');
  8675. opt.value = c;
  8676. dl.appendChild(opt);
  8677. });
  8678. }
  8679. function openEditBgpPeerModal(id) {
  8680. const p = (state.bgpPeers || []).find(item => item.id === id);
  8681. if (!p) return;
  8682. populateBgpRoutingTables();
  8683. populateFilterChainsDatalist();
  8684. document.getElementById('modal-bgp-peer-id').value = p.id;
  8685. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8686. // General Tab
  8687. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8688. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8689. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8690. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8691. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8692. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8693. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8694. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8695. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8696. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8697. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8698. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8699. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8700. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8701. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8702. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8703. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8704. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8705. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8706. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8707. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8708. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8709. // Extra Tab
  8710. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8711. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8712. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8713. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8714. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8715. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8716. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8717. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8718. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8719. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8720. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8721. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8722. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8723. 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;
  8724. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8725. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8726. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8727. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8728. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8729. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8730. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8731. // Attributes Tab
  8732. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8733. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8734. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8735. 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;
  8736. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8737. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8738. // Filter Tab
  8739. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8740. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8741. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8742. 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 || '';
  8743. 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 || '';
  8744. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8745. 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 || '';
  8746. 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 || '';
  8747. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8748. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8749. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8750. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8751. // Output Networks
  8752. const container = document.getElementById('modal-bgp-output-networks-container');
  8753. if (container) {
  8754. container.innerHTML = '';
  8755. if (p.output_networks && p.output_networks.length > 0) {
  8756. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8757. } else {
  8758. addOutputNetworkRow('');
  8759. }
  8760. }
  8761. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8762. if (removeBtn) removeBtn.classList.remove('hidden');
  8763. switchBgpPeerModalTab('general');
  8764. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8765. }
  8766. function copyCurrentBgpPeer() {
  8767. document.getElementById('modal-bgp-peer-id').value = '';
  8768. const nameEl = document.getElementById('modal-bgp-peer-name');
  8769. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8770. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8771. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8772. if (removeBtn) removeBtn.classList.add('hidden');
  8773. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8774. }
  8775. function removeCurrentBgpPeer() {
  8776. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8777. if (!id) return;
  8778. deleteBgpPeer(id);
  8779. closeBgpPeerModal();
  8780. }
  8781. function closeBgpPeerModal() {
  8782. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8783. }
  8784. function getBgpPeerFormData() {
  8785. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8786. const outputNetworks = [];
  8787. netInputs.forEach(inp => {
  8788. const v = inp.value.trim();
  8789. if (v) outputNetworks.push(v);
  8790. });
  8791. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8792. return {
  8793. id: document.getElementById('modal-bgp-peer-id').value,
  8794. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8795. enabled: enabled,
  8796. disabled: !enabled,
  8797. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8798. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8799. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8800. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8801. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8802. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8803. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8804. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8805. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8806. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8807. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8808. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8809. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8810. password: document.getElementById('modal-bgp-peer-password').value,
  8811. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8812. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8813. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8814. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8815. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8816. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8817. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8818. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8819. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8820. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8821. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8822. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8823. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8824. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8825. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8826. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8827. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8828. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8829. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8830. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8831. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8832. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8833. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8834. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8835. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8836. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8837. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8838. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8839. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8840. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8841. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8842. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8843. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8844. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8845. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8846. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8847. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8848. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8849. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8850. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8851. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8852. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8853. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8854. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8855. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8856. output_networks: outputNetworks
  8857. };
  8858. }
  8859. async function submitBgpPeer(e) {
  8860. if (e) e.preventDefault();
  8861. const payload = getBgpPeerFormData();
  8862. try {
  8863. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8864. method: 'POST',
  8865. headers: { 'Content-Type': 'application/json' },
  8866. body: JSON.stringify(payload)
  8867. });
  8868. if (res.ok) {
  8869. closeBgpPeerModal();
  8870. showToast('Success', 'BGP Connection saved', 'success');
  8871. loadDynamicRouting();
  8872. } else {
  8873. const err = await res.json();
  8874. showToast('Error', err.error || 'Failed to save peer', 'error');
  8875. }
  8876. } catch (err) {
  8877. showToast('Error', err.message, 'error');
  8878. }
  8879. }
  8880. async function applyBgpPeerModal(e) {
  8881. if (e) e.preventDefault();
  8882. const payload = getBgpPeerFormData();
  8883. try {
  8884. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8885. method: 'POST',
  8886. headers: { 'Content-Type': 'application/json' },
  8887. body: JSON.stringify(payload)
  8888. });
  8889. if (res.ok) {
  8890. const data = await res.json();
  8891. if (data.peer && data.peer.id) {
  8892. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8893. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8894. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8895. }
  8896. showToast('Applied', 'BGP Connection applied', 'success');
  8897. loadDynamicRouting();
  8898. } else {
  8899. const err = await res.json();
  8900. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8901. }
  8902. } catch (err) {
  8903. showToast('Error', err.message, 'error');
  8904. }
  8905. }
  8906. async function deleteBgpPeer(id) {
  8907. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8908. try {
  8909. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8910. if (res.ok) {
  8911. showToast('Deleted', 'BGP peer removed', 'success');
  8912. loadDynamicRouting();
  8913. }
  8914. } catch (err) {
  8915. showToast('Error', err.message, 'error');
  8916. }
  8917. }
  8918. async function toggleBgpPeerState(id, disabled) {
  8919. try {
  8920. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8921. method: 'POST',
  8922. headers: { 'Content-Type': 'application/json' },
  8923. body: JSON.stringify({ disabled })
  8924. });
  8925. if (res.ok) {
  8926. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8927. loadDynamicRouting();
  8928. }
  8929. } catch (err) {
  8930. showToast('Error', err.message, 'error');
  8931. }
  8932. }
  8933. function openAddBgpNetworkModal() {
  8934. document.getElementById('bgp-network-form').reset();
  8935. document.getElementById('modal-bgp-net-id').value = '';
  8936. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8937. }
  8938. function closeBgpNetworkModal() {
  8939. document.getElementById('bgp-network-modal').classList.add('hidden');
  8940. }
  8941. async function submitBgpNetwork(e) {
  8942. e.preventDefault();
  8943. const payload = {
  8944. id: document.getElementById('modal-bgp-net-id').value,
  8945. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8946. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8947. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8948. };
  8949. try {
  8950. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8951. method: 'POST',
  8952. headers: { 'Content-Type': 'application/json' },
  8953. body: JSON.stringify(payload)
  8954. });
  8955. if (res.ok) {
  8956. closeBgpNetworkModal();
  8957. showToast('Success', 'BGP network advertisement saved', 'success');
  8958. loadDynamicRouting();
  8959. } else {
  8960. const err = await res.json();
  8961. showToast('Error', err.error || 'Failed to save network', 'error');
  8962. }
  8963. } catch (err) {
  8964. showToast('Error', err.message, 'error');
  8965. }
  8966. }
  8967. async function deleteBgpNetwork(id) {
  8968. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8969. try {
  8970. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8971. if (res.ok) {
  8972. showToast('Deleted', 'Network advertisement removed', 'success');
  8973. loadDynamicRouting();
  8974. }
  8975. } catch (err) {
  8976. showToast('Error', err.message, 'error');
  8977. }
  8978. }
  8979. // =========================================================================
  8980. // DEBTIK v7 OSPF MODALS & ACTIONS
  8981. // =========================================================================
  8982. // --- 1. OSPF INSTANCE ---
  8983. function openOspfInstanceModal(id = null) {
  8984. const isEdit = !!id;
  8985. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8986. id: '',
  8987. name: 'Default',
  8988. version: 2,
  8989. vrf: 'main',
  8990. router_id: '192.168.131.56',
  8991. routing_table: 'main',
  8992. enabled: true,
  8993. redistribute_connected: false,
  8994. redistribute_static: true,
  8995. redistribute_bgp: false,
  8996. comment: ''
  8997. };
  8998. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8999. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9000. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9001. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9002. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9003. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9004. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9005. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9006. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9007. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9008. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9009. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9010. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9011. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9012. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9013. }
  9014. function openEditOspfInstanceModal(id) {
  9015. openOspfInstanceModal(id);
  9016. }
  9017. function closeOspfInstanceModal() {
  9018. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9019. }
  9020. async function submitOspfInstance(e) {
  9021. if (e) e.preventDefault();
  9022. const payload = {
  9023. id: document.getElementById('modal-ospf-inst-id').value,
  9024. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9025. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9026. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9027. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9028. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9029. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9030. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9031. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9032. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9033. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9034. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9035. };
  9036. try {
  9037. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9038. method: 'POST',
  9039. headers: { 'Content-Type': 'application/json' },
  9040. body: JSON.stringify(payload)
  9041. });
  9042. if (res.ok) {
  9043. closeOspfInstanceModal();
  9044. showToast('Saved', 'OSPF instance updated', 'success');
  9045. loadDynamicRouting();
  9046. } else {
  9047. const err = await res.json();
  9048. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9049. }
  9050. } catch (err) {
  9051. showToast('Error', err.message, 'error');
  9052. }
  9053. }
  9054. function applyOspfInstanceForm() {
  9055. submitOspfInstance(null);
  9056. }
  9057. function copyOspfInstance() {
  9058. document.getElementById('modal-ospf-inst-id').value = '';
  9059. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9060. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9061. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9062. }
  9063. async function deleteCurrentOspfInstance() {
  9064. const id = document.getElementById('modal-ospf-inst-id').value;
  9065. if (!id) return;
  9066. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9067. try {
  9068. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9069. if (res.ok) {
  9070. closeOspfInstanceModal();
  9071. showToast('Removed', 'OSPF instance deleted', 'success');
  9072. loadDynamicRouting();
  9073. }
  9074. } catch (err) {
  9075. showToast('Error', err.message, 'error');
  9076. }
  9077. }
  9078. async function enableSelectedOspfInstance() {
  9079. const id = state.selectedOspfRow?.instances;
  9080. if (!id) return;
  9081. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9082. method: 'POST',
  9083. headers: { 'Content-Type': 'application/json' },
  9084. body: JSON.stringify({ disabled: false })
  9085. });
  9086. loadDynamicRouting();
  9087. }
  9088. async function disableSelectedOspfInstance() {
  9089. const id = state.selectedOspfRow?.instances;
  9090. if (!id) return;
  9091. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9092. method: 'POST',
  9093. headers: { 'Content-Type': 'application/json' },
  9094. body: JSON.stringify({ disabled: true })
  9095. });
  9096. loadDynamicRouting();
  9097. }
  9098. async function removeSelectedOspfInstance() {
  9099. const id = state.selectedOspfRow?.instances;
  9100. if (!id) return;
  9101. if (!confirm('Delete selected OSPF instance?')) return;
  9102. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9103. loadDynamicRouting();
  9104. }
  9105. async function promptCommentOspfInstance() {
  9106. const id = state.selectedOspfRow?.instances;
  9107. if (!id) return;
  9108. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9109. if (!inst) return;
  9110. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9111. if (comment === null) return;
  9112. inst.comment = comment;
  9113. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9114. method: 'POST',
  9115. headers: { 'Content-Type': 'application/json' },
  9116. body: JSON.stringify(inst)
  9117. });
  9118. loadDynamicRouting();
  9119. }
  9120. // --- 2. OSPF AREA ---
  9121. function populateOspfAreaDropdowns() {
  9122. const instSelect = document.getElementById('modal-ospf-area-instance');
  9123. if (instSelect) {
  9124. const cur = instSelect.value;
  9125. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9126. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9127. if (cur) instSelect.value = cur;
  9128. }
  9129. }
  9130. function openOspfAreaModal(id = null) {
  9131. const isEdit = !!id;
  9132. populateOspfAreaDropdowns();
  9133. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9134. id: '',
  9135. name: 'Default',
  9136. instance: 'Default',
  9137. area_id: '0.0.0.0',
  9138. area_type: 'default',
  9139. default_cost: 1,
  9140. no_summaries: false,
  9141. disabled: false,
  9142. comment: ''
  9143. };
  9144. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9145. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9146. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9147. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9148. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9149. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9150. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9151. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9152. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9153. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9154. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9155. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9156. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9157. }
  9158. function openEditOspfAreaModal(id) {
  9159. openOspfAreaModal(id);
  9160. }
  9161. function closeOspfAreaModal() {
  9162. document.getElementById('ospf-area-modal').classList.add('hidden');
  9163. }
  9164. async function submitOspfArea(e) {
  9165. if (e) e.preventDefault();
  9166. const payload = {
  9167. id: document.getElementById('modal-ospf-area-id').value,
  9168. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9169. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9170. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9171. area_type: document.getElementById('modal-ospf-area-type').value,
  9172. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9173. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9174. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9175. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9176. };
  9177. try {
  9178. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9179. method: 'POST',
  9180. headers: { 'Content-Type': 'application/json' },
  9181. body: JSON.stringify(payload)
  9182. });
  9183. if (res.ok) {
  9184. closeOspfAreaModal();
  9185. showToast('Saved', 'OSPF area saved', 'success');
  9186. loadDynamicRouting();
  9187. } else {
  9188. const err = await res.json();
  9189. showToast('Error', err.error || 'Failed to save area', 'error');
  9190. }
  9191. } catch (err) {
  9192. showToast('Error', err.message, 'error');
  9193. }
  9194. }
  9195. function applyOspfAreaForm() {
  9196. submitOspfArea(null);
  9197. }
  9198. function copyOspfArea() {
  9199. document.getElementById('modal-ospf-area-id').value = '';
  9200. document.getElementById('modal-ospf-area-name').value += '-copy';
  9201. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9202. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9203. }
  9204. async function deleteCurrentOspfArea() {
  9205. const id = document.getElementById('modal-ospf-area-id').value;
  9206. if (!id) return;
  9207. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9208. try {
  9209. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9210. if (res.ok) {
  9211. closeOspfAreaModal();
  9212. showToast('Removed', 'OSPF area deleted', 'success');
  9213. loadDynamicRouting();
  9214. }
  9215. } catch (err) {
  9216. showToast('Error', err.message, 'error');
  9217. }
  9218. }
  9219. async function enableSelectedOspfArea() {
  9220. const id = state.selectedOspfRow?.areas;
  9221. if (!id) return;
  9222. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9223. method: 'POST',
  9224. headers: { 'Content-Type': 'application/json' },
  9225. body: JSON.stringify({ disabled: false })
  9226. });
  9227. loadDynamicRouting();
  9228. }
  9229. async function disableSelectedOspfArea() {
  9230. const id = state.selectedOspfRow?.areas;
  9231. if (!id) return;
  9232. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9233. method: 'POST',
  9234. headers: { 'Content-Type': 'application/json' },
  9235. body: JSON.stringify({ disabled: true })
  9236. });
  9237. loadDynamicRouting();
  9238. }
  9239. async function removeSelectedOspfArea() {
  9240. const id = state.selectedOspfRow?.areas;
  9241. if (!id) return;
  9242. if (!confirm('Delete selected OSPF area?')) return;
  9243. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9244. loadDynamicRouting();
  9245. }
  9246. async function promptCommentOspfArea() {
  9247. const id = state.selectedOspfRow?.areas;
  9248. if (!id) return;
  9249. const area = (state.ospfAreas || []).find(a => a.id === id);
  9250. if (!area) return;
  9251. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9252. if (comment === null) return;
  9253. area.comment = comment;
  9254. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9255. method: 'POST',
  9256. headers: { 'Content-Type': 'application/json' },
  9257. body: JSON.stringify(area)
  9258. });
  9259. loadDynamicRouting();
  9260. }
  9261. // --- 3. OSPF AREA RANGE ---
  9262. function populateAreaRangeDropdowns() {
  9263. const select = document.getElementById('modal-ospf-range-area');
  9264. if (select) {
  9265. const cur = select.value;
  9266. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9267. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9268. if (cur) select.value = cur;
  9269. }
  9270. }
  9271. function openOspfAreaRangeModal(id = null) {
  9272. const isEdit = !!id;
  9273. populateAreaRangeDropdowns();
  9274. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9275. id: '',
  9276. area: 'Default',
  9277. prefix: '',
  9278. cost: 1,
  9279. advertise: true,
  9280. disabled: false,
  9281. comment: ''
  9282. };
  9283. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9284. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9285. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9286. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9287. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9288. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9289. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9290. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9291. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9292. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9293. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9294. }
  9295. function openEditOspfAreaRangeModal(id) {
  9296. openOspfAreaRangeModal(id);
  9297. }
  9298. function closeOspfAreaRangeModal() {
  9299. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9300. }
  9301. async function submitOspfAreaRange(e) {
  9302. if (e) e.preventDefault();
  9303. const payload = {
  9304. id: document.getElementById('modal-ospf-range-id').value,
  9305. area: document.getElementById('modal-ospf-range-area').value,
  9306. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9307. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9308. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9309. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9310. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9311. };
  9312. try {
  9313. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9314. method: 'POST',
  9315. headers: { 'Content-Type': 'application/json' },
  9316. body: JSON.stringify(payload)
  9317. });
  9318. if (res.ok) {
  9319. closeOspfAreaRangeModal();
  9320. showToast('Saved', 'Area range saved', 'success');
  9321. loadDynamicRouting();
  9322. } else {
  9323. const err = await res.json();
  9324. showToast('Error', err.error || 'Failed to save area range', 'error');
  9325. }
  9326. } catch (err) {
  9327. showToast('Error', err.message, 'error');
  9328. }
  9329. }
  9330. function applyOspfAreaRangeForm() {
  9331. submitOspfAreaRange(null);
  9332. }
  9333. async function deleteCurrentOspfAreaRange() {
  9334. const id = document.getElementById('modal-ospf-range-id').value;
  9335. if (!id) return;
  9336. if (!confirm('Delete this area range?')) return;
  9337. try {
  9338. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9339. closeOspfAreaRangeModal();
  9340. showToast('Removed', 'Area range removed', 'success');
  9341. loadDynamicRouting();
  9342. } catch (err) {
  9343. showToast('Error', err.message, 'error');
  9344. }
  9345. }
  9346. async function enableSelectedOspfAreaRange() {
  9347. const id = state.selectedOspfRow?.['area-ranges'];
  9348. if (!id) return;
  9349. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9350. if (!r) return;
  9351. r.disabled = false;
  9352. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9353. loadDynamicRouting();
  9354. }
  9355. async function disableSelectedOspfAreaRange() {
  9356. const id = state.selectedOspfRow?.['area-ranges'];
  9357. if (!id) return;
  9358. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9359. if (!r) return;
  9360. r.disabled = true;
  9361. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9362. loadDynamicRouting();
  9363. }
  9364. async function removeSelectedOspfAreaRange() {
  9365. const id = state.selectedOspfRow?.['area-ranges'];
  9366. if (!id) return;
  9367. if (!confirm('Delete selected area range?')) return;
  9368. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9369. loadDynamicRouting();
  9370. }
  9371. async function promptCommentOspfAreaRange() {
  9372. const id = state.selectedOspfRow?.['area-ranges'];
  9373. if (!id) return;
  9374. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9375. if (!r) return;
  9376. const comment = prompt('Enter comment for area range:', r.comment || '');
  9377. if (comment === null) return;
  9378. r.comment = comment;
  9379. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9380. loadDynamicRouting();
  9381. }
  9382. // --- 4. OSPF INTERFACE TEMPLATE ---
  9383. function switchOspfTemplateTab(tab) {
  9384. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9385. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9386. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9387. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9388. if (tab === 'general') {
  9389. if (tabGen) tabGen.classList.remove('hidden');
  9390. if (tabAuth) tabAuth.classList.add('hidden');
  9391. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9392. 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';
  9393. } else {
  9394. if (tabGen) tabGen.classList.add('hidden');
  9395. if (tabAuth) tabAuth.classList.remove('hidden');
  9396. 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';
  9397. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9398. }
  9399. }
  9400. function populateTemplateAreaDropdowns() {
  9401. const select = document.getElementById('modal-ospf-tmpl-area');
  9402. if (select) {
  9403. const cur = select.value;
  9404. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9405. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9406. if (cur) select.value = cur;
  9407. }
  9408. }
  9409. function openOspfTemplateModal(id = null) {
  9410. const isEdit = !!id;
  9411. populateTemplateAreaDropdowns();
  9412. switchOspfTemplateTab('general');
  9413. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9414. id: '',
  9415. interfaces: '',
  9416. area: 'Default',
  9417. networks: '',
  9418. network_type: 'broadcast',
  9419. cost: 1,
  9420. priority: 128,
  9421. passive: false,
  9422. hello_interval: 10,
  9423. dead_interval: 40,
  9424. auth: 'none',
  9425. auth_key: '',
  9426. disabled: false,
  9427. comment: ''
  9428. };
  9429. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9430. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9431. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9432. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9433. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9434. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9435. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9436. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9437. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9438. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9439. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9440. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9441. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9442. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9443. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9444. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9445. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9446. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9447. }
  9448. function openEditOspfTemplateModal(id) {
  9449. openOspfTemplateModal(id);
  9450. }
  9451. function closeOspfTemplateModal() {
  9452. document.getElementById('ospf-template-modal').classList.add('hidden');
  9453. }
  9454. async function submitOspfTemplate(e) {
  9455. if (e) e.preventDefault();
  9456. const payload = {
  9457. id: document.getElementById('modal-ospf-tmpl-id').value,
  9458. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9459. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9460. area: document.getElementById('modal-ospf-tmpl-area').value,
  9461. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9462. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9463. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9464. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9465. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9466. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9467. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9468. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9469. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9470. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9471. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9472. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9473. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9474. };
  9475. try {
  9476. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9477. method: 'POST',
  9478. headers: { 'Content-Type': 'application/json' },
  9479. body: JSON.stringify(payload)
  9480. });
  9481. if (res.ok) {
  9482. closeOspfTemplateModal();
  9483. showToast('Saved', 'Interface template saved', 'success');
  9484. loadDynamicRouting();
  9485. } else {
  9486. const err = await res.json();
  9487. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9488. }
  9489. } catch (err) {
  9490. showToast('Error', err.message, 'error');
  9491. }
  9492. }
  9493. function applyOspfTemplateForm() {
  9494. submitOspfTemplate(null);
  9495. }
  9496. function copyOspfTemplate() {
  9497. document.getElementById('modal-ospf-tmpl-id').value = '';
  9498. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9499. showToast('Copied', 'Duplicated as new template', 'info');
  9500. }
  9501. async function deleteCurrentOspfTemplate() {
  9502. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9503. if (!id) return;
  9504. if (!confirm('Delete this interface template?')) return;
  9505. try {
  9506. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9507. closeOspfTemplateModal();
  9508. showToast('Removed', 'Interface template deleted', 'success');
  9509. loadDynamicRouting();
  9510. } catch (err) {
  9511. showToast('Error', err.message, 'error');
  9512. }
  9513. }
  9514. async function enableSelectedOspfTemplate() {
  9515. const id = state.selectedOspfRow?.templates;
  9516. if (!id) return;
  9517. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9518. method: 'POST',
  9519. headers: { 'Content-Type': 'application/json' },
  9520. body: JSON.stringify({ disabled: false })
  9521. });
  9522. loadDynamicRouting();
  9523. }
  9524. async function disableSelectedOspfTemplate() {
  9525. const id = state.selectedOspfRow?.templates;
  9526. if (!id) return;
  9527. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9528. method: 'POST',
  9529. headers: { 'Content-Type': 'application/json' },
  9530. body: JSON.stringify({ disabled: true })
  9531. });
  9532. loadDynamicRouting();
  9533. }
  9534. async function removeSelectedOspfTemplate() {
  9535. const id = state.selectedOspfRow?.templates;
  9536. if (!id) return;
  9537. if (!confirm('Delete selected interface template?')) return;
  9538. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9539. loadDynamicRouting();
  9540. }
  9541. async function promptCommentOspfTemplate() {
  9542. const id = state.selectedOspfRow?.templates;
  9543. if (!id) return;
  9544. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9545. if (!tmpl) return;
  9546. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9547. if (comment === null) return;
  9548. tmpl.comment = comment;
  9549. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9550. method: 'POST',
  9551. headers: { 'Content-Type': 'application/json' },
  9552. body: JSON.stringify(tmpl)
  9553. });
  9554. loadDynamicRouting();
  9555. }
  9556. // --- 5. OSPF STATIC NEIGHBOR ---
  9557. function populateStaticNbrAreaDropdowns() {
  9558. const select = document.getElementById('modal-ospf-snbr-area');
  9559. if (select) {
  9560. const cur = select.value;
  9561. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9562. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9563. if (cur) select.value = cur;
  9564. }
  9565. }
  9566. function openOspfStaticNbrModal(id = null) {
  9567. const isEdit = !!id;
  9568. populateStaticNbrAreaDropdowns();
  9569. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9570. id: '',
  9571. address: '',
  9572. area: 'Default',
  9573. poll_interval: 120,
  9574. cost: 1,
  9575. disabled: false,
  9576. comment: ''
  9577. };
  9578. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9579. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9580. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9581. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9582. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9583. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9584. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9585. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9586. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9587. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9588. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9589. }
  9590. function openEditOspfStaticNbrModal(id) {
  9591. openOspfStaticNbrModal(id);
  9592. }
  9593. function closeOspfStaticNbrModal() {
  9594. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9595. }
  9596. async function submitOspfStaticNbr(e) {
  9597. if (e) e.preventDefault();
  9598. const payload = {
  9599. id: document.getElementById('modal-ospf-snbr-id').value,
  9600. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9601. area: document.getElementById('modal-ospf-snbr-area').value,
  9602. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9603. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9604. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9605. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9606. };
  9607. try {
  9608. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9609. method: 'POST',
  9610. headers: { 'Content-Type': 'application/json' },
  9611. body: JSON.stringify(payload)
  9612. });
  9613. if (res.ok) {
  9614. closeOspfStaticNbrModal();
  9615. showToast('Saved', 'Static neighbor saved', 'success');
  9616. loadDynamicRouting();
  9617. } else {
  9618. const err = await res.json();
  9619. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9620. }
  9621. } catch (err) {
  9622. showToast('Error', err.message, 'error');
  9623. }
  9624. }
  9625. function applyOspfStaticNbrForm() {
  9626. submitOspfStaticNbr(null);
  9627. }
  9628. async function deleteCurrentOspfStaticNbr() {
  9629. const id = document.getElementById('modal-ospf-snbr-id').value;
  9630. if (!id) return;
  9631. if (!confirm('Delete this static neighbor?')) return;
  9632. try {
  9633. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9634. closeOspfStaticNbrModal();
  9635. showToast('Removed', 'Static neighbor removed', 'success');
  9636. loadDynamicRouting();
  9637. } catch (err) {
  9638. showToast('Error', err.message, 'error');
  9639. }
  9640. }
  9641. async function enableSelectedOspfStaticNbr() {
  9642. const id = state.selectedOspfRow?.['static-nbrs'];
  9643. if (!id) return;
  9644. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9645. if (!n) return;
  9646. n.disabled = false;
  9647. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9648. loadDynamicRouting();
  9649. }
  9650. async function disableSelectedOspfStaticNbr() {
  9651. const id = state.selectedOspfRow?.['static-nbrs'];
  9652. if (!id) return;
  9653. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9654. if (!n) return;
  9655. n.disabled = true;
  9656. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9657. loadDynamicRouting();
  9658. }
  9659. async function removeSelectedOspfStaticNbr() {
  9660. const id = state.selectedOspfRow?.['static-nbrs'];
  9661. if (!id) return;
  9662. if (!confirm('Delete selected static neighbor?')) return;
  9663. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9664. loadDynamicRouting();
  9665. }
  9666. async function promptCommentOspfStaticNbr() {
  9667. const id = state.selectedOspfRow?.['static-nbrs'];
  9668. if (!id) return;
  9669. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9670. if (!n) return;
  9671. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9672. if (comment === null) return;
  9673. n.comment = comment;
  9674. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9675. loadDynamicRouting();
  9676. }
  9677. // Backward-compat aliases
  9678. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9679. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9680. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9681. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9682. function deleteOspfInterface(id) {
  9683. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9684. }
  9685. function toggleOspfInterfaceState(id, disabled) {
  9686. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9687. method: 'POST',
  9688. headers: { 'Content-Type': 'application/json' },
  9689. body: JSON.stringify({ disabled })
  9690. }).then(() => loadDynamicRouting());
  9691. }
  9692. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9693. function deleteOspfArea(id) {
  9694. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9695. }
  9696. // ============================================================================
  9697. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9698. // ============================================================================
  9699. function switchBridgeSubTab(tab) {
  9700. state.bridgeSubTab = tab;
  9701. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9702. tabs.forEach(t => {
  9703. const panel = document.getElementById(`bridge-subtab-${t}`);
  9704. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9705. if (panel) {
  9706. if (t === tab) panel.classList.remove('hidden');
  9707. else panel.classList.add('hidden');
  9708. }
  9709. if (btn) {
  9710. if (t === tab) {
  9711. 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';
  9712. } else {
  9713. 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';
  9714. }
  9715. }
  9716. });
  9717. const addBtn = document.getElementById('bridge-top-action-btn');
  9718. if (addBtn) {
  9719. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9720. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9721. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9722. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9723. }
  9724. if (tab === 'hosts') loadBridgeHosts();
  9725. setTimeout(initTableSorting, 50);
  9726. }
  9727. function openCurrentBridgeModal() {
  9728. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9729. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9730. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9731. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9732. }
  9733. async function loadBridge() {
  9734. try {
  9735. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9736. fetch(`${API_BASE}/bridge/bridges`),
  9737. fetch(`${API_BASE}/bridge/ports`),
  9738. fetch(`${API_BASE}/bridge/vlans`),
  9739. fetch(`${API_BASE}/bridge/summary`),
  9740. fetch(`${API_BASE}/vpn/eoip`),
  9741. fetch(`${API_BASE}/vlans`)
  9742. ]);
  9743. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9744. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9745. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9746. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9747. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9748. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9749. // Badges & Stats
  9750. const bBridges = document.getElementById('bridge-badge-bridges');
  9751. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9752. const bPorts = document.getElementById('bridge-badge-ports');
  9753. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9754. const bVlans = document.getElementById('bridge-badge-vlans');
  9755. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9756. const bHosts = document.getElementById('bridge-badge-hosts');
  9757. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9758. const sBr = document.getElementById('bridge-stat-bridges');
  9759. if (sBr) sBr.innerText = (state.bridges || []).length;
  9760. const sPorts = document.getElementById('bridge-stat-ports');
  9761. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9762. const sHosts = document.getElementById('bridge-stat-hosts');
  9763. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9764. renderBridges();
  9765. renderBridgePorts();
  9766. renderBridgeVLANs();
  9767. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9768. } catch (err) {
  9769. console.error('Failed to load bridge subsystem:', err);
  9770. }
  9771. }
  9772. // ----------------- Bridges -----------------
  9773. function renderBridges() {
  9774. const tbody = document.getElementById('bridge-table-body');
  9775. const empty = document.getElementById('bridge-empty-bridges');
  9776. const countBadge = document.getElementById('bridge-count-badge');
  9777. if (!tbody) return;
  9778. tbody.innerHTML = '';
  9779. const bridges = state.bridges || [];
  9780. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9781. if (bridges.length === 0) {
  9782. empty?.classList.remove('hidden');
  9783. return;
  9784. }
  9785. empty?.classList.add('hidden');
  9786. bridges.forEach((b, idx) => {
  9787. const tr = document.createElement('tr');
  9788. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9789. // Format IP addresses pill list
  9790. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9791. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9792. ipsHtml = b.ip_addresses.map(ip => `
  9793. <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">
  9794. <span>${ip}</span>
  9795. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9796. </span>
  9797. `).join(' ');
  9798. }
  9799. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9800. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9801. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9802. tr.innerHTML = `
  9803. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9804. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9805. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9806. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9807. </td>
  9808. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9809. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9810. <td class="py-2.5 px-3">
  9811. <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>
  9812. </td>
  9813. <td class="py-2.5 px-3 text-center">
  9814. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9815. </td>
  9816. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9817. <td class="py-2.5 px-3">
  9818. <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>
  9819. </td>
  9820. <td class="py-2.5 px-3">
  9821. <div class="flex items-center gap-1.5 flex-wrap">
  9822. ${ipsHtml}
  9823. <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>
  9824. </div>
  9825. </td>
  9826. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9827. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9828. </td>
  9829. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9830. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9831. <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>
  9832. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9833. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9834. </td>
  9835. `;
  9836. tbody.appendChild(tr);
  9837. });
  9838. }
  9839. function openAddBridgeModal() {
  9840. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9841. document.getElementById('bridge-modal-id').value = '';
  9842. document.getElementById('bridge-modal-name').value = 'bridge1';
  9843. document.getElementById('bridge-modal-name').disabled = false;
  9844. document.getElementById('bridge-modal-mtu').value = '1500';
  9845. document.getElementById('bridge-modal-mac').value = '';
  9846. document.getElementById('bridge-modal-stp').value = 'stp';
  9847. document.getElementById('bridge-modal-priority').value = '32768';
  9848. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9849. document.getElementById('bridge-modal-pvid').value = '1';
  9850. document.getElementById('bridge-modal-fastforward').checked = true;
  9851. document.getElementById('bridge-modal-comment').value = '';
  9852. document.getElementById('bridge-modal-disabled').checked = false;
  9853. toggleBridgeModalVlanFiltering();
  9854. document.getElementById('bridge-modal').classList.remove('hidden');
  9855. }
  9856. function openEditBridgeModal(id) {
  9857. const b = (state.bridges || []).find(x => x.id === id);
  9858. if (!b) return;
  9859. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9860. document.getElementById('bridge-modal-id').value = b.id;
  9861. document.getElementById('bridge-modal-name').value = b.name;
  9862. document.getElementById('bridge-modal-name').disabled = true;
  9863. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9864. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9865. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  9866. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9867. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9868. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9869. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9870. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9871. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9872. toggleBridgeModalVlanFiltering();
  9873. document.getElementById('bridge-modal').classList.remove('hidden');
  9874. }
  9875. function closeBridgeModal() {
  9876. document.getElementById('bridge-modal').classList.add('hidden');
  9877. }
  9878. function toggleBridgeModalVlanFiltering() {
  9879. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9880. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9881. if (pvidBox) {
  9882. if (chk) pvidBox.classList.remove('opacity-40');
  9883. else pvidBox.classList.add('opacity-40');
  9884. }
  9885. }
  9886. async function submitSaveBridge(e) {
  9887. e.preventDefault();
  9888. const id = document.getElementById('bridge-modal-id').value;
  9889. const name = document.getElementById('bridge-modal-name').value.trim();
  9890. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9891. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9892. const stp = document.getElementById('bridge-modal-stp').value;
  9893. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9894. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9895. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9896. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9897. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9898. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9899. try {
  9900. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9901. method: 'POST',
  9902. headers: { 'Content-Type': 'application/json' },
  9903. body: JSON.stringify({
  9904. id,
  9905. name,
  9906. mtu,
  9907. mac_address: mac,
  9908. stp,
  9909. priority,
  9910. vlan_filtering: vlanFiltering,
  9911. pvid,
  9912. fast_forward: fastForward,
  9913. comment,
  9914. disabled
  9915. })
  9916. });
  9917. if (res.ok) {
  9918. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9919. closeBridgeModal();
  9920. loadBridge();
  9921. fetchData(false);
  9922. } else {
  9923. const err = await res.json();
  9924. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9925. }
  9926. } catch (err) {
  9927. showToast('Error', err.message, 'error');
  9928. }
  9929. }
  9930. async function toggleBridgeState(id, disabled) {
  9931. try {
  9932. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9933. method: 'POST',
  9934. headers: { 'Content-Type': 'application/json' },
  9935. body: JSON.stringify({ disabled })
  9936. });
  9937. if (res.ok) {
  9938. loadBridge();
  9939. fetchData(false);
  9940. }
  9941. } catch (err) {
  9942. showToast('Error', err.message, 'error');
  9943. }
  9944. }
  9945. async function deleteBridge(id) {
  9946. const b = (state.bridges || []).find(x => x.id === id);
  9947. const name = b ? b.name : id;
  9948. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9949. try {
  9950. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9951. if (res.ok) {
  9952. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9953. loadBridge();
  9954. fetchData(false);
  9955. } else {
  9956. const err = await res.json();
  9957. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9958. }
  9959. } catch (err) {
  9960. showToast('Error', err.message, 'error');
  9961. }
  9962. }
  9963. // ----------------- Bridge IP Assignments -----------------
  9964. function openAddBridgeIPModal(id, name) {
  9965. document.getElementById('bridge-ip-modal-id').value = id;
  9966. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9967. document.getElementById('bridge-ip-modal-cidr').value = '';
  9968. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9969. }
  9970. function closeBridgeIPModal() {
  9971. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9972. }
  9973. async function submitAddBridgeIP(e) {
  9974. e.preventDefault();
  9975. const id = document.getElementById('bridge-ip-modal-id').value;
  9976. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9977. try {
  9978. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9979. method: 'POST',
  9980. headers: { 'Content-Type': 'application/json' },
  9981. body: JSON.stringify({ ip })
  9982. });
  9983. if (res.ok) {
  9984. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9985. closeBridgeIPModal();
  9986. loadBridge();
  9987. fetchData(false);
  9988. } else {
  9989. const err = await res.json();
  9990. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9991. }
  9992. } catch (err) {
  9993. showToast('Error', err.message, 'error');
  9994. }
  9995. }
  9996. async function deleteBridgeIP(id, ip) {
  9997. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9998. try {
  9999. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10000. method: 'DELETE',
  10001. headers: { 'Content-Type': 'application/json' },
  10002. body: JSON.stringify({ ip })
  10003. });
  10004. if (res.ok) {
  10005. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10006. loadBridge();
  10007. fetchData(false);
  10008. }
  10009. } catch (err) {
  10010. showToast('Error', err.message, 'error');
  10011. }
  10012. }
  10013. // ----------------- Bridge Ports -----------------
  10014. function renderBridgePorts() {
  10015. const tbody = document.getElementById('bridge-ports-table-body');
  10016. const empty = document.getElementById('bridge-empty-ports');
  10017. const countBadge = document.getElementById('bridge-ports-count-badge');
  10018. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10019. if (!tbody) return;
  10020. tbody.innerHTML = '';
  10021. // Update filter select
  10022. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10023. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10024. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10025. if (ports.length === 0) {
  10026. empty?.classList.remove('hidden');
  10027. return;
  10028. }
  10029. empty?.classList.add('hidden');
  10030. ports.forEach((p, idx) => {
  10031. const tr = document.createElement('tr');
  10032. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10033. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10034. tr.innerHTML = `
  10035. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10036. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10037. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10038. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10039. </td>
  10040. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10041. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10042. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10043. <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>
  10044. <td class="py-2.5 px-3">
  10045. ${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>'}
  10046. </td>
  10047. <td class="py-2.5 px-3">
  10048. <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>
  10049. </td>
  10050. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10051. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10052. <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>
  10053. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10054. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10055. </td>
  10056. `;
  10057. tbody.appendChild(tr);
  10058. });
  10059. }
  10060. function openAddBridgePortModal() {
  10061. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10062. document.getElementById('bridge-port-modal-id').value = '';
  10063. populateBridgeSelect('bridge-port-modal-bridge');
  10064. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10065. document.getElementById('bridge-port-modal-pvid').value = '1';
  10066. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10067. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10068. document.getElementById('bridge-port-modal-horizon').value = '0';
  10069. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10070. document.getElementById('bridge-port-modal-priority').value = '128';
  10071. document.getElementById('bridge-port-modal-learn').checked = true;
  10072. document.getElementById('bridge-port-modal-comment').value = '';
  10073. document.getElementById('bridge-port-modal-disabled').checked = false;
  10074. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10075. }
  10076. function openEditBridgePortModal(id) {
  10077. const p = (state.bridgePorts || []).find(x => x.id === id);
  10078. if (!p) return;
  10079. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10080. document.getElementById('bridge-port-modal-id').value = p.id;
  10081. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10082. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10083. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10084. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10085. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10086. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10087. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10088. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10089. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10090. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10091. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10092. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10093. }
  10094. function closeBridgePortModal() {
  10095. document.getElementById('bridge-port-modal').classList.add('hidden');
  10096. }
  10097. async function submitSaveBridgePort(e) {
  10098. e.preventDefault();
  10099. const id = document.getElementById('bridge-port-modal-id').value;
  10100. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10101. const iface = document.getElementById('bridge-port-modal-interface').value;
  10102. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10103. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10104. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10105. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10106. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10107. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10108. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10109. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10110. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10111. try {
  10112. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10113. method: 'POST',
  10114. headers: { 'Content-Type': 'application/json' },
  10115. body: JSON.stringify({
  10116. id,
  10117. bridge,
  10118. interface: iface,
  10119. pvid,
  10120. frame_types: frameTypes,
  10121. ingress_filtering: ingressFiltering,
  10122. horizon,
  10123. path_cost: pathCost,
  10124. priority,
  10125. learn,
  10126. comment,
  10127. disabled
  10128. })
  10129. });
  10130. if (res.ok) {
  10131. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10132. closeBridgePortModal();
  10133. loadBridge();
  10134. fetchData(false);
  10135. } else {
  10136. const err = await res.json();
  10137. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10138. }
  10139. } catch (err) {
  10140. showToast('Error', err.message, 'error');
  10141. }
  10142. }
  10143. async function toggleBridgePortState(id, disabled) {
  10144. try {
  10145. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10146. method: 'POST',
  10147. headers: { 'Content-Type': 'application/json' },
  10148. body: JSON.stringify({ disabled })
  10149. });
  10150. if (res.ok) {
  10151. loadBridge();
  10152. fetchData(false);
  10153. }
  10154. } catch (err) {
  10155. showToast('Error', err.message, 'error');
  10156. }
  10157. }
  10158. async function deleteBridgePort(id) {
  10159. const p = (state.bridgePorts || []).find(x => x.id === id);
  10160. const iface = p ? p.interface : id;
  10161. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10162. try {
  10163. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10164. if (res.ok) {
  10165. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10166. loadBridge();
  10167. fetchData(false);
  10168. }
  10169. } catch (err) {
  10170. showToast('Error', err.message, 'error');
  10171. }
  10172. }
  10173. // ----------------- Bridge VLANs -----------------
  10174. function renderBridgeVLANs() {
  10175. const tbody = document.getElementById('bridge-vlans-table-body');
  10176. const empty = document.getElementById('bridge-empty-vlans');
  10177. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10178. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10179. if (!tbody) return;
  10180. tbody.innerHTML = '';
  10181. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10182. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10183. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10184. if (vlans.length === 0) {
  10185. empty?.classList.remove('hidden');
  10186. return;
  10187. }
  10188. empty?.classList.add('hidden');
  10189. vlans.forEach((v, idx) => {
  10190. const tr = document.createElement('tr');
  10191. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10192. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10193. ? 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(' ')
  10194. : '<span class="text-slate-600">none</span>';
  10195. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10196. ? 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(' ')
  10197. : '<span class="text-slate-600">none</span>';
  10198. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10199. tr.innerHTML = `
  10200. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10201. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10202. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10203. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10204. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10205. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10206. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10207. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10208. <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>
  10209. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10210. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10211. </td>
  10212. `;
  10213. tbody.appendChild(tr);
  10214. });
  10215. }
  10216. function openAddBridgeVLANModal() {
  10217. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10218. document.getElementById('bridge-vlan-modal-id').value = '';
  10219. populateBridgeSelect('bridge-vlan-modal-bridge');
  10220. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10221. document.getElementById('bridge-vlan-modal-comment').value = '';
  10222. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10223. updateBridgeVlanPortCheckboxes();
  10224. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10225. }
  10226. function openEditBridgeVLANModal(id) {
  10227. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10228. if (!v) return;
  10229. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10230. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10231. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10232. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10233. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10234. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10235. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10236. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10237. }
  10238. function closeBridgeVlanModal() {
  10239. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10240. }
  10241. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10242. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10243. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10244. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10245. if (!taggedBox || !untaggedBox) return;
  10246. // Ports belonging to the selected bridge
  10247. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10248. if (memberPorts.length === 0) {
  10249. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10250. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10251. return;
  10252. }
  10253. taggedBox.innerHTML = memberPorts.map(p => `
  10254. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10255. <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">
  10256. <span>${p.interface}</span>
  10257. </label>
  10258. `).join('');
  10259. untaggedBox.innerHTML = memberPorts.map(p => `
  10260. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10261. <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">
  10262. <span>${p.interface}</span>
  10263. </label>
  10264. `).join('');
  10265. }
  10266. async function submitSaveBridgeVLAN(e) {
  10267. e.preventDefault();
  10268. const id = document.getElementById('bridge-vlan-modal-id').value;
  10269. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10270. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10271. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10272. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10273. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10274. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10275. try {
  10276. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10277. method: 'POST',
  10278. headers: { 'Content-Type': 'application/json' },
  10279. body: JSON.stringify({
  10280. id,
  10281. bridge,
  10282. vlan_ids: vlanIDs,
  10283. tagged,
  10284. untagged,
  10285. comment,
  10286. disabled
  10287. })
  10288. });
  10289. if (res.ok) {
  10290. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10291. closeBridgeVlanModal();
  10292. loadBridge();
  10293. } else {
  10294. const err = await res.json();
  10295. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10296. }
  10297. } catch (err) {
  10298. showToast('Error', err.message, 'error');
  10299. }
  10300. }
  10301. async function toggleBridgeVLANState(id, disabled) {
  10302. try {
  10303. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10304. method: 'POST',
  10305. headers: { 'Content-Type': 'application/json' },
  10306. body: JSON.stringify({ disabled })
  10307. });
  10308. if (res.ok) loadBridge();
  10309. } catch (err) {
  10310. showToast('Error', err.message, 'error');
  10311. }
  10312. }
  10313. async function deleteBridgeVLAN(id) {
  10314. if (!confirm('Delete this bridge VLAN entry?')) return;
  10315. try {
  10316. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10317. if (res.ok) {
  10318. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10319. loadBridge();
  10320. }
  10321. } catch (err) {
  10322. showToast('Error', err.message, 'error');
  10323. }
  10324. }
  10325. // ----------------- Hosts / MAC Table -----------------
  10326. async function loadBridgeHosts() {
  10327. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10328. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10329. try {
  10330. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10331. const res = await fetch(url);
  10332. if (res.ok) {
  10333. state.bridgeHosts = await res.json();
  10334. renderBridgeHosts();
  10335. }
  10336. } catch (err) {
  10337. console.error('Failed to load bridge hosts:', err);
  10338. }
  10339. }
  10340. function renderBridgeHosts() {
  10341. const tbody = document.getElementById('bridge-hosts-table-body');
  10342. const empty = document.getElementById('bridge-empty-hosts');
  10343. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10344. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10345. if (!tbody) return;
  10346. tbody.innerHTML = '';
  10347. const hosts = (state.bridgeHosts || []).filter(h => {
  10348. if (!search) return true;
  10349. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10350. });
  10351. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10352. if (hosts.length === 0) {
  10353. empty?.classList.remove('hidden');
  10354. return;
  10355. }
  10356. empty?.classList.add('hidden');
  10357. hosts.forEach(h => {
  10358. const tr = document.createElement('tr');
  10359. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10360. let flagBadges = '';
  10361. 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>';
  10362. 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>';
  10363. 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>';
  10364. tr.innerHTML = `
  10365. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10366. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10367. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10368. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10369. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10370. <td class="py-2.5 px-3">${flagBadges}</td>
  10371. `;
  10372. tbody.appendChild(tr);
  10373. });
  10374. }
  10375. async function flushBridgeHosts() {
  10376. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10377. if (!selBridge) {
  10378. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10379. return;
  10380. }
  10381. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10382. try {
  10383. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10384. method: 'POST',
  10385. headers: { 'Content-Type': 'application/json' },
  10386. body: JSON.stringify({ bridge: selBridge })
  10387. });
  10388. if (res.ok) {
  10389. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10390. loadBridgeHosts();
  10391. }
  10392. } catch (err) {
  10393. showToast('Error', err.message, 'error');
  10394. }
  10395. }
  10396. // ----------------- Helpers -----------------
  10397. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10398. const sel = document.getElementById(selectId);
  10399. if (!sel) return;
  10400. const prevVal = currentVal || sel.value;
  10401. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10402. (state.bridges || []).forEach(b => {
  10403. const opt = document.createElement('option');
  10404. opt.value = b.name;
  10405. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10406. if (b.name === prevVal) opt.selected = true;
  10407. sel.appendChild(opt);
  10408. });
  10409. }
  10410. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10411. const sel = document.getElementById(selectId);
  10412. if (!sel) return;
  10413. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10414. // 1. Physical Interfaces
  10415. const grpPhys = document.createElement('optgroup');
  10416. grpPhys.label = 'Physical Interfaces';
  10417. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10418. const opt = document.createElement('option');
  10419. opt.value = i.name;
  10420. opt.innerText = `${i.name} (${i.role || i.type})`;
  10421. if (i.name === currentVal) opt.selected = true;
  10422. grpPhys.appendChild(opt);
  10423. });
  10424. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10425. // 2. VLAN Sub-interfaces
  10426. const grpVlans = document.createElement('optgroup');
  10427. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10428. (state.vlans || []).forEach(v => {
  10429. const opt = document.createElement('option');
  10430. opt.value = v.name;
  10431. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10432. if (v.name === currentVal) opt.selected = true;
  10433. grpVlans.appendChild(opt);
  10434. });
  10435. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10436. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10437. const grpEoip = document.createElement('optgroup');
  10438. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10439. (state.eoipTunnels || []).forEach(t => {
  10440. const opt = document.createElement('option');
  10441. opt.value = t.name;
  10442. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10443. if (t.name === currentVal) opt.selected = true;
  10444. grpEoip.appendChild(opt);
  10445. });
  10446. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10447. }
  10448. // -------------------------------------------------------------
  10449. // DebTik Routing Filters Management (/routing filter)
  10450. // -------------------------------------------------------------
  10451. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10452. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10453. if (!state.rfSort) state.rfSort = {};
  10454. function switchRoutingFilterTab(tab) {
  10455. state.activeRoutingFilterTab = tab;
  10456. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10457. tabs.forEach(t => {
  10458. const btn = document.getElementById(`tab-rf-${t}`);
  10459. const content = document.getElementById(`tab-content-rf-${t}`);
  10460. if (btn) {
  10461. if (t === tab) {
  10462. 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';
  10463. } else {
  10464. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10465. }
  10466. }
  10467. if (content) {
  10468. if (t === tab) content.classList.remove('hidden');
  10469. else content.classList.add('hidden');
  10470. }
  10471. });
  10472. const chainContainer = document.getElementById('rf-chain-filter-container');
  10473. if (chainContainer) {
  10474. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10475. else chainContainer.classList.add('hidden');
  10476. }
  10477. renderRoutingFilters();
  10478. }
  10479. function selectFilterRow(tab, id) {
  10480. if (state.selectedFilterRow[tab] === id) {
  10481. delete state.selectedFilterRow[tab];
  10482. } else {
  10483. state.selectedFilterRow[tab] = id;
  10484. }
  10485. if (tab === 'rules') renderRoutingFilterRules();
  10486. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10487. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10488. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10489. }
  10490. function openRoutingFilterNewModal() {
  10491. const tab = state.activeRoutingFilterTab || 'rules';
  10492. if (tab === 'rules') openAddRoutingFilterModal();
  10493. else if (tab === 'select-rules') openAddSelectRuleModal();
  10494. else if (tab === 'community-lists') openAddCommunityListModal();
  10495. else if (tab === 'as-lists') openAddASListModal();
  10496. }
  10497. function toggleSelectedRoutingFilter(disabled) {
  10498. const tab = state.activeRoutingFilterTab || 'rules';
  10499. const id = state.selectedFilterRow[tab];
  10500. if (!id) {
  10501. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10502. return;
  10503. }
  10504. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10505. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10506. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10507. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10508. }
  10509. function removeSelectedRoutingFilter() {
  10510. const tab = state.activeRoutingFilterTab || 'rules';
  10511. const id = state.selectedFilterRow[tab];
  10512. if (!id) {
  10513. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10514. return;
  10515. }
  10516. if (tab === 'rules') deleteRoutingFilter(id);
  10517. else if (tab === 'select-rules') deleteSelectRule(id);
  10518. else if (tab === 'community-lists') deleteCommunityList(id);
  10519. else if (tab === 'as-lists') deleteASList(id);
  10520. }
  10521. function searchRoutingFilters(q) {
  10522. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10523. renderRoutingFilters();
  10524. }
  10525. function sortFilterTable(tab, col) {
  10526. if (!state.rfSort) state.rfSort = {};
  10527. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10528. if (state.rfSort[tab].col === col) {
  10529. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10530. } else {
  10531. state.rfSort[tab].col = col;
  10532. state.rfSort[tab].asc = true;
  10533. }
  10534. const asc = state.rfSort[tab].asc;
  10535. let list = [];
  10536. if (tab === 'rules') list = state.routingFilters || [];
  10537. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10538. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10539. else if (tab === 'as-lists') list = state.routingASLists || [];
  10540. list.sort((a, b) => {
  10541. let valA = a[col] ?? '';
  10542. let valB = b[col] ?? '';
  10543. if (col === 'flags') {
  10544. valA = a.disabled ? 'X' : 'A';
  10545. valB = b.disabled ? 'X' : 'A';
  10546. }
  10547. if (typeof valA === 'number' && typeof valB === 'number') {
  10548. return asc ? valA - valB : valB - valA;
  10549. }
  10550. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10551. });
  10552. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10553. allCols.forEach(c => {
  10554. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10555. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10556. });
  10557. if (tab === 'rules') renderRoutingFilterRules();
  10558. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10559. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10560. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10561. }
  10562. function renderRoutingFilters() {
  10563. const navBadge = document.getElementById('badge-filters-count');
  10564. const allRules = state.routingFilters || [];
  10565. if (navBadge) navBadge.innerText = allRules.length;
  10566. // Populate chain filter select options and datalist
  10567. const chainSelect = document.getElementById('routing-filter-chain-select');
  10568. const chainDatalist = document.getElementById('dl-routing-chains');
  10569. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10570. if (chainSelect) {
  10571. const currentVal = state.filterChainSelected || 'all';
  10572. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10573. uniqueChains.map(ch => {
  10574. const count = allRules.filter(r => r.chain === ch).length;
  10575. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10576. }).join('');
  10577. chainSelect.value = currentVal;
  10578. }
  10579. if (chainDatalist) {
  10580. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10581. }
  10582. renderRoutingFilterRules();
  10583. renderRoutingFilterSelectRules();
  10584. renderRoutingFilterCommunityLists();
  10585. renderRoutingFilterASLists();
  10586. }
  10587. function filterRoutingFiltersByChain(chain) {
  10588. state.filterChainSelected = chain;
  10589. renderRoutingFilters();
  10590. }
  10591. // -------------------------------------------------------------
  10592. // TAB 1: RULES (/routing filter rule)
  10593. // -------------------------------------------------------------
  10594. function renderRoutingFilterRules() {
  10595. const tbody = document.getElementById('routing-filter-rules-tbody');
  10596. if (!tbody) return;
  10597. const empty = document.getElementById('rf-rules-empty');
  10598. const statusCount = document.getElementById('rf-status-count');
  10599. let list = (state.routingFilters || []).slice();
  10600. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10601. list = list.filter(r => r.chain === state.filterChainSelected);
  10602. }
  10603. const q = state.rfSearchQuery;
  10604. if (q) {
  10605. list = list.filter(r =>
  10606. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10607. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10608. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10609. (r.comment && r.comment.toLowerCase().includes(q))
  10610. );
  10611. }
  10612. if (!state.rfSort?.['rules']) {
  10613. list.sort((a, b) => {
  10614. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10615. return (a.rule_order || 0) - (b.rule_order || 0);
  10616. });
  10617. }
  10618. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10619. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10620. }
  10621. if (list.length === 0) {
  10622. tbody.innerHTML = '';
  10623. if (empty) empty.classList.remove('hidden');
  10624. return;
  10625. }
  10626. if (empty) empty.classList.add('hidden');
  10627. tbody.innerHTML = list.map(r => {
  10628. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10629. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10630. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10631. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10632. let ruleDisplay = '';
  10633. if (r.rule && r.rule.trim() !== '') {
  10634. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10635. } else {
  10636. let conds = [];
  10637. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10638. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10639. let act = r.action || 'accept';
  10640. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10641. }
  10642. return `
  10643. <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'}">
  10644. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10645. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10646. <td class="py-2 px-3">
  10647. <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>
  10648. </td>
  10649. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10650. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10651. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10652. <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>
  10653. <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>
  10654. <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'}">
  10655. ${r.disabled ? 'Enable' : 'Disable'}
  10656. </button>
  10657. <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">
  10658. Edit
  10659. </button>
  10660. <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">
  10661. ✕
  10662. </button>
  10663. </td>
  10664. </tr>
  10665. `;
  10666. }).join('');
  10667. }
  10668. // -------------------------------------------------------------
  10669. // TAB 2: SELECT RULES (/routing filter select-rule)
  10670. // -------------------------------------------------------------
  10671. function renderRoutingFilterSelectRules() {
  10672. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10673. if (!tbody) return;
  10674. const empty = document.getElementById('rf-select-rules-empty');
  10675. const statusCount = document.getElementById('rf-status-count');
  10676. let list = (state.routingSelectRules || []).slice();
  10677. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10678. list = list.filter(r => r.chain === state.filterChainSelected);
  10679. }
  10680. const q = state.rfSearchQuery;
  10681. if (q) {
  10682. list = list.filter(r =>
  10683. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10684. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10685. (r.comment && r.comment.toLowerCase().includes(q))
  10686. );
  10687. }
  10688. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10689. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10690. }
  10691. if (list.length === 0) {
  10692. tbody.innerHTML = '';
  10693. if (empty) empty.classList.remove('hidden');
  10694. return;
  10695. }
  10696. if (empty) empty.classList.add('hidden');
  10697. tbody.innerHTML = list.map(r => {
  10698. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10699. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10700. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10701. return `
  10702. <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'}">
  10703. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10704. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10705. <td class="py-2 px-3">
  10706. <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>
  10707. </td>
  10708. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10709. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10710. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10711. <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'}">
  10712. ${r.disabled ? 'Enable' : 'Disable'}
  10713. </button>
  10714. <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">
  10715. Edit
  10716. </button>
  10717. <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">
  10718. ✕
  10719. </button>
  10720. </td>
  10721. </tr>
  10722. `;
  10723. }).join('');
  10724. }
  10725. // -------------------------------------------------------------
  10726. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10727. // -------------------------------------------------------------
  10728. function renderRoutingFilterCommunityLists() {
  10729. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10730. if (!tbody) return;
  10731. const empty = document.getElementById('rf-comm-lists-empty');
  10732. const statusCount = document.getElementById('rf-status-count');
  10733. let list = (state.routingCommunityLists || []).slice();
  10734. const q = state.rfSearchQuery;
  10735. if (q) {
  10736. list = list.filter(cl =>
  10737. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10738. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10739. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10740. );
  10741. }
  10742. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10743. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10744. }
  10745. if (list.length === 0) {
  10746. tbody.innerHTML = '';
  10747. if (empty) empty.classList.remove('hidden');
  10748. return;
  10749. }
  10750. if (empty) empty.classList.add('hidden');
  10751. tbody.innerHTML = list.map(cl => {
  10752. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10753. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10754. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10755. const commBadges = (cl.communities || []).map(c =>
  10756. `<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>`
  10757. ).join(' ');
  10758. return `
  10759. <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'}">
  10760. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10761. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10762. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10763. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10764. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10765. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10766. <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'}">
  10767. ${cl.disabled ? 'Enable' : 'Disable'}
  10768. </button>
  10769. <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">
  10770. Edit
  10771. </button>
  10772. <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">
  10773. ✕
  10774. </button>
  10775. </td>
  10776. </tr>
  10777. `;
  10778. }).join('');
  10779. }
  10780. // -------------------------------------------------------------
  10781. // TAB 4: AS LISTS (/routing filter num-list)
  10782. // -------------------------------------------------------------
  10783. function renderRoutingFilterASLists() {
  10784. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10785. if (!tbody) return;
  10786. const empty = document.getElementById('rf-as-lists-empty');
  10787. const statusCount = document.getElementById('rf-status-count');
  10788. let list = (state.routingASLists || []).slice();
  10789. const q = state.rfSearchQuery;
  10790. if (q) {
  10791. list = list.filter(al =>
  10792. (al.name && al.name.toLowerCase().includes(q)) ||
  10793. (al.range && al.range.toLowerCase().includes(q)) ||
  10794. (al.comment && al.comment.toLowerCase().includes(q))
  10795. );
  10796. }
  10797. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10798. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10799. }
  10800. if (list.length === 0) {
  10801. tbody.innerHTML = '';
  10802. if (empty) empty.classList.remove('hidden');
  10803. return;
  10804. }
  10805. if (empty) empty.classList.add('hidden');
  10806. tbody.innerHTML = list.map(al => {
  10807. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10808. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10809. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10810. return `
  10811. <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'}">
  10812. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10813. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10814. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10815. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10816. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10817. <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'}">
  10818. ${al.disabled ? 'Enable' : 'Disable'}
  10819. </button>
  10820. <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">
  10821. Edit
  10822. </button>
  10823. <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">
  10824. ✕
  10825. </button>
  10826. </td>
  10827. </tr>
  10828. `;
  10829. }).join('');
  10830. }
  10831. // -------------------------------------------------------------
  10832. // SNIPPETS & WIZARD HELPERS
  10833. // -------------------------------------------------------------
  10834. function insertRuleSnippet(type) {
  10835. const textarea = document.getElementById('modal-rf-rule');
  10836. if (!textarea) return;
  10837. let snippet = '';
  10838. switch (type) {
  10839. case 'accept-default':
  10840. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10841. break;
  10842. case 'drop-rfc1918':
  10843. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10844. break;
  10845. case 'len-24':
  10846. snippet = 'if (dst-len > 24) { reject; }';
  10847. break;
  10848. case 'local-pref-150':
  10849. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10850. break;
  10851. case 'as-prepend-2':
  10852. snippet = 'set bgp-path-prepend 2; accept;';
  10853. break;
  10854. case 'set-comm':
  10855. snippet = 'set bgp-communities.add 65000:100; accept;';
  10856. break;
  10857. case 'match-comm':
  10858. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10859. break;
  10860. case 'reject-all':
  10861. snippet = 'reject;';
  10862. break;
  10863. }
  10864. if (!snippet) return;
  10865. if (!textarea.value.trim()) {
  10866. textarea.value = snippet;
  10867. } else {
  10868. textarea.value = textarea.value.trim() + '\n' + snippet;
  10869. }
  10870. }
  10871. function generateScriptFromWizard() {
  10872. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10873. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10874. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10875. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10876. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10877. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10878. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10879. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10880. const conds = [];
  10881. if (pfx) {
  10882. if (pfxLen) {
  10883. if (pfxLen.includes('-')) {
  10884. const parts = pfxLen.split('-');
  10885. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10886. } else {
  10887. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10888. }
  10889. } else {
  10890. conds.push(`dst in ${pfx}`);
  10891. }
  10892. }
  10893. if (proto && proto !== 'any') {
  10894. conds.push(`protocol ${proto}`);
  10895. }
  10896. if (asp) {
  10897. conds.push(`bgp-as-path "${asp}"`);
  10898. }
  10899. if (comm) {
  10900. conds.push(`bgp-communities includes ${comm}`);
  10901. }
  10902. const actions = [];
  10903. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10904. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10905. actions.push(`${act};`);
  10906. let code = '';
  10907. if (conds.length > 0) {
  10908. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10909. } else {
  10910. code = actions.join(' ');
  10911. }
  10912. const textarea = document.getElementById('modal-rf-rule');
  10913. if (textarea) textarea.value = code;
  10914. }
  10915. // -------------------------------------------------------------
  10916. // MODAL CRUD: RULES (/routing filter rule)
  10917. // -------------------------------------------------------------
  10918. function openAddRoutingFilterModal(defaultChain = '') {
  10919. const form = document.getElementById('routing-filter-form');
  10920. if (form) form.reset();
  10921. const idEl = document.getElementById('modal-rf-id');
  10922. if (idEl) idEl.value = '';
  10923. const titleEl = document.getElementById('modal-rf-title');
  10924. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10925. const chainEl = document.getElementById('modal-rf-chain');
  10926. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10927. const orderEl = document.getElementById('modal-rf-order');
  10928. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10929. const ruleEl = document.getElementById('modal-rf-rule');
  10930. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10931. const disEl = document.getElementById('modal-rf-disabled');
  10932. if (disEl) disEl.checked = false;
  10933. const modal = document.getElementById('modal-routing-filter');
  10934. if (modal) modal.classList.remove('hidden');
  10935. }
  10936. function openEditRoutingFilterModal(id) {
  10937. const r = (state.routingFilters || []).find(item => item.id === id);
  10938. if (!r) return;
  10939. const idEl = document.getElementById('modal-rf-id');
  10940. if (idEl) idEl.value = r.id;
  10941. const titleEl = document.getElementById('modal-rf-title');
  10942. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10943. const chainEl = document.getElementById('modal-rf-chain');
  10944. if (chainEl) chainEl.value = r.chain || '';
  10945. const orderEl = document.getElementById('modal-rf-order');
  10946. if (orderEl) orderEl.value = r.rule_order || 10;
  10947. const ruleEl = document.getElementById('modal-rf-rule');
  10948. if (ruleEl) {
  10949. if (r.rule) {
  10950. ruleEl.value = r.rule;
  10951. } else {
  10952. let conds = [];
  10953. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10954. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10955. let act = r.action || 'accept';
  10956. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10957. }
  10958. }
  10959. const comEl = document.getElementById('modal-rf-comment');
  10960. if (comEl) comEl.value = r.comment || '';
  10961. const disEl = document.getElementById('modal-rf-disabled');
  10962. if (disEl) disEl.checked = !!r.disabled;
  10963. const modal = document.getElementById('modal-routing-filter');
  10964. if (modal) modal.classList.remove('hidden');
  10965. }
  10966. function closeRoutingFilterModal() {
  10967. const modal = document.getElementById('modal-routing-filter');
  10968. if (modal) modal.classList.add('hidden');
  10969. }
  10970. async function submitRoutingFilter(e) {
  10971. if (e) e.preventDefault();
  10972. const payload = {
  10973. id: document.getElementById('modal-rf-id').value,
  10974. chain: document.getElementById('modal-rf-chain').value.trim(),
  10975. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10976. rule: document.getElementById('modal-rf-rule').value.trim(),
  10977. comment: document.getElementById('modal-rf-comment').value.trim(),
  10978. disabled: document.getElementById('modal-rf-disabled').checked
  10979. };
  10980. try {
  10981. const res = await fetch(`${API_BASE}/routing/filters`, {
  10982. method: 'POST',
  10983. headers: { 'Content-Type': 'application/json' },
  10984. body: JSON.stringify(payload)
  10985. });
  10986. if (res.ok) {
  10987. closeRoutingFilterModal();
  10988. showToast('Success', 'Routing filter rule saved', 'success');
  10989. loadDynamicRouting();
  10990. } else {
  10991. const err = await res.json();
  10992. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10993. }
  10994. } catch (err) {
  10995. showToast('Error', err.message, 'error');
  10996. }
  10997. }
  10998. async function applyRoutingFilterForm() {
  10999. const payload = {
  11000. id: document.getElementById('modal-rf-id').value,
  11001. chain: document.getElementById('modal-rf-chain').value.trim(),
  11002. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11003. rule: document.getElementById('modal-rf-rule').value.trim(),
  11004. comment: document.getElementById('modal-rf-comment').value.trim(),
  11005. disabled: document.getElementById('modal-rf-disabled').checked
  11006. };
  11007. try {
  11008. const res = await fetch(`${API_BASE}/routing/filters`, {
  11009. method: 'POST',
  11010. headers: { 'Content-Type': 'application/json' },
  11011. body: JSON.stringify(payload)
  11012. });
  11013. if (res.ok) {
  11014. const data = await res.json();
  11015. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11016. showToast('Applied', 'Routing filter configuration applied', 'success');
  11017. loadDynamicRouting();
  11018. } else {
  11019. const err = await res.json();
  11020. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11021. }
  11022. } catch (err) {
  11023. showToast('Error', err.message, 'error');
  11024. }
  11025. }
  11026. async function moveRoutingFilterOrder(id, delta) {
  11027. const list = state.routingFilters || [];
  11028. const idx = list.findIndex(r => r.id === id);
  11029. if (idx < 0) return;
  11030. const targetIdx = idx + delta;
  11031. if (targetIdx < 0 || targetIdx >= list.length) return;
  11032. const currentOrder = list[idx].rule_order || 10;
  11033. const targetOrder = list[targetIdx].rule_order || 20;
  11034. list[idx].rule_order = targetOrder;
  11035. list[targetIdx].rule_order = currentOrder;
  11036. try {
  11037. await fetch(`${API_BASE}/routing/filters`, {
  11038. method: 'POST',
  11039. headers: { 'Content-Type': 'application/json' },
  11040. body: JSON.stringify(list[idx])
  11041. });
  11042. await fetch(`${API_BASE}/routing/filters`, {
  11043. method: 'POST',
  11044. headers: { 'Content-Type': 'application/json' },
  11045. body: JSON.stringify(list[targetIdx])
  11046. });
  11047. loadDynamicRouting();
  11048. } catch (e) {
  11049. console.error('Reorder error:', e);
  11050. }
  11051. }
  11052. async function deleteRoutingFilter(id) {
  11053. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11054. try {
  11055. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11056. if (res.ok) {
  11057. showToast('Deleted', 'Routing filter rule removed', 'info');
  11058. loadDynamicRouting();
  11059. } else {
  11060. const err = await res.json();
  11061. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11062. }
  11063. } catch (err) {
  11064. showToast('Error', err.message, 'error');
  11065. }
  11066. }
  11067. async function toggleRoutingFilterState(id, disabled) {
  11068. try {
  11069. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11070. method: 'POST',
  11071. headers: { 'Content-Type': 'application/json' },
  11072. body: JSON.stringify({ disabled })
  11073. });
  11074. if (res.ok) {
  11075. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11076. loadDynamicRouting();
  11077. } else {
  11078. const err = await res.json();
  11079. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11080. }
  11081. } catch (err) {
  11082. showToast('Error', err.message, 'error');
  11083. }
  11084. }
  11085. // -------------------------------------------------------------
  11086. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11087. // -------------------------------------------------------------
  11088. function openAddSelectRuleModal() {
  11089. document.getElementById('modal-rf-sr-id').value = '';
  11090. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11091. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11092. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11093. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11094. document.getElementById('modal-rf-sr-comment').value = '';
  11095. document.getElementById('modal-rf-sr-disabled').checked = false;
  11096. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11097. }
  11098. function openEditSelectRuleModal(id) {
  11099. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11100. if (!r) return;
  11101. document.getElementById('modal-rf-sr-id').value = r.id;
  11102. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11103. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11104. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11105. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11106. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11107. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11108. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11109. }
  11110. function closeSelectRuleModal() {
  11111. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11112. }
  11113. async function submitSelectRule(e) {
  11114. e.preventDefault();
  11115. const payload = {
  11116. id: document.getElementById('modal-rf-sr-id').value,
  11117. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11118. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11119. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11120. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11121. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11122. };
  11123. try {
  11124. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11125. method: 'POST',
  11126. headers: { 'Content-Type': 'application/json' },
  11127. body: JSON.stringify(payload)
  11128. });
  11129. if (res.ok) {
  11130. closeSelectRuleModal();
  11131. showToast('Success', 'Select rule saved', 'success');
  11132. loadDynamicRouting();
  11133. } else {
  11134. const err = await res.json();
  11135. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11136. }
  11137. } catch (err) {
  11138. showToast('Error', err.message, 'error');
  11139. }
  11140. }
  11141. async function deleteSelectRule(id) {
  11142. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11143. try {
  11144. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11145. if (res.ok) {
  11146. showToast('Deleted', 'Select rule removed', 'info');
  11147. loadDynamicRouting();
  11148. } else {
  11149. const err = await res.json();
  11150. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11151. }
  11152. } catch (err) {
  11153. showToast('Error', err.message, 'error');
  11154. }
  11155. }
  11156. async function toggleSelectRuleState(id, disabled) {
  11157. try {
  11158. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11159. method: 'POST',
  11160. headers: { 'Content-Type': 'application/json' },
  11161. body: JSON.stringify({ disabled })
  11162. });
  11163. if (res.ok) {
  11164. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11165. loadDynamicRouting();
  11166. } else {
  11167. const err = await res.json();
  11168. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11169. }
  11170. } catch (err) {
  11171. showToast('Error', err.message, 'error');
  11172. }
  11173. }
  11174. // -------------------------------------------------------------
  11175. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11176. // -------------------------------------------------------------
  11177. function openAddCommunityListModal() {
  11178. document.getElementById('modal-rf-cl-id').value = '';
  11179. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11180. document.getElementById('modal-rf-cl-name').value = '';
  11181. document.getElementById('modal-rf-cl-communities').value = '';
  11182. document.getElementById('modal-rf-cl-regexp').value = '';
  11183. document.getElementById('modal-rf-cl-comment').value = '';
  11184. document.getElementById('modal-rf-cl-disabled').checked = false;
  11185. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11186. }
  11187. function openEditCommunityListModal(id) {
  11188. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11189. if (!cl) return;
  11190. document.getElementById('modal-rf-cl-id').value = cl.id;
  11191. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11192. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11193. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11194. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11195. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11196. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11197. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11198. }
  11199. function closeCommunityListModal() {
  11200. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11201. }
  11202. async function submitCommunityList(e) {
  11203. e.preventDefault();
  11204. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11205. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11206. const payload = {
  11207. id: document.getElementById('modal-rf-cl-id').value,
  11208. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11209. communities: comms,
  11210. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11211. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11212. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11213. };
  11214. try {
  11215. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11216. method: 'POST',
  11217. headers: { 'Content-Type': 'application/json' },
  11218. body: JSON.stringify(payload)
  11219. });
  11220. if (res.ok) {
  11221. closeCommunityListModal();
  11222. showToast('Success', 'Community list saved', 'success');
  11223. loadDynamicRouting();
  11224. } else {
  11225. const err = await res.json();
  11226. showToast('Error', err.error || 'Failed to save community list', 'error');
  11227. }
  11228. } catch (err) {
  11229. showToast('Error', err.message, 'error');
  11230. }
  11231. }
  11232. async function deleteCommunityList(id) {
  11233. if (!confirm('Are you sure you want to delete this community list?')) return;
  11234. try {
  11235. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11236. if (res.ok) {
  11237. showToast('Deleted', 'Community list removed', 'info');
  11238. loadDynamicRouting();
  11239. } else {
  11240. const err = await res.json();
  11241. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11242. }
  11243. } catch (err) {
  11244. showToast('Error', err.message, 'error');
  11245. }
  11246. }
  11247. async function toggleCommunityListState(id, disabled) {
  11248. try {
  11249. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11250. method: 'POST',
  11251. headers: { 'Content-Type': 'application/json' },
  11252. body: JSON.stringify({ disabled })
  11253. });
  11254. if (res.ok) {
  11255. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11256. loadDynamicRouting();
  11257. } else {
  11258. const err = await res.json();
  11259. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11260. }
  11261. } catch (err) {
  11262. showToast('Error', err.message, 'error');
  11263. }
  11264. }
  11265. // -------------------------------------------------------------
  11266. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11267. // -------------------------------------------------------------
  11268. function openAddASListModal() {
  11269. document.getElementById('modal-rf-al-id').value = '';
  11270. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11271. document.getElementById('modal-rf-al-name').value = '';
  11272. document.getElementById('modal-rf-al-range').value = '';
  11273. document.getElementById('modal-rf-al-comment').value = '';
  11274. document.getElementById('modal-rf-al-disabled').checked = false;
  11275. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11276. }
  11277. function openEditASListModal(id) {
  11278. const al = (state.routingASLists || []).find(item => item.id === id);
  11279. if (!al) return;
  11280. document.getElementById('modal-rf-al-id').value = al.id;
  11281. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11282. document.getElementById('modal-rf-al-name').value = al.name || '';
  11283. document.getElementById('modal-rf-al-range').value = al.range || '';
  11284. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11285. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11286. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11287. }
  11288. function closeASListModal() {
  11289. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11290. }
  11291. async function submitASList(e) {
  11292. e.preventDefault();
  11293. const payload = {
  11294. id: document.getElementById('modal-rf-al-id').value,
  11295. name: document.getElementById('modal-rf-al-name').value.trim(),
  11296. range: document.getElementById('modal-rf-al-range').value.trim(),
  11297. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11298. disabled: document.getElementById('modal-rf-al-disabled').checked
  11299. };
  11300. try {
  11301. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11302. method: 'POST',
  11303. headers: { 'Content-Type': 'application/json' },
  11304. body: JSON.stringify(payload)
  11305. });
  11306. if (res.ok) {
  11307. closeASListModal();
  11308. showToast('Success', 'AS number list saved', 'success');
  11309. loadDynamicRouting();
  11310. } else {
  11311. const err = await res.json();
  11312. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11313. }
  11314. } catch (err) {
  11315. showToast('Error', err.message, 'error');
  11316. }
  11317. }
  11318. async function deleteASList(id) {
  11319. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11320. try {
  11321. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11322. if (res.ok) {
  11323. showToast('Deleted', 'AS list removed', 'info');
  11324. loadDynamicRouting();
  11325. } else {
  11326. const err = await res.json();
  11327. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11328. }
  11329. } catch (err) {
  11330. showToast('Error', err.message, 'error');
  11331. }
  11332. }
  11333. async function toggleASListState(id, disabled) {
  11334. try {
  11335. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11336. method: 'POST',
  11337. headers: { 'Content-Type': 'application/json' },
  11338. body: JSON.stringify({ disabled })
  11339. });
  11340. if (res.ok) {
  11341. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11342. loadDynamicRouting();
  11343. } else {
  11344. const err = await res.json();
  11345. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11346. }
  11347. } catch (err) {
  11348. showToast('Error', err.message, 'error');
  11349. }
  11350. }
  11351. // ==========================================
  11352. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11353. // ==========================================
  11354. function loadToolsView() {
  11355. populateToolsInterfaces();
  11356. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11357. }
  11358. function populateToolsInterfaces() {
  11359. const pingSel = document.getElementById('tools-ping-iface');
  11360. const traceSel = document.getElementById('tools-tr-iface');
  11361. let opts = '<option value="">Auto (Default Route)</option>';
  11362. if (Array.isArray(state.interfaces)) {
  11363. state.interfaces.forEach(iface => {
  11364. if (iface.name) {
  11365. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11366. }
  11367. });
  11368. }
  11369. if (pingSel) {
  11370. const cur = pingSel.value;
  11371. pingSel.innerHTML = opts;
  11372. if (cur) pingSel.value = cur;
  11373. }
  11374. if (traceSel) {
  11375. const cur = traceSel.value;
  11376. traceSel.innerHTML = opts;
  11377. if (cur) traceSel.value = cur;
  11378. }
  11379. }
  11380. function switchToolsSubTab(subTab) {
  11381. state.activeToolsSubTab = subTab;
  11382. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11383. tabs.forEach(t => {
  11384. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11385. const view = document.getElementById(`tools-view-${t}`);
  11386. if (btn) {
  11387. if (t === subTab) {
  11388. 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';
  11389. } else {
  11390. 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';
  11391. }
  11392. }
  11393. if (view) {
  11394. if (t === subTab) {
  11395. view.classList.remove('hidden');
  11396. } else {
  11397. view.classList.add('hidden');
  11398. }
  11399. }
  11400. });
  11401. }
  11402. function setPortPreset(port) {
  11403. const input = document.getElementById('tools-port-num');
  11404. if (input) input.value = port;
  11405. }
  11406. let pingAbortController = null;
  11407. let tracerouteAbortController = null;
  11408. function clearPingTable() {
  11409. const tbody = document.getElementById('tools-ping-tbody');
  11410. if (tbody) tbody.innerHTML = '';
  11411. const rawEl = document.getElementById('tools-ping-raw');
  11412. if (rawEl) rawEl.innerText = '';
  11413. const sentEl = document.getElementById('tools-ping-stat-sent');
  11414. if (sentEl) sentEl.innerText = '0';
  11415. const recvEl = document.getElementById('tools-ping-stat-recv');
  11416. if (recvEl) recvEl.innerText = '0';
  11417. const lossEl = document.getElementById('tools-ping-stat-loss');
  11418. if (lossEl) lossEl.innerText = '0%';
  11419. const avgEl = document.getElementById('tools-ping-stat-avg');
  11420. if (avgEl) avgEl.innerText = '0 ms';
  11421. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11422. if (minMaxEl) minMaxEl.innerText = '-';
  11423. const badge = document.getElementById('tools-ping-status-badge');
  11424. if (badge) {
  11425. badge.className = '';
  11426. badge.innerText = '';
  11427. }
  11428. }
  11429. function clearTracerouteTable() {
  11430. const tbody = document.getElementById('tools-tr-tbody');
  11431. if (tbody) tbody.innerHTML = '';
  11432. const rawEl = document.getElementById('tools-tr-raw');
  11433. if (rawEl) rawEl.innerText = '';
  11434. const statHops = document.getElementById('tools-tr-hops-count');
  11435. if (statHops) statHops.innerText = '0 Hops';
  11436. }
  11437. function resetPingButton() {
  11438. const btn = document.getElementById('tools-ping-btn');
  11439. const btnText = document.getElementById('tools-ping-btn-text');
  11440. const spinner = document.getElementById('tools-ping-spinner');
  11441. if (btn) {
  11442. btn.disabled = false;
  11443. 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';
  11444. }
  11445. if (btnText) btnText.innerText = 'Start Ping';
  11446. if (spinner) spinner.classList.add('hidden');
  11447. }
  11448. function setPingRunningButton() {
  11449. const btn = document.getElementById('tools-ping-btn');
  11450. const btnText = document.getElementById('tools-ping-btn-text');
  11451. const spinner = document.getElementById('tools-ping-spinner');
  11452. if (btn) {
  11453. btn.disabled = false;
  11454. 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';
  11455. }
  11456. if (btnText) btnText.innerText = 'Stop Ping';
  11457. if (spinner) spinner.classList.remove('hidden');
  11458. }
  11459. function resetTracerouteButton() {
  11460. const btn = document.getElementById('tools-tr-btn');
  11461. const btnText = document.getElementById('tools-tr-btn-text');
  11462. const spinner = document.getElementById('tools-tr-spinner');
  11463. if (btn) {
  11464. btn.disabled = false;
  11465. 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';
  11466. }
  11467. if (btnText) btnText.innerText = 'Start Traceroute';
  11468. if (spinner) spinner.classList.add('hidden');
  11469. }
  11470. function setTracerouteRunningButton() {
  11471. const btn = document.getElementById('tools-tr-btn');
  11472. const btnText = document.getElementById('tools-tr-btn-text');
  11473. const spinner = document.getElementById('tools-tr-spinner');
  11474. if (btn) {
  11475. btn.disabled = false;
  11476. 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';
  11477. }
  11478. if (btnText) btnText.innerText = 'Stop Traceroute';
  11479. if (spinner) spinner.classList.remove('hidden');
  11480. }
  11481. async function executePing(e) {
  11482. if (e) e.preventDefault();
  11483. // If already running, clicking the button stops the stream!
  11484. if (pingAbortController) {
  11485. pingAbortController.abort();
  11486. pingAbortController = null;
  11487. resetPingButton();
  11488. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11489. return;
  11490. }
  11491. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11492. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11493. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11494. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11495. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11496. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11497. if (!target) {
  11498. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11499. return;
  11500. }
  11501. clearPingTable();
  11502. const resCard = document.getElementById('tools-ping-results');
  11503. if (resCard) resCard.classList.remove('hidden');
  11504. pingAbortController = new AbortController();
  11505. setPingRunningButton();
  11506. try {
  11507. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11508. method: 'POST',
  11509. headers: { 'Content-Type': 'application/json' },
  11510. body: JSON.stringify({
  11511. target,
  11512. count,
  11513. size,
  11514. timeout,
  11515. interface: iface,
  11516. dont_frag: dontFrag
  11517. }),
  11518. signal: pingAbortController.signal
  11519. });
  11520. if (!res.ok) {
  11521. const errText = await res.text();
  11522. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11523. resetPingButton();
  11524. pingAbortController = null;
  11525. return;
  11526. }
  11527. const reader = res.body.getReader();
  11528. const decoder = new TextDecoder('utf-8');
  11529. let buffer = '';
  11530. while (true) {
  11531. const { done, value } = await reader.read();
  11532. if (done) break;
  11533. buffer += decoder.decode(value, { stream: true });
  11534. const blocks = buffer.split('\n\n');
  11535. buffer = blocks.pop() || '';
  11536. for (const block of blocks) {
  11537. const trimmed = block.trim();
  11538. if (!trimmed) continue;
  11539. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11540. try {
  11541. const evt = JSON.parse(line);
  11542. handleLivePingEvent(evt);
  11543. } catch (parseErr) {
  11544. console.warn('Ping SSE parse error:', parseErr, line);
  11545. }
  11546. }
  11547. }
  11548. } catch (err) {
  11549. if (err.name === 'AbortError') {
  11550. // User aborted normally
  11551. } else {
  11552. showToast('Ping Error', err.message, 'error');
  11553. }
  11554. } finally {
  11555. pingAbortController = null;
  11556. resetPingButton();
  11557. }
  11558. }
  11559. function handleLivePingEvent(evt) {
  11560. const sentEl = document.getElementById('tools-ping-stat-sent');
  11561. const recvEl = document.getElementById('tools-ping-stat-recv');
  11562. const lossEl = document.getElementById('tools-ping-stat-loss');
  11563. const avgEl = document.getElementById('tools-ping-stat-avg');
  11564. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11565. const badge = document.getElementById('tools-ping-status-badge');
  11566. const tbody = document.getElementById('tools-ping-tbody');
  11567. const rawEl = document.getElementById('tools-ping-raw');
  11568. if (evt.raw && rawEl) {
  11569. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11570. rawEl.scrollTop = rawEl.scrollHeight;
  11571. }
  11572. if (evt.type === 'reply') {
  11573. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11574. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11575. if (lossEl && evt.packet_loss_pct !== undefined) {
  11576. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11577. lossEl.className = evt.packet_loss_pct === 0
  11578. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11579. : (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');
  11580. }
  11581. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11582. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11583. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11584. }
  11585. if (badge) {
  11586. if (evt.packet_loss_pct === 0) {
  11587. 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';
  11588. badge.innerText = '100% OK';
  11589. } else {
  11590. 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';
  11591. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11592. }
  11593. }
  11594. if (tbody) {
  11595. const tr = document.createElement('tr');
  11596. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11597. tr.innerHTML = `
  11598. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11599. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11600. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11601. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11602. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11603. <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>
  11604. `;
  11605. tbody.appendChild(tr);
  11606. }
  11607. } else if (evt.type === 'timeout') {
  11608. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11609. if (lossEl && evt.packet_loss_pct !== undefined) {
  11610. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11611. 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';
  11612. }
  11613. if (badge) {
  11614. 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';
  11615. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11616. }
  11617. if (tbody) {
  11618. const tr = document.createElement('tr');
  11619. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11620. tr.innerHTML = `
  11621. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11622. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11623. <td class="py-2 px-3 text-slate-600">--</td>
  11624. <td class="py-2 px-3 text-slate-600">--</td>
  11625. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11626. <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>
  11627. `;
  11628. tbody.appendChild(tr);
  11629. }
  11630. } else if (evt.type === 'unreach') {
  11631. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11632. if (lossEl && evt.packet_loss_pct !== undefined) {
  11633. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11634. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11635. }
  11636. if (badge) {
  11637. 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';
  11638. badge.innerText = 'UNREACHABLE';
  11639. }
  11640. if (tbody) {
  11641. const tr = document.createElement('tr');
  11642. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11643. tr.innerHTML = `
  11644. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11645. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11646. <td class="py-2 px-3 text-slate-600">--</td>
  11647. <td class="py-2 px-3 text-slate-600">--</td>
  11648. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11649. <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>
  11650. `;
  11651. tbody.appendChild(tr);
  11652. }
  11653. } else if (evt.type === 'stats') {
  11654. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11655. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11656. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11657. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11658. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11659. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11660. }
  11661. } else if (evt.type === 'done') {
  11662. 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');
  11663. }
  11664. }
  11665. async function executeTraceroute(e) {
  11666. if (e) e.preventDefault();
  11667. if (tracerouteAbortController) {
  11668. tracerouteAbortController.abort();
  11669. tracerouteAbortController = null;
  11670. resetTracerouteButton();
  11671. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11672. return;
  11673. }
  11674. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11675. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11676. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11677. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11678. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11679. if (!target) {
  11680. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11681. return;
  11682. }
  11683. clearTracerouteTable();
  11684. const resCard = document.getElementById('tools-tr-results');
  11685. if (resCard) resCard.classList.remove('hidden');
  11686. tracerouteAbortController = new AbortController();
  11687. setTracerouteRunningButton();
  11688. try {
  11689. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11690. method: 'POST',
  11691. headers: { 'Content-Type': 'application/json' },
  11692. body: JSON.stringify({
  11693. target,
  11694. max_hops: maxHops,
  11695. protocol,
  11696. interface: iface,
  11697. resolve
  11698. }),
  11699. signal: tracerouteAbortController.signal
  11700. });
  11701. if (!res.ok) {
  11702. const errText = await res.text();
  11703. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11704. resetTracerouteButton();
  11705. tracerouteAbortController = null;
  11706. return;
  11707. }
  11708. const reader = res.body.getReader();
  11709. const decoder = new TextDecoder('utf-8');
  11710. let buffer = '';
  11711. while (true) {
  11712. const { done, value } = await reader.read();
  11713. if (done) break;
  11714. buffer += decoder.decode(value, { stream: true });
  11715. const blocks = buffer.split('\n\n');
  11716. buffer = blocks.pop() || '';
  11717. for (const block of blocks) {
  11718. const trimmed = block.trim();
  11719. if (!trimmed) continue;
  11720. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11721. try {
  11722. const evt = JSON.parse(line);
  11723. handleLiveTracerouteEvent(evt);
  11724. } catch (parseErr) {
  11725. console.warn('Traceroute SSE parse error:', parseErr, line);
  11726. }
  11727. }
  11728. }
  11729. } catch (err) {
  11730. if (err.name === 'AbortError') {
  11731. // User aborted normally
  11732. } else {
  11733. showToast('Traceroute Error', err.message, 'error');
  11734. }
  11735. } finally {
  11736. tracerouteAbortController = null;
  11737. resetTracerouteButton();
  11738. }
  11739. }
  11740. function handleLiveTracerouteEvent(evt) {
  11741. const statHops = document.getElementById('tools-tr-hops-count');
  11742. const tbody = document.getElementById('tools-tr-tbody');
  11743. const rawEl = document.getElementById('tools-tr-raw');
  11744. if (evt.raw && rawEl) {
  11745. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11746. rawEl.scrollTop = rawEl.scrollHeight;
  11747. }
  11748. if (evt.hops_count !== undefined && statHops) {
  11749. statHops.innerText = `${evt.hops_count} Hops`;
  11750. }
  11751. if (evt.type === 'hop' && evt.hop && tbody) {
  11752. const h = evt.hop;
  11753. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11754. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11755. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11756. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11757. const tr = document.createElement('tr');
  11758. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11759. tr.innerHTML = `
  11760. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11761. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11762. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11763. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11764. <td class="py-2.5 px-3 text-right">
  11765. ${isTimeout
  11766. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11767. : '<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>'}
  11768. </td>
  11769. `;
  11770. tbody.appendChild(tr);
  11771. } else if (evt.type === 'done') {
  11772. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11773. }
  11774. }
  11775. async function executeMTR(e) {
  11776. if (e) e.preventDefault();
  11777. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11778. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11779. if (!target) {
  11780. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11781. return;
  11782. }
  11783. const btn = document.getElementById('tools-mtr-btn');
  11784. const spinner = document.getElementById('tools-mtr-spinner');
  11785. if (btn) btn.disabled = true;
  11786. if (spinner) spinner.classList.remove('hidden');
  11787. try {
  11788. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11789. method: 'POST',
  11790. headers: { 'Content-Type': 'application/json' },
  11791. body: JSON.stringify({ target, count: cycles })
  11792. });
  11793. const data = await res.json();
  11794. if (!res.ok) {
  11795. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11796. return;
  11797. }
  11798. const resCard = document.getElementById('tools-mtr-results');
  11799. if (resCard) resCard.classList.remove('hidden');
  11800. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11801. const statHops = document.getElementById('tools-mtr-hops-count');
  11802. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11803. const tbody = document.getElementById('tools-mtr-tbody');
  11804. if (tbody) {
  11805. if (hopsCount > 0) {
  11806. tbody.innerHTML = data.hops.map(h => {
  11807. 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');
  11808. return `
  11809. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11810. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11811. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11812. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11813. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11814. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11815. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11816. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11817. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11818. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11819. </tr>
  11820. `;
  11821. }).join('');
  11822. } else {
  11823. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11824. }
  11825. }
  11826. const rawEl = document.getElementById('tools-mtr-raw');
  11827. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11828. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11829. } catch (err) {
  11830. showToast('MTR Error', err.message, 'error');
  11831. } finally {
  11832. if (btn) btn.disabled = false;
  11833. if (spinner) spinner.classList.add('hidden');
  11834. }
  11835. }
  11836. async function executeDNS(e) {
  11837. if (e) e.preventDefault();
  11838. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11839. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11840. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11841. if (!domain) {
  11842. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11843. return;
  11844. }
  11845. const btn = document.getElementById('tools-dns-btn');
  11846. const spinner = document.getElementById('tools-dns-spinner');
  11847. if (btn) btn.disabled = true;
  11848. if (spinner) spinner.classList.remove('hidden');
  11849. try {
  11850. const res = await fetch(`${API_BASE}/tools/dns`, {
  11851. method: 'POST',
  11852. headers: { 'Content-Type': 'application/json' },
  11853. body: JSON.stringify({ domain, type, server })
  11854. });
  11855. const data = await res.json();
  11856. if (!res.ok) {
  11857. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11858. return;
  11859. }
  11860. const resCard = document.getElementById('tools-dns-results');
  11861. if (resCard) resCard.classList.remove('hidden');
  11862. const metaEl = document.getElementById('tools-dns-meta');
  11863. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11864. const tbody = document.getElementById('tools-dns-tbody');
  11865. if (tbody) {
  11866. if (Array.isArray(data.records) && data.records.length > 0) {
  11867. tbody.innerHTML = data.records.map(r => `
  11868. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11869. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11870. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11871. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11872. <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>
  11873. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11874. </tr>
  11875. `).join('');
  11876. } else {
  11877. 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>`;
  11878. }
  11879. }
  11880. const rawEl = document.getElementById('tools-dns-raw');
  11881. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11882. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11883. } catch (err) {
  11884. showToast('DNS Error', err.message, 'error');
  11885. } finally {
  11886. if (btn) btn.disabled = false;
  11887. if (spinner) spinner.classList.add('hidden');
  11888. }
  11889. }
  11890. async function executePortProbe(e) {
  11891. if (e) e.preventDefault();
  11892. const target = document.getElementById('tools-port-target')?.value?.trim();
  11893. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11894. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11895. if (!target || !port) {
  11896. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11897. return;
  11898. }
  11899. const btn = document.getElementById('tools-port-btn');
  11900. const spinner = document.getElementById('tools-port-spinner');
  11901. if (btn) btn.disabled = true;
  11902. if (spinner) spinner.classList.remove('hidden');
  11903. try {
  11904. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11905. method: 'POST',
  11906. headers: { 'Content-Type': 'application/json' },
  11907. body: JSON.stringify({ target, port, timeout })
  11908. });
  11909. const data = await res.json();
  11910. if (!res.ok) {
  11911. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11912. return;
  11913. }
  11914. const resCard = document.getElementById('tools-port-results');
  11915. if (resCard) resCard.classList.remove('hidden');
  11916. const banner = document.getElementById('tools-port-banner');
  11917. const icon = document.getElementById('tools-port-icon');
  11918. const title = document.getElementById('tools-port-title');
  11919. const sub = document.getElementById('tools-port-sub');
  11920. const latency = document.getElementById('tools-port-latency');
  11921. if (data.open) {
  11922. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11923. if (icon) {
  11924. 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';
  11925. icon.innerText = '✓';
  11926. }
  11927. if (title) {
  11928. title.className = 'text-sm font-bold text-emerald-300';
  11929. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11930. }
  11931. if (sub) {
  11932. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11933. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11934. }
  11935. if (latency) {
  11936. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11937. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11938. }
  11939. } else {
  11940. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11941. if (icon) {
  11942. 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';
  11943. icon.innerText = '✕';
  11944. }
  11945. if (title) {
  11946. title.className = 'text-sm font-bold text-rose-300';
  11947. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11948. }
  11949. if (sub) {
  11950. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11951. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11952. }
  11953. if (latency) {
  11954. latency.className = 'text-base font-bold font-mono text-slate-500';
  11955. latency.innerText = '--';
  11956. }
  11957. }
  11958. const rawEl = document.getElementById('tools-port-raw');
  11959. 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'}`);
  11960. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11961. } catch (err) {
  11962. showToast('Probe Error', err.message, 'error');
  11963. } finally {
  11964. if (btn) btn.disabled = false;
  11965. if (spinner) spinner.classList.add('hidden');
  11966. }
  11967. }
  11968. // ==========================================
  11969. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11970. // ==========================================
  11971. async function loadDHCPClients(showToastMsg = false) {
  11972. try {
  11973. const [clientsRes, sumRes] = await Promise.all([
  11974. fetch(`${API_BASE}/dhcp/clients`),
  11975. fetch(`${API_BASE}/dhcp/clients/summary`)
  11976. ]);
  11977. if (clientsRes.ok) {
  11978. state.dhcpClients = await clientsRes.json();
  11979. }
  11980. if (sumRes.ok) {
  11981. state.dhcpSummary = await sumRes.json();
  11982. }
  11983. renderDHCPClients();
  11984. updateDHCPSummaryCards();
  11985. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11986. if (bDhcp && state.dhcpSummary) {
  11987. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11988. }
  11989. if (showToastMsg) {
  11990. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11991. }
  11992. } catch (err) {
  11993. console.error('Failed to load DHCP clients:', err);
  11994. if (showToastMsg) {
  11995. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11996. }
  11997. }
  11998. }
  11999. function updateDHCPSummaryCards() {
  12000. const sum = state.dhcpSummary || {
  12001. total_clients: (state.dhcpClients || []).length,
  12002. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12003. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12004. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12005. };
  12006. const totalEl = document.getElementById('dhcp-stat-total');
  12007. const boundEl = document.getElementById('dhcp-stat-bound');
  12008. const searchEl = document.getElementById('dhcp-stat-searching');
  12009. const disEl = document.getElementById('dhcp-stat-disabled');
  12010. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12011. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12012. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12013. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12014. }
  12015. function renderDHCPClients() {
  12016. const tbody = document.getElementById('dhcp-clients-tbody');
  12017. const emptyState = document.getElementById('dhcp-clients-empty');
  12018. if (!tbody) return;
  12019. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12020. if (clients.length === 0) {
  12021. tbody.innerHTML = '';
  12022. if (emptyState) emptyState.classList.remove('hidden');
  12023. return;
  12024. }
  12025. if (emptyState) emptyState.classList.add('hidden');
  12026. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12027. if (tbody.dataset.sig === sig) return;
  12028. tbody.dataset.sig = sig;
  12029. tbody.innerHTML = clients.map(c => {
  12030. let statusBadge = '';
  12031. if (!c.enabled) {
  12032. 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>';
  12033. } else if (c.status === 'bound') {
  12034. 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>';
  12035. } else if (c.status === 'searching') {
  12036. 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>';
  12037. } else if (c.status === 'stopped') {
  12038. 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>';
  12039. } else {
  12040. 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>`;
  12041. }
  12042. 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>';
  12043. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12044. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12045. 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>';
  12046. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12047. // Option flags
  12048. const flags = [];
  12049. 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>');
  12050. 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>');
  12051. 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>');
  12052. 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>`);
  12053. return `
  12054. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12055. <td class="py-3 px-4">
  12056. <div class="flex items-center gap-2">
  12057. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12058. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12059. </div>
  12060. </td>
  12061. <td class="py-3 px-4">${statusBadge}</td>
  12062. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12063. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12064. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12065. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12066. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12067. <td class="py-3 px-4">
  12068. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12069. </td>
  12070. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12071. ${c.enabled ? `
  12072. <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>
  12073. <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>
  12074. <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>
  12075. ` : `
  12076. <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>
  12077. `}
  12078. <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>
  12079. <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>
  12080. </td>
  12081. </tr>
  12082. `;
  12083. }).join('');
  12084. }
  12085. function openDHCPClientModal(clientId = null) {
  12086. const modal = document.getElementById('modal-dhcp-client');
  12087. if (!modal) return;
  12088. const title = document.getElementById('modal-dhcp-title');
  12089. const idInput = document.getElementById('modal-dhcp-id');
  12090. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12091. const distInput = document.getElementById('modal-dhcp-distance');
  12092. const commentInput = document.getElementById('modal-dhcp-comment');
  12093. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12094. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12095. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12096. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12097. // Populate interfaces
  12098. if (ifaceSelect) {
  12099. let opts = '<option value="">Select interface...</option>';
  12100. const allIfaces = state.interfaces || [];
  12101. const allVlans = state.vlans || [];
  12102. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12103. // Group 1: Physical & Bridge Interfaces
  12104. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12105. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12106. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12107. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12108. });
  12109. opts += '</optgroup>';
  12110. // Group 2: VLAN Interfaces
  12111. if (allVlans.length > 0) {
  12112. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12113. allVlans.forEach(v => {
  12114. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12115. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12116. });
  12117. opts += '</optgroup>';
  12118. }
  12119. ifaceSelect.innerHTML = opts;
  12120. }
  12121. if (clientId) {
  12122. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12123. if (client) {
  12124. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12125. if (idInput) idInput.value = client.id;
  12126. if (ifaceSelect) {
  12127. ifaceSelect.value = client.interface;
  12128. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12129. }
  12130. if (distInput) distInput.value = client.default_route_distance || 1;
  12131. if (commentInput) commentInput.value = client.comment || '';
  12132. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12133. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12134. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12135. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12136. }
  12137. } else {
  12138. if (title) title.innerText = 'Add DHCP Client';
  12139. if (idInput) idInput.value = '';
  12140. if (ifaceSelect) {
  12141. ifaceSelect.value = '';
  12142. ifaceSelect.disabled = false;
  12143. }
  12144. if (distInput) distInput.value = 1;
  12145. if (commentInput) commentInput.value = '';
  12146. if (defRouteCheck) defRouteCheck.checked = true;
  12147. if (peerDnsCheck) peerDnsCheck.checked = true;
  12148. if (peerNtpCheck) peerNtpCheck.checked = true;
  12149. if (enabledCheck) enabledCheck.checked = true;
  12150. }
  12151. modal.classList.remove('hidden');
  12152. }
  12153. function openDHCPClientModalForIface(ifaceName) {
  12154. openDHCPClientModal();
  12155. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12156. if (ifaceSelect && ifaceName) {
  12157. ifaceSelect.value = ifaceName;
  12158. }
  12159. }
  12160. function closeDHCPClientModal() {
  12161. const modal = document.getElementById('modal-dhcp-client');
  12162. if (modal) modal.classList.add('hidden');
  12163. }
  12164. async function submitSaveDHCPClient(e) {
  12165. if (e) e.preventDefault();
  12166. const id = document.getElementById('modal-dhcp-id')?.value;
  12167. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12168. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12169. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12170. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12171. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12172. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12173. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12174. if (!id && !iface) {
  12175. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12176. return;
  12177. }
  12178. try {
  12179. let res;
  12180. if (id) {
  12181. // PUT update
  12182. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12183. method: 'PUT',
  12184. headers: { 'Content-Type': 'application/json' },
  12185. body: JSON.stringify({
  12186. enabled,
  12187. add_default_route: defRoute,
  12188. default_route_distance: distance,
  12189. use_peer_dns: peerDns,
  12190. use_peer_ntp: peerNtp,
  12191. comment
  12192. })
  12193. });
  12194. } else {
  12195. // POST create
  12196. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12197. method: 'POST',
  12198. headers: { 'Content-Type': 'application/json' },
  12199. body: JSON.stringify({
  12200. interface: iface,
  12201. enabled,
  12202. add_default_route: defRoute,
  12203. default_route_distance: distance,
  12204. use_peer_dns: peerDns,
  12205. use_peer_ntp: peerNtp,
  12206. comment
  12207. })
  12208. });
  12209. }
  12210. const data = await res.json();
  12211. if (!res.ok) {
  12212. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12213. return;
  12214. }
  12215. closeDHCPClientModal();
  12216. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12217. await loadDHCPClients();
  12218. fetchData(); // refresh interfaces list with new lease/status
  12219. } catch (err) {
  12220. showToast('Error', err.message, 'error');
  12221. }
  12222. }
  12223. async function toggleDHCPClientState(id, enabled) {
  12224. try {
  12225. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12226. method: 'POST',
  12227. headers: { 'Content-Type': 'application/json' },
  12228. body: JSON.stringify({ enabled })
  12229. });
  12230. const data = await res.json();
  12231. if (!res.ok) {
  12232. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12233. return;
  12234. }
  12235. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12236. await loadDHCPClients();
  12237. fetchData();
  12238. } catch (err) {
  12239. showToast('Error', err.message, 'error');
  12240. }
  12241. }
  12242. async function renewDHCPClient(id) {
  12243. try {
  12244. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12245. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12246. method: 'POST'
  12247. });
  12248. const data = await res.json();
  12249. if (!res.ok) {
  12250. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12251. return;
  12252. }
  12253. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12254. setTimeout(() => {
  12255. loadDHCPClients();
  12256. fetchData();
  12257. }, 1500);
  12258. } catch (err) {
  12259. showToast('Error', err.message, 'error');
  12260. }
  12261. }
  12262. async function releaseDHCPClient(id) {
  12263. try {
  12264. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12265. method: 'POST'
  12266. });
  12267. const data = await res.json();
  12268. if (!res.ok) {
  12269. showToast('Error', data.error || 'Failed to release lease', 'error');
  12270. return;
  12271. }
  12272. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12273. await loadDHCPClients();
  12274. fetchData();
  12275. } catch (err) {
  12276. showToast('Error', err.message, 'error');
  12277. }
  12278. }
  12279. async function deleteDHCPClient(id, ifaceName) {
  12280. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12281. return;
  12282. }
  12283. try {
  12284. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12285. method: 'DELETE'
  12286. });
  12287. const data = await res.json();
  12288. if (!res.ok) {
  12289. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12290. return;
  12291. }
  12292. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12293. await loadDHCPClients();
  12294. fetchData();
  12295. } catch (err) {
  12296. showToast('Error', err.message, 'error');
  12297. }
  12298. }
  12299. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12300. async function loadDHCPServer(populate = true) {
  12301. try {
  12302. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12303. fetch(`${API_BASE}/dhcp-server/summary`),
  12304. fetch(`${API_BASE}/dhcp-server/servers`),
  12305. fetch(`${API_BASE}/dhcp-server/networks`),
  12306. fetch(`${API_BASE}/dhcp-server/leases`),
  12307. fetch(`${API_BASE}/dhcp-server/options`)
  12308. ]);
  12309. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12310. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12311. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12312. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12313. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12314. const sum = state.dhcpServerSummary || {};
  12315. const srvs = state.dhcpServers || [];
  12316. const nets = state.dhcpNetworks || [];
  12317. const leases = state.dhcpLeases || [];
  12318. const opts = state.dhcpOptions || [];
  12319. // KPI Cards
  12320. const statActive = document.getElementById('dhcp-server-stat-active');
  12321. if (statActive) {
  12322. const activeCount = srvs.filter(s => s.running).length;
  12323. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12324. }
  12325. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12326. if (statLeases) {
  12327. statLeases.innerText = leases.length;
  12328. }
  12329. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12330. if (statLeasesSub) {
  12331. const dyn = leases.filter(l => l.dynamic).length;
  12332. const st = leases.filter(l => !l.dynamic).length;
  12333. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12334. }
  12335. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12336. if (statNetworks) {
  12337. statNetworks.innerText = nets.length;
  12338. }
  12339. // Subtab Badges
  12340. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12341. if (bSrv) bSrv.innerText = srvs.length;
  12342. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12343. if (bNet) bNet.innerText = nets.length;
  12344. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12345. if (bLease) bLease.innerText = leases.length;
  12346. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12347. if (bOpt) bOpt.innerText = opts.length;
  12348. // Sidebar Badge
  12349. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12350. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12351. renderCurrentDHCPServerTab();
  12352. } catch (err) {
  12353. console.error('Failed to load DHCP Server:', err);
  12354. }
  12355. }
  12356. function switchDHCPServerTab(tab) {
  12357. state.dhcpServerTab = tab;
  12358. const tabs = ['servers', 'networks', 'leases', 'options'];
  12359. tabs.forEach(t => {
  12360. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12361. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12362. if (panel) {
  12363. if (t === tab) panel.classList.remove('hidden');
  12364. else panel.classList.add('hidden');
  12365. }
  12366. if (btn) {
  12367. if (t === tab) {
  12368. 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';
  12369. } else {
  12370. 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';
  12371. }
  12372. }
  12373. });
  12374. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12375. if (addBtn) {
  12376. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12377. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12378. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12379. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12380. }
  12381. renderCurrentDHCPServerTab();
  12382. }
  12383. function handleDHCPServerPrimaryAdd() {
  12384. const tab = state.dhcpServerTab || 'servers';
  12385. if (tab === 'servers') openAddDHCPServerModal();
  12386. else if (tab === 'networks') openAddDHCPNetworkModal();
  12387. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12388. else if (tab === 'options') openAddDHCPOptionModal();
  12389. }
  12390. function renderCurrentDHCPServerTab() {
  12391. const tab = state.dhcpServerTab || 'servers';
  12392. if (tab === 'servers') renderDHCPServers();
  12393. else if (tab === 'networks') renderDHCPNetworks();
  12394. else if (tab === 'leases') renderDHCPLeases();
  12395. else if (tab === 'options') renderDHCPOptions();
  12396. }
  12397. function renderDHCPServers() {
  12398. const tbody = document.getElementById('dhcp-server-tbody');
  12399. const empty = document.getElementById('dhcp-server-empty');
  12400. if (!tbody) return;
  12401. const servers = state.dhcpServers || [];
  12402. if (servers.length === 0) {
  12403. tbody.innerHTML = '';
  12404. empty?.classList.remove('hidden');
  12405. return;
  12406. }
  12407. empty?.classList.add('hidden');
  12408. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12409. if (tbody.dataset.sig === sig) return;
  12410. tbody.dataset.sig = sig;
  12411. tbody.innerHTML = '';
  12412. servers.forEach(s => {
  12413. const tr = document.createElement('tr');
  12414. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12415. tr.innerHTML = `
  12416. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12417. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12418. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12419. <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>
  12420. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12421. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12422. <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>
  12423. <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>
  12424. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12425. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12426. <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>
  12427. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12428. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12429. </td>
  12430. `;
  12431. tbody.appendChild(tr);
  12432. });
  12433. }
  12434. function renderDHCPNetworks() {
  12435. const tbody = document.getElementById('dhcp-networks-tbody');
  12436. const empty = document.getElementById('dhcp-networks-empty');
  12437. if (!tbody) return;
  12438. tbody.innerHTML = '';
  12439. const networks = state.dhcpNetworks || [];
  12440. if (networks.length === 0) {
  12441. empty?.classList.remove('hidden');
  12442. return;
  12443. }
  12444. empty?.classList.add('hidden');
  12445. networks.forEach(n => {
  12446. const tr = document.createElement('tr');
  12447. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12448. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12449. const optionsChips = (n.dhcp_options || []).map(optId => {
  12450. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12451. if (!opt) return '';
  12452. 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>`;
  12453. }).filter(Boolean).join('');
  12454. tr.innerHTML = `
  12455. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12456. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12457. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12458. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12459. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12460. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12461. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12462. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12463. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12464. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12465. </td>
  12466. `;
  12467. tbody.appendChild(tr);
  12468. });
  12469. }
  12470. function renderDHCPLeases() {
  12471. const tbody = document.getElementById('dhcp-leases-tbody');
  12472. const empty = document.getElementById('dhcp-leases-empty');
  12473. if (!tbody) return;
  12474. tbody.innerHTML = '';
  12475. const leases = state.dhcpLeases || [];
  12476. if (leases.length === 0) {
  12477. empty?.classList.remove('hidden');
  12478. return;
  12479. }
  12480. empty?.classList.add('hidden');
  12481. leases.forEach(l => {
  12482. const tr = document.createElement('tr');
  12483. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12484. 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>';
  12485. const statusBadge = l.status === 'bound'
  12486. ? '<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>'
  12487. : l.status === 'static'
  12488. ? '<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>'
  12489. : '<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>';
  12490. const makeStaticBtn = l.dynamic
  12491. ? `<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>`
  12492. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12493. tr.innerHTML = `
  12494. <td class="py-2.5 px-3 text-center">${flag}</td>
  12495. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12496. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12497. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12498. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12499. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12500. <td class="py-2.5 px-3">${statusBadge}</td>
  12501. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12502. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12503. ${makeStaticBtn}
  12504. </td>
  12505. `;
  12506. tbody.appendChild(tr);
  12507. });
  12508. }
  12509. function renderDHCPOptions() {
  12510. const tbody = document.getElementById('dhcp-options-tbody');
  12511. const empty = document.getElementById('dhcp-options-empty');
  12512. if (!tbody) return;
  12513. tbody.innerHTML = '';
  12514. const options = state.dhcpOptions || [];
  12515. if (options.length === 0) {
  12516. empty?.classList.remove('hidden');
  12517. return;
  12518. }
  12519. empty?.classList.add('hidden');
  12520. options.forEach(o => {
  12521. const tr = document.createElement('tr');
  12522. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12523. tr.innerHTML = `
  12524. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12525. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12526. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12527. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12528. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12529. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12530. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12531. </td>
  12532. `;
  12533. tbody.appendChild(tr);
  12534. });
  12535. }
  12536. // ==================== MODALS & ACTIONS: SERVER ====================
  12537. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12538. const sel = document.getElementById(elemId);
  12539. if (!sel) return;
  12540. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12541. const networks = state.dhcpNetworks || [];
  12542. networks.forEach(n => {
  12543. const opt = document.createElement('option');
  12544. opt.value = n.address;
  12545. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12546. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12547. opt.selected = true;
  12548. }
  12549. sel.appendChild(opt);
  12550. });
  12551. }
  12552. function onDHCPServerNetworkChange() {
  12553. const netSel = document.getElementById('dhcp-server-modal-network');
  12554. if (!netSel) return;
  12555. const netVal = netSel.value;
  12556. if (!netVal) return;
  12557. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12558. if (!poolInput) return;
  12559. // Auto-calculate suggested address pool based on subnet CIDR
  12560. const parts = netVal.split('/');
  12561. const ip = parts[0];
  12562. const cidr = parseInt(parts[1] || '24', 10);
  12563. if (cidr === 24) {
  12564. const octets = ip.split('.');
  12565. if (octets.length === 4) {
  12566. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12567. poolInput.value = `${base}.10-${base}.254`;
  12568. }
  12569. }
  12570. }
  12571. function openAddDHCPServerModal() {
  12572. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12573. document.getElementById('dhcp-server-modal-id').value = '';
  12574. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12575. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12576. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12577. document.getElementById('dhcp-server-modal-comment').value = '';
  12578. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12579. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12580. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12581. const networks = state.dhcpNetworks || [];
  12582. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12583. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12584. if (defaultNet) {
  12585. onDHCPServerNetworkChange();
  12586. }
  12587. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12588. }
  12589. function openEditDHCPServerModal(id) {
  12590. const s = (state.dhcpServers || []).find(item => item.id === id);
  12591. if (!s) return;
  12592. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12593. document.getElementById('dhcp-server-modal-id').value = s.id;
  12594. document.getElementById('dhcp-server-modal-name').value = s.name;
  12595. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12596. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12597. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12598. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12599. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12600. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12601. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12602. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12603. }
  12604. function closeDHCPServerModal() {
  12605. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12606. }
  12607. async function submitSaveDHCPServer(e) {
  12608. e.preventDefault();
  12609. const id = document.getElementById('dhcp-server-modal-id').value;
  12610. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12611. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12612. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12613. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12614. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12615. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12616. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12617. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12618. try {
  12619. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12620. method: 'POST',
  12621. headers: { 'Content-Type': 'application/json' },
  12622. body: JSON.stringify({
  12623. id,
  12624. name,
  12625. interface: iface,
  12626. network,
  12627. address_pool: pool,
  12628. lease_time: leaseTime,
  12629. authoritative,
  12630. disabled,
  12631. comment
  12632. })
  12633. });
  12634. if (res.ok) {
  12635. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12636. closeDHCPServerModal();
  12637. loadDHCPServer(false);
  12638. fetchData(false);
  12639. } else {
  12640. const err = await res.text();
  12641. showToast('Error', err, 'error');
  12642. }
  12643. } catch (err) {
  12644. showToast('Error', err.message, 'error');
  12645. }
  12646. }
  12647. async function toggleDHCPServerState(id, disabled) {
  12648. try {
  12649. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12650. method: 'POST',
  12651. headers: { 'Content-Type': 'application/json' },
  12652. body: JSON.stringify({ disabled })
  12653. });
  12654. if (res.ok) {
  12655. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12656. loadDHCPServer(false);
  12657. fetchData(false);
  12658. }
  12659. } catch (err) {
  12660. showToast('Error', err.message, 'error');
  12661. }
  12662. }
  12663. async function deleteDHCPServer(id, name) {
  12664. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12665. try {
  12666. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12667. if (res.ok) {
  12668. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12669. loadDHCPServer(false);
  12670. fetchData(false);
  12671. }
  12672. } catch (err) {
  12673. showToast('Error', err.message, 'error');
  12674. }
  12675. }
  12676. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12677. function openAddDHCPNetworkModal() {
  12678. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12679. document.getElementById('dhcp-network-modal-id').value = '';
  12680. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12681. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12682. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12683. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12684. document.getElementById('dhcp-network-modal-netmask').value = '';
  12685. document.getElementById('dhcp-network-modal-comment').value = '';
  12686. renderDHCPNetworkOptionsCheckboxes([]);
  12687. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12688. }
  12689. function openEditDHCPNetworkModal(id) {
  12690. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12691. if (!n) return;
  12692. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12693. document.getElementById('dhcp-network-modal-id').value = n.id;
  12694. document.getElementById('dhcp-network-modal-address').value = n.address;
  12695. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12696. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12697. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12698. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12699. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12700. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12701. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12702. }
  12703. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12704. const container = document.getElementById('dhcp-network-modal-options-list');
  12705. if (!container) return;
  12706. container.innerHTML = '';
  12707. const opts = state.dhcpOptions || [];
  12708. if (opts.length === 0) {
  12709. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12710. return;
  12711. }
  12712. opts.forEach(o => {
  12713. const isChecked = selectedIds.includes(o.id);
  12714. const label = document.createElement('label');
  12715. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12716. label.innerHTML = `
  12717. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12718. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12719. `;
  12720. container.appendChild(label);
  12721. });
  12722. }
  12723. function closeDHCPNetworkModal() {
  12724. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12725. }
  12726. async function submitSaveDHCPNetwork(e) {
  12727. e.preventDefault();
  12728. const id = document.getElementById('dhcp-network-modal-id').value;
  12729. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12730. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12731. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12732. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12733. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12734. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12735. const selectedOpts = [];
  12736. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12737. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12738. try {
  12739. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12740. method: 'POST',
  12741. headers: { 'Content-Type': 'application/json' },
  12742. body: JSON.stringify({
  12743. id,
  12744. address,
  12745. gateway,
  12746. netmask,
  12747. dns_servers: dnsServers,
  12748. domain,
  12749. dhcp_options: selectedOpts,
  12750. comment
  12751. })
  12752. });
  12753. if (res.ok) {
  12754. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12755. closeDHCPNetworkModal();
  12756. loadDHCPServer(false);
  12757. fetchData(false);
  12758. } else {
  12759. const err = await res.text();
  12760. showToast('Error', err, 'error');
  12761. }
  12762. } catch (err) {
  12763. showToast('Error', err.message, 'error');
  12764. }
  12765. }
  12766. async function deleteDHCPNetwork(id, addr) {
  12767. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12768. try {
  12769. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12770. if (res.ok) {
  12771. showToast('Deleted', `Network ${addr} removed`, 'success');
  12772. loadDHCPServer(false);
  12773. fetchData(false);
  12774. }
  12775. } catch (err) {
  12776. showToast('Error', err.message, 'error');
  12777. }
  12778. }
  12779. // ==================== MODALS & ACTIONS: LEASES ====================
  12780. function openAddDHCPStaticLeaseModal() {
  12781. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12782. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12783. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12784. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12785. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12786. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12787. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12788. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12789. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12790. }
  12791. function closeDHCPStaticLeaseModal() {
  12792. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12793. }
  12794. async function submitSaveDHCPStaticLease(e) {
  12795. e.preventDefault();
  12796. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12797. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12798. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12799. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12800. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12801. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12802. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12803. try {
  12804. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12805. method: 'POST',
  12806. headers: { 'Content-Type': 'application/json' },
  12807. body: JSON.stringify({
  12808. id,
  12809. mac_address: mac,
  12810. address: ip,
  12811. hostname,
  12812. server,
  12813. comment,
  12814. disabled
  12815. })
  12816. });
  12817. if (res.ok) {
  12818. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12819. closeDHCPStaticLeaseModal();
  12820. loadDHCPServer(false);
  12821. fetchData(false);
  12822. } else {
  12823. const err = await res.text();
  12824. showToast('Error', err, 'error');
  12825. }
  12826. } catch (err) {
  12827. showToast('Error', err.message, 'error');
  12828. }
  12829. }
  12830. async function deleteDHCPStaticLease(id) {
  12831. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12832. try {
  12833. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12834. if (res.ok) {
  12835. showToast('Deleted', 'Static lease removed', 'success');
  12836. loadDHCPServer(false);
  12837. fetchData(false);
  12838. }
  12839. } catch (err) {
  12840. showToast('Error', err.message, 'error');
  12841. }
  12842. }
  12843. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12844. try {
  12845. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12846. method: 'POST',
  12847. headers: { 'Content-Type': 'application/json' },
  12848. body: JSON.stringify({
  12849. mac_address: mac,
  12850. address: ip,
  12851. hostname,
  12852. comment: comment || 'Converted to static'
  12853. })
  12854. });
  12855. if (res.ok) {
  12856. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12857. loadDHCPServer(false);
  12858. fetchData(false);
  12859. } else {
  12860. const err = await res.text();
  12861. showToast('Error', err, 'error');
  12862. }
  12863. } catch (err) {
  12864. showToast('Error', err.message, 'error');
  12865. }
  12866. }
  12867. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12868. function openAddDHCPOptionModal() {
  12869. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12870. document.getElementById('dhcp-option-modal-id').value = '';
  12871. document.getElementById('dhcp-option-modal-name').value = '';
  12872. document.getElementById('dhcp-option-modal-code').value = '';
  12873. document.getElementById('dhcp-option-modal-value').value = '';
  12874. document.getElementById('dhcp-option-modal-comment').value = '';
  12875. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12876. }
  12877. function openEditDHCPOptionModal(id) {
  12878. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12879. if (!o) return;
  12880. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12881. document.getElementById('dhcp-option-modal-id').value = o.id;
  12882. document.getElementById('dhcp-option-modal-name').value = o.name;
  12883. document.getElementById('dhcp-option-modal-code').value = o.code;
  12884. document.getElementById('dhcp-option-modal-value').value = o.value;
  12885. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12886. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12887. }
  12888. function closeDHCPOptionModal() {
  12889. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12890. }
  12891. async function submitSaveDHCPOption(e) {
  12892. e.preventDefault();
  12893. const id = document.getElementById('dhcp-option-modal-id').value;
  12894. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12895. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12896. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12897. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12898. try {
  12899. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12900. method: 'POST',
  12901. headers: { 'Content-Type': 'application/json' },
  12902. body: JSON.stringify({ id, name, code, value, comment })
  12903. });
  12904. if (res.ok) {
  12905. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12906. closeDHCPOptionModal();
  12907. loadDHCPServer(false);
  12908. fetchData(false);
  12909. } else {
  12910. const err = await res.text();
  12911. showToast('Error', err, 'error');
  12912. }
  12913. } catch (err) {
  12914. showToast('Error', err.message, 'error');
  12915. }
  12916. }
  12917. async function deleteDHCPOption(id, name) {
  12918. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12919. try {
  12920. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12921. if (res.ok) {
  12922. showToast('Deleted', `Option ${name} removed`, 'success');
  12923. loadDHCPServer(false);
  12924. fetchData(false);
  12925. }
  12926. } catch (err) {
  12927. showToast('Error', err.message, 'error');
  12928. }
  12929. }
  12930. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12931. function openDHCPServerSetupModal() {
  12932. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12933. onDHCPWizardIfaceChange();
  12934. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12935. }
  12936. function closeDHCPServerSetupModal() {
  12937. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12938. }
  12939. function onDHCPWizardIfaceChange() {
  12940. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12941. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12942. let ip = '192.168.88.1';
  12943. let prefix = '24';
  12944. if (iface && iface.ip_address) {
  12945. const parts = iface.ip_address.split('/');
  12946. ip = parts[0];
  12947. if (parts.length > 1) prefix = parts[1];
  12948. }
  12949. // Calculate subnet base (e.g. 192.168.88.0/24)
  12950. const ipParts = ip.split('.');
  12951. if (ipParts.length === 4) {
  12952. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12953. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12954. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12955. document.getElementById('dhcp-wizard-gateway').value = ip;
  12956. document.getElementById('dhcp-wizard-pool').value = pool;
  12957. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12958. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12959. }
  12960. }
  12961. async function submitDHCPServerSetupWizard(e) {
  12962. e.preventDefault();
  12963. const iface = document.getElementById('dhcp-wizard-iface').value;
  12964. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12965. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12966. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12967. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12968. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12969. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12970. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12971. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12972. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12973. try {
  12974. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12975. method: 'POST',
  12976. headers: { 'Content-Type': 'application/json' },
  12977. body: JSON.stringify({
  12978. interface: iface,
  12979. address_space: space,
  12980. gateway: gw,
  12981. address_pool: pool,
  12982. dns_servers: dnsServers,
  12983. lease_time: leaseTime,
  12984. ntp_servers: ntpServers,
  12985. next_server: tftp
  12986. })
  12987. });
  12988. if (res.ok) {
  12989. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12990. closeDHCPServerSetupModal();
  12991. loadDHCPServer(false);
  12992. fetchData(false);
  12993. } else {
  12994. const err = await res.text();
  12995. showToast('Error', err, 'error');
  12996. }
  12997. } catch (err) {
  12998. showToast('Error', err.message, 'error');
  12999. }
  13000. }
  13001. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13002. const sel = document.getElementById(elemId);
  13003. if (!sel) return;
  13004. sel.innerHTML = '<option value="">Select interface...</option>';
  13005. const ifaces = state.interfaces || [];
  13006. ifaces.forEach(i => {
  13007. if (i.name === 'lo') return;
  13008. const opt = document.createElement('option');
  13009. opt.value = i.name;
  13010. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13011. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13012. if (i.name === selectedVal) opt.selected = true;
  13013. sel.appendChild(opt);
  13014. });
  13015. }
  13016. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13017. function initTableSorting() {
  13018. document.querySelectorAll('table').forEach(setupSortableTable);
  13019. }
  13020. function setupSortableTable(table) {
  13021. const thead = table.querySelector('thead');
  13022. const tbody = table.querySelector('tbody');
  13023. if (!thead || !tbody) return;
  13024. const headerRows = thead.querySelectorAll('tr');
  13025. if (headerRows.length === 0) return;
  13026. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13027. ths.forEach((th, colIdx) => {
  13028. if (th._sortBound) return;
  13029. th._sortBound = true;
  13030. const rawText = th.innerText.trim().toLowerCase();
  13031. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13032. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13033. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13034. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13035. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13036. return;
  13037. }
  13038. th.classList.add('table-sortable', 'group');
  13039. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13040. let icon = th.querySelector('.table-sort-icon');
  13041. if (!icon) {
  13042. icon = document.createElement('span');
  13043. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13044. icon.innerHTML = '⇅';
  13045. th.appendChild(icon);
  13046. }
  13047. th.addEventListener('click', (e) => {
  13048. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13049. handleHeaderClick(table, th, colIdx);
  13050. });
  13051. });
  13052. if (!tbody._sortObserved) {
  13053. tbody._sortObserved = true;
  13054. let sortDebounceTimer = null;
  13055. const observer = new MutationObserver((mutations) => {
  13056. if (tbody._isSorting) return;
  13057. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13058. if (!hasChildChanges) return;
  13059. clearTimeout(sortDebounceTimer);
  13060. sortDebounceTimer = setTimeout(() => {
  13061. if (tbody._isSorting) return;
  13062. if (table._activeSort && table._activeSort.dir !== 'none') {
  13063. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13064. } else {
  13065. tagOriginalRowOrder(tbody);
  13066. }
  13067. }, 50);
  13068. });
  13069. tbody._sortObserver = observer;
  13070. observer.observe(tbody, { childList: true });
  13071. }
  13072. tagOriginalRowOrder(tbody);
  13073. }
  13074. function tagOriginalRowOrder(tbody) {
  13075. let idx = 0;
  13076. Array.from(tbody.children).forEach(tr => {
  13077. if (!tr.querySelector('td[colspan]')) {
  13078. if (!tr.hasAttribute('data-orig-idx')) {
  13079. tr.setAttribute('data-orig-idx', idx++);
  13080. }
  13081. }
  13082. });
  13083. }
  13084. function handleHeaderClick(table, th, colIdx) {
  13085. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13086. let newDir = 'asc';
  13087. if (currentSort.colIdx === colIdx) {
  13088. if (currentSort.dir === 'asc') newDir = 'desc';
  13089. else if (currentSort.dir === 'desc') newDir = 'none';
  13090. else newDir = 'asc';
  13091. } else {
  13092. newDir = 'asc';
  13093. }
  13094. table._activeSort = { colIdx, dir: newDir };
  13095. updateHeaderIcons(table, colIdx, newDir);
  13096. applyTableSort(table, colIdx, newDir, true);
  13097. }
  13098. function updateHeaderIcons(table, activeColIdx, dir) {
  13099. const thead = table.querySelector('thead');
  13100. if (!thead) return;
  13101. const ths = thead.querySelectorAll('th');
  13102. ths.forEach((th, idx) => {
  13103. const icon = th.querySelector('.table-sort-icon');
  13104. if (!icon) return;
  13105. if (idx === activeColIdx && dir !== 'none') {
  13106. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13107. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13108. th.classList.add('table-sorted-active');
  13109. } else {
  13110. icon.innerHTML = '⇅';
  13111. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13112. th.classList.remove('table-sorted-active');
  13113. }
  13114. });
  13115. }
  13116. function applyTableSort(table, colIdx, dir, userInitiated) {
  13117. const tbody = table.querySelector('tbody');
  13118. if (!tbody || tbody.children.length <= 1) return;
  13119. tbody._isSorting = true;
  13120. tagOriginalRowOrder(tbody);
  13121. // Group parent rows and any attached drawer/sub-rows
  13122. const groups = [];
  13123. let currentGroup = null;
  13124. Array.from(tbody.children).forEach(tr => {
  13125. if (tr.querySelector('td[colspan]')) {
  13126. if (currentGroup) {
  13127. currentGroup.subRows.push(tr);
  13128. } else {
  13129. groups.push({ mainRow: tr, subRows: [] });
  13130. }
  13131. } else {
  13132. currentGroup = { mainRow: tr, subRows: [] };
  13133. groups.push(currentGroup);
  13134. }
  13135. });
  13136. if (dir === 'none') {
  13137. groups.sort((a, b) => {
  13138. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13139. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13140. return idxA - idxB;
  13141. });
  13142. } else {
  13143. groups.sort((a, b) => {
  13144. const cellA = a.mainRow.children[colIdx];
  13145. const cellB = b.mainRow.children[colIdx];
  13146. const res = compareTableCells(cellA, cellB);
  13147. return dir === 'asc' ? res : -res;
  13148. });
  13149. }
  13150. // Check if rows are already in correct order to avoid modifying DOM
  13151. let alreadyOrdered = true;
  13152. let childIdx = 0;
  13153. for (const g of groups) {
  13154. if (tbody.children[childIdx] !== g.mainRow) {
  13155. alreadyOrdered = false;
  13156. break;
  13157. }
  13158. childIdx++;
  13159. for (const sub of g.subRows) {
  13160. if (tbody.children[childIdx] !== sub) {
  13161. alreadyOrdered = false;
  13162. break;
  13163. }
  13164. childIdx++;
  13165. }
  13166. }
  13167. if (alreadyOrdered) {
  13168. tbody._isSorting = false;
  13169. return;
  13170. }
  13171. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13172. if (tbody._sortObserver) {
  13173. tbody._sortObserver.disconnect();
  13174. }
  13175. // Re-append rows in sorted order
  13176. groups.forEach(g => {
  13177. tbody.appendChild(g.mainRow);
  13178. g.subRows.forEach(sub => tbody.appendChild(sub));
  13179. });
  13180. // Drain any queued mutations and re-connect observer
  13181. if (tbody._sortObserver) {
  13182. tbody._sortObserver.takeRecords();
  13183. tbody._sortObserver.observe(tbody, { childList: true });
  13184. }
  13185. tbody._isSorting = false;
  13186. }
  13187. function getCellRawText(cell) {
  13188. if (!cell) return '';
  13189. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13190. const input = cell.querySelector('input, select');
  13191. if (input) {
  13192. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13193. return input.value;
  13194. }
  13195. return cell.innerText.trim();
  13196. }
  13197. function parseTrafficToNumber(str) {
  13198. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13199. if (!m) return null;
  13200. const num = parseFloat(m[1].replace(/,/g, ''));
  13201. if (isNaN(num)) return null;
  13202. const unit = m[2].toUpperCase();
  13203. let mult = 1;
  13204. if (unit.startsWith('K')) mult = 1024;
  13205. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13206. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13207. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13208. return num * mult;
  13209. }
  13210. function parseIpToNumber(str) {
  13211. const clean = str.replace(/^[!~]/, '').trim();
  13212. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13213. if (!m) return null;
  13214. const o1 = parseInt(m[1], 10);
  13215. const o2 = parseInt(m[2], 10);
  13216. const o3 = parseInt(m[3], 10);
  13217. const o4 = parseInt(m[4], 10);
  13218. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13219. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13220. }
  13221. function parseCompoundPackets(str) {
  13222. const m = str.match(/^([\d,]+)p/);
  13223. if (!m) return null;
  13224. return parseInt(m[1].replace(/,/g, ''), 10);
  13225. }
  13226. function compareTableCells(cellA, cellB) {
  13227. const a = getCellRawText(cellA);
  13228. const b = getCellRawText(cellB);
  13229. if (a === '' && b !== '') return 1;
  13230. if (b === '' && a !== '') return -1;
  13231. if (a === b) return 0;
  13232. // 1. IP Addresses / CIDR
  13233. const ipA = parseIpToNumber(a);
  13234. const ipB = parseIpToNumber(b);
  13235. if (ipA !== null && ipB !== null) return ipA - ipB;
  13236. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13237. const pktA = parseCompoundPackets(a);
  13238. const pktB = parseCompoundPackets(b);
  13239. if (pktA !== null && pktB !== null) return pktA - pktB;
  13240. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13241. const trafA = parseTrafficToNumber(a);
  13242. const trafB = parseTrafficToNumber(b);
  13243. if (trafA !== null && trafB !== null) return trafA - trafB;
  13244. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13245. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13246. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13247. const numA = Number(cleanNumA);
  13248. const numB = Number(cleanNumB);
  13249. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13250. return numA - numB;
  13251. }
  13252. // 5. Natural case-insensitive string compare
  13253. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13254. }
  13255. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13256. async function loadVRRP(showToastNotification = false) {
  13257. try {
  13258. const [instRes, sumRes] = await Promise.all([
  13259. fetch(`${API_BASE}/vrrp/instances`),
  13260. fetch(`${API_BASE}/vrrp/summary`)
  13261. ]);
  13262. if (instRes.ok) {
  13263. state.vrrpInstances = await instRes.json();
  13264. renderVRRP();
  13265. }
  13266. if (sumRes.ok) {
  13267. state.vrrpSummary = await sumRes.json();
  13268. renderVRRPSummary();
  13269. }
  13270. if (showToastNotification) {
  13271. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13272. }
  13273. } catch (err) {
  13274. console.error('Failed to load VRRP:', err);
  13275. }
  13276. }
  13277. function renderVRRPSummary() {
  13278. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13279. const elTotal = document.getElementById('vrrp-stat-total');
  13280. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13281. const elMaster = document.getElementById('vrrp-stat-master');
  13282. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13283. const elBackup = document.getElementById('vrrp-stat-backup');
  13284. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13285. const bCount = document.getElementById('badge-vrrp-count');
  13286. if (bCount) bCount.innerText = s.total_instances || 0;
  13287. const dot = document.getElementById('badge-vrrp-dot');
  13288. if (dot) {
  13289. if (s.master_instances > 0) {
  13290. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13291. } else if (s.backup_instances > 0) {
  13292. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13293. } else {
  13294. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13295. }
  13296. }
  13297. }
  13298. function renderVRRP() {
  13299. const tbody = document.getElementById('vrrp-table-tbody');
  13300. const empty = document.getElementById('vrrp-table-empty');
  13301. if (!tbody) return;
  13302. tbody.innerHTML = '';
  13303. const instances = state.vrrpInstances || [];
  13304. if (instances.length === 0) {
  13305. empty?.classList.remove('hidden');
  13306. return;
  13307. }
  13308. empty?.classList.add('hidden');
  13309. instances.forEach(inst => {
  13310. const tr = document.createElement('tr');
  13311. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13312. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13313. 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>`;
  13314. if (inst.disabled) {
  13315. 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>`;
  13316. } else if (inst.state === 'MASTER') {
  13317. 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>`;
  13318. } else if (inst.state === 'BACKUP') {
  13319. 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>`;
  13320. } else if (inst.state === 'FAULT') {
  13321. 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>`;
  13322. }
  13323. // Render State Badge
  13324. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13325. if (!inst.disabled) {
  13326. if (inst.state === 'MASTER') {
  13327. 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>`;
  13328. } else if (inst.state === 'BACKUP') {
  13329. 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>`;
  13330. } else if (inst.state === 'FAULT') {
  13331. 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>`;
  13332. }
  13333. }
  13334. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13335. tr.innerHTML = `
  13336. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13337. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13338. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13339. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13340. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13341. <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>
  13342. <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>
  13343. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13344. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13345. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13346. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13347. <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>
  13348. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13349. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13350. </td>
  13351. `;
  13352. tbody.appendChild(tr);
  13353. });
  13354. }
  13355. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13356. const sel = document.getElementById(elemId);
  13357. if (!sel) return;
  13358. sel.innerHTML = '<option value="">Select interface...</option>';
  13359. const ifaces = state.interfaces || [];
  13360. ifaces.forEach(i => {
  13361. const opt = document.createElement('option');
  13362. opt.value = i.name;
  13363. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13364. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13365. sel.appendChild(opt);
  13366. });
  13367. }
  13368. function openAddVRRPModal() {
  13369. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13370. document.getElementById('modal-vrrp-id').value = '';
  13371. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13372. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13373. document.getElementById('modal-vrrp-priority').value = 100;
  13374. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13375. document.getElementById('modal-vrrp-version').value = '3';
  13376. document.getElementById('modal-vrrp-interval').value = 1;
  13377. document.getElementById('modal-vrrp-authtype').value = 'none';
  13378. document.getElementById('modal-vrrp-authpass').value = '';
  13379. document.getElementById('modal-vrrp-comment').value = '';
  13380. document.getElementById('modal-vrrp-preempt').checked = true;
  13381. document.getElementById('modal-vrrp-disabled').checked = false;
  13382. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13383. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13384. }
  13385. function openEditVRRPModal(id) {
  13386. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13387. if (!inst) return;
  13388. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13389. document.getElementById('modal-vrrp-id').value = inst.id;
  13390. document.getElementById('modal-vrrp-name').value = inst.name;
  13391. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13392. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13393. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13394. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13395. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13396. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13397. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13398. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13399. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13400. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13401. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13402. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13403. }
  13404. function closeVRRPModal() {
  13405. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13406. }
  13407. async function submitSaveVRRP(e) {
  13408. e.preventDefault();
  13409. const id = document.getElementById('modal-vrrp-id').value;
  13410. const name = document.getElementById('modal-vrrp-name').value.trim();
  13411. const iface = document.getElementById('modal-vrrp-iface').value;
  13412. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13413. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13414. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13415. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13416. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13417. const authType = document.getElementById('modal-vrrp-authtype').value;
  13418. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13419. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13420. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13421. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13422. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13423. try {
  13424. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13425. method: 'POST',
  13426. headers: { 'Content-Type': 'application/json' },
  13427. body: JSON.stringify({
  13428. id,
  13429. name,
  13430. interface: iface,
  13431. vrid,
  13432. priority,
  13433. virtual_ips: vips,
  13434. version,
  13435. interval,
  13436. auth_type: authType,
  13437. auth_password: authPass,
  13438. comment,
  13439. preempt,
  13440. disabled
  13441. })
  13442. });
  13443. if (res.ok) {
  13444. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13445. closeVRRPModal();
  13446. loadVRRP(false);
  13447. fetchData(false);
  13448. } else {
  13449. const err = await res.text();
  13450. showToast('Error', err, 'error');
  13451. }
  13452. } catch (err) {
  13453. showToast('Error', err.message, 'error');
  13454. }
  13455. }
  13456. async function deleteVRRP(id, name) {
  13457. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13458. try {
  13459. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13460. if (res.ok) {
  13461. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13462. loadVRRP(false);
  13463. fetchData(false);
  13464. } else {
  13465. const err = await res.text();
  13466. showToast('Error', err, 'error');
  13467. }
  13468. } catch (err) {
  13469. showToast('Error', err.message, 'error');
  13470. }
  13471. }
  13472. async function toggleVRRPState(id, disabled) {
  13473. try {
  13474. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13475. method: 'POST',
  13476. headers: { 'Content-Type': 'application/json' },
  13477. body: JSON.stringify({ disabled })
  13478. });
  13479. if (res.ok) {
  13480. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13481. loadVRRP(false);
  13482. fetchData(false);
  13483. } else {
  13484. const err = await res.text();
  13485. showToast('Error', err, 'error');
  13486. }
  13487. } catch (err) {
  13488. showToast('Error', err.message, 'error');
  13489. }
  13490. }
  13491. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13492. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13493. let docSortDebounce = null;
  13494. const docTableObserver = new MutationObserver((mutations) => {
  13495. let needsInit = false;
  13496. for (const m of mutations) {
  13497. for (const node of m.addedNodes) {
  13498. if (node.nodeType === 1) {
  13499. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13500. needsInit = true;
  13501. break;
  13502. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13503. needsInit = true;
  13504. break;
  13505. }
  13506. }
  13507. }
  13508. if (needsInit) break;
  13509. }
  13510. if (needsInit) {
  13511. clearTimeout(docSortDebounce);
  13512. docSortDebounce = setTimeout(initTableSorting, 100);
  13513. }
  13514. });
  13515. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13516. }
  13517. // =========================================================================
  13518. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13519. // =========================================================================
  13520. const bwtestState = {
  13521. running: false,
  13522. pollTimer: null,
  13523. eventSource: null,
  13524. chartPoints: [],
  13525. maxChartPoints: 60,
  13526. serverConfig: null,
  13527. peakTx: 0,
  13528. peakRx: 0,
  13529. targetDuration: 10,
  13530. lastSampleElapsed: -1,
  13531. sessionID: null
  13532. };
  13533. async function loadBwTestView() {
  13534. resizeBwTestCanvas();
  13535. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13536. }
  13537. async function fetchBwTestServerStatus() {
  13538. try {
  13539. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13540. if (!res.ok) return;
  13541. const s = await res.json();
  13542. bwtestState.serverConfig = s;
  13543. // Update indicator and badges
  13544. const indicator = document.getElementById('bwtest-server-indicator');
  13545. const badge = document.getElementById('bwtest-server-badge');
  13546. const sideBadge = document.getElementById('badge-bwtest-server');
  13547. if (s.enabled && s.running) {
  13548. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13549. if (badge) {
  13550. badge.innerText = `Port ${s.port} (Active)`;
  13551. badge.className = 'text-emerald-400 font-bold';
  13552. }
  13553. if (sideBadge) {
  13554. sideBadge.innerText = s.port;
  13555. 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';
  13556. }
  13557. } else {
  13558. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13559. if (badge) {
  13560. badge.innerText = `Disabled`;
  13561. badge.className = 'text-slate-500 font-bold';
  13562. }
  13563. if (sideBadge) {
  13564. sideBadge.innerText = 'Off';
  13565. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13566. }
  13567. }
  13568. // Modal fields
  13569. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13570. const serverModal = document.getElementById('modal-bwtest-server');
  13571. const editing = serverModal && !serverModal.classList.contains('hidden');
  13572. if (toggle && !editing) toggle.checked = !!s.enabled;
  13573. const portInp = document.getElementById('bwtest-server-port-input');
  13574. if (portInp && !editing) portInp.value = s.port || 2000;
  13575. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13576. if (actSess) actSess.innerText = s.active_sessions || 0;
  13577. const totServ = document.getElementById('bwtest-modal-total-served');
  13578. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13579. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13580. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13581. } catch (err) {
  13582. console.error('Failed to fetch BwTest server status:', err);
  13583. }
  13584. }
  13585. function openBwTestServerModal() {
  13586. const cfg = bwtestState.serverConfig;
  13587. if (cfg) {
  13588. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13589. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13590. }
  13591. fetchBwTestServerStatus();
  13592. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13593. }
  13594. function closeBwTestServerModal() {
  13595. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13596. }
  13597. async function submitBwTestServerSettings(e) {
  13598. e.preventDefault();
  13599. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13600. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13601. try {
  13602. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13603. method: 'POST',
  13604. headers: { 'Content-Type': 'application/json' },
  13605. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13606. });
  13607. if (!res.ok) {
  13608. const err = await res.json();
  13609. throw new Error(err.error || 'Failed to update server configuration');
  13610. }
  13611. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13612. closeBwTestServerModal();
  13613. fetchBwTestServerStatus();
  13614. } catch (err) {
  13615. showToast('Server Configuration Error', err.message, 'error');
  13616. }
  13617. }
  13618. function setBwTestTarget(target) {
  13619. const inp = document.getElementById('bwtest-input-target');
  13620. if (inp) inp.value = target;
  13621. }
  13622. function setBwTestProtocol(proto) {
  13623. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13624. if (hiddenInp) hiddenInp.value = proto;
  13625. const btnUdp = document.getElementById('bwtest-proto-udp');
  13626. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13627. const badge = document.getElementById('bwtest-proto-badge');
  13628. const pktField = document.getElementById('bwtest-field-pktsize');
  13629. 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';
  13630. 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';
  13631. 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';
  13632. if (proto === 'udp') {
  13633. if (btnUdp) {
  13634. btnUdp.className = activeUdpCls;
  13635. const dot = btnUdp.querySelector('span');
  13636. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13637. }
  13638. if (btnTcp) {
  13639. btnTcp.className = inactiveCls;
  13640. const dot = btnTcp.querySelector('span');
  13641. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13642. }
  13643. if (badge) {
  13644. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13645. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13646. }
  13647. if (pktField) pktField.classList.remove('opacity-40');
  13648. } else {
  13649. if (btnUdp) {
  13650. btnUdp.className = inactiveCls;
  13651. const dot = btnUdp.querySelector('span');
  13652. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13653. }
  13654. if (btnTcp) {
  13655. btnTcp.className = activeTcpCls;
  13656. const dot = btnTcp.querySelector('span');
  13657. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13658. }
  13659. if (badge) {
  13660. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13661. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13662. }
  13663. if (pktField) pktField.classList.add('opacity-40');
  13664. }
  13665. }
  13666. function setBwTestDirection(dir) {
  13667. const hiddenInp = document.getElementById('bwtest-input-direction');
  13668. if (hiddenInp) hiddenInp.value = dir;
  13669. const btnBoth = document.getElementById('bwtest-dir-both');
  13670. const btnTx = document.getElementById('bwtest-dir-tx');
  13671. const btnRx = document.getElementById('bwtest-dir-rx');
  13672. 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';
  13673. 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';
  13674. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13675. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13676. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13677. }
  13678. function setBwTestLimit(bps) {
  13679. const sel = document.getElementById('bwtest-input-limit');
  13680. if (sel) sel.value = String(bps);
  13681. }
  13682. async function checkActiveBwTest() {
  13683. try {
  13684. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13685. if (!res.ok) return;
  13686. const st = await res.json();
  13687. if (st.running) {
  13688. setBwTestRunningUI(true);
  13689. processBwTestStatus(st);
  13690. startBwTestTelemetry();
  13691. }
  13692. } catch (err) {
  13693. console.error('Failed to check active BwTest:', err);
  13694. }
  13695. }
  13696. async function startBwTest(e) {
  13697. if (e && e.preventDefault) e.preventDefault();
  13698. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13699. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13700. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13701. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13702. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13703. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13704. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13705. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13706. bwtestState.targetDuration = duration;
  13707. bwtestState.chartPoints = [];
  13708. bwtestState.peakTx = 0;
  13709. bwtestState.peakRx = 0;
  13710. bwtestState.lastSampleElapsed = -1;
  13711. bwtestState.sessionID = null;
  13712. // Clear UI elements
  13713. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13714. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13715. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13716. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13717. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13718. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13719. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13720. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13721. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13722. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13723. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13724. const tbody = document.getElementById('bwtest-samples-tbody');
  13725. if (tbody) tbody.innerHTML = '';
  13726. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13727. setBwTestRunningUI(true);
  13728. try {
  13729. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13730. method: 'POST',
  13731. headers: { 'Content-Type': 'application/json' },
  13732. body: JSON.stringify({
  13733. target,
  13734. port,
  13735. direction,
  13736. protocol,
  13737. bandwidth_limit,
  13738. packet_size,
  13739. streams,
  13740. duration
  13741. })
  13742. });
  13743. if (!res.ok) {
  13744. const err = await res.json();
  13745. throw new Error(err.error || 'Failed to start bandwidth test');
  13746. }
  13747. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13748. startBwTestTelemetry();
  13749. } catch (err) {
  13750. setBwTestRunningUI(false);
  13751. showToast('Start Failed', err.message, 'error');
  13752. }
  13753. }
  13754. function setBwTestRunningUI(running) {
  13755. bwtestState.running = running;
  13756. const startBtn = document.getElementById('bwtest-btn-start');
  13757. const stopBtn = document.getElementById('bwtest-btn-stop');
  13758. const badge = document.getElementById('bwtest-run-status-badge');
  13759. const ph = document.getElementById('bwtest-chart-placeholder');
  13760. if (running) {
  13761. if (startBtn) {
  13762. startBtn.disabled = true;
  13763. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13764. }
  13765. if (stopBtn) {
  13766. stopBtn.disabled = false;
  13767. stopBtn.classList.remove('opacity-40');
  13768. }
  13769. if (badge) {
  13770. badge.innerText = 'TESTING...';
  13771. 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';
  13772. }
  13773. if (ph) ph.style.display = 'none';
  13774. } else {
  13775. if (startBtn) {
  13776. startBtn.disabled = false;
  13777. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13778. }
  13779. if (stopBtn) {
  13780. stopBtn.disabled = true;
  13781. stopBtn.classList.add('opacity-40');
  13782. }
  13783. if (badge) {
  13784. badge.innerText = 'IDLE';
  13785. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13786. }
  13787. }
  13788. }
  13789. async function stopBwTest() {
  13790. try {
  13791. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13792. if (!res.ok) throw new Error(await responseError(res));
  13793. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13794. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13795. } catch (err) {
  13796. showToast('Stop Failed', err.message, 'error');
  13797. }
  13798. }
  13799. async function responseError(res) {
  13800. const text = await res.text();
  13801. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13802. catch { return text || `HTTP ${res.status}`; }
  13803. }
  13804. function processBwTestStatus(st) {
  13805. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13806. bwtestState.sessionID = st.session_id;
  13807. bwtestState.lastSampleElapsed = -1;
  13808. }
  13809. for (const sample of st.recent_samples || []) {
  13810. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13811. handleBwTestSample(sample);
  13812. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13813. }
  13814. }
  13815. if (!st.running) {
  13816. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13817. bwtestState.pollTimer = null;
  13818. setBwTestRunningUI(false);
  13819. handleBwTestFinish(st.summary, st.error);
  13820. }
  13821. }
  13822. function startBwTestTelemetry() {
  13823. if (!state.currentUser) return;
  13824. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13825. let busy = false;
  13826. const poll = async () => {
  13827. if (busy || !state.currentUser || document.hidden) return;
  13828. busy = true;
  13829. try {
  13830. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13831. if (!res.ok) throw new Error(await responseError(res));
  13832. processBwTestStatus(await res.json());
  13833. } catch (err) {
  13834. console.error('BwTest polling error:', err);
  13835. } finally { busy = false; }
  13836. };
  13837. bwtestState.pollTimer = setInterval(poll, 400);
  13838. poll();
  13839. }
  13840. function handleBwTestSample(s) {
  13841. if (!s) return;
  13842. const payloadHint = document.getElementById('bwtest-effective-payload');
  13843. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13844. const txMbps = s.tx_mbps || 0;
  13845. const rxMbps = s.rx_mbps || 0;
  13846. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13847. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13848. // KPI updates
  13849. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13850. if (elTx) {
  13851. elTx.innerText = txMbps.toFixed(2);
  13852. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13853. }
  13854. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13855. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13856. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13857. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13858. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13859. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13860. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13861. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13862. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13863. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13864. const elLoss = document.getElementById('bwtest-stat-loss');
  13865. if (elLoss) {
  13866. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13867. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13868. }
  13869. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13870. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13871. const elJitter = document.getElementById('bwtest-stat-jitter');
  13872. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13873. const elTime = document.getElementById('bwtest-stat-time');
  13874. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13875. const elData = document.getElementById('bwtest-stat-data');
  13876. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13877. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13878. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13879. // Append point to chart buffer
  13880. bwtestState.chartPoints.push({
  13881. elapsed: s.elapsed_sec || 0,
  13882. tx: txMbps,
  13883. rx: rxMbps
  13884. });
  13885. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13886. bwtestState.chartPoints.shift();
  13887. }
  13888. drawBwTestChart();
  13889. // Add row to breakdown table
  13890. const tbody = document.getElementById('bwtest-samples-tbody');
  13891. if (tbody) {
  13892. const tr = document.createElement('tr');
  13893. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13894. tr.innerHTML = `
  13895. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13896. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13897. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13898. <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>
  13899. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13900. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13901. `;
  13902. tbody.insertBefore(tr, tbody.firstChild);
  13903. const countEl = document.getElementById('bwtest-sample-count');
  13904. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13905. }
  13906. }
  13907. function handleBwTestFinish(summary, error) {
  13908. const badge = document.getElementById('bwtest-run-status-badge');
  13909. if (error) {
  13910. showToast('Benchmark Error', error, 'error');
  13911. if (badge) {
  13912. badge.innerText = 'ERROR';
  13913. 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';
  13914. }
  13915. } else if (summary) {
  13916. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13917. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13918. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13919. if (badge) {
  13920. badge.innerText = 'COMPLETED';
  13921. 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';
  13922. }
  13923. }
  13924. loadBwTestHistory();
  13925. fetchBwTestServerStatus();
  13926. }
  13927. function resizeBwTestCanvas() {
  13928. const canvas = document.getElementById('bwtest-chart');
  13929. if (!canvas || !canvas.parentElement) return;
  13930. const rect = canvas.parentElement.getBoundingClientRect();
  13931. const dpr = window.devicePixelRatio || 1;
  13932. canvas.width = rect.width * dpr;
  13933. canvas.height = rect.height * dpr;
  13934. const ctx = canvas.getContext('2d');
  13935. ctx.scale(dpr, dpr);
  13936. drawBwTestChart();
  13937. }
  13938. window.addEventListener('resize', () => {
  13939. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13940. });
  13941. function drawBwTestChart() {
  13942. const canvas = document.getElementById('bwtest-chart');
  13943. if (!canvas) return;
  13944. const ctx = canvas.getContext('2d');
  13945. const dpr = window.devicePixelRatio || 1;
  13946. const width = canvas.width / dpr;
  13947. const height = canvas.height / dpr;
  13948. ctx.clearRect(0, 0, width, height);
  13949. const points = bwtestState.chartPoints;
  13950. if (!points || points.length === 0) return;
  13951. // Determine scale ceiling
  13952. let maxRate = 10;
  13953. for (const p of points) {
  13954. if (p.tx > maxRate) maxRate = p.tx;
  13955. if (p.rx > maxRate) maxRate = p.rx;
  13956. }
  13957. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13958. const paddingLeft = 55;
  13959. const paddingBottom = 24;
  13960. const paddingTop = 12;
  13961. const paddingRight = 16;
  13962. const chartW = width - paddingLeft - paddingRight;
  13963. const chartH = height - paddingTop - paddingBottom;
  13964. // Grid Lines and Y-Axis labels
  13965. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13966. ctx.lineWidth = 1;
  13967. ctx.fillStyle = '#94a3b8';
  13968. ctx.font = '10px monospace';
  13969. ctx.textAlign = 'right';
  13970. const gridSteps = 4;
  13971. for (let i = 0; i <= gridSteps; i++) {
  13972. const val = (maxRate / gridSteps) * i;
  13973. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13974. ctx.beginPath();
  13975. ctx.moveTo(paddingLeft, y);
  13976. ctx.lineTo(width - paddingRight, y);
  13977. ctx.stroke();
  13978. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13979. }
  13980. // Draw TX Line (Cyan #22d3ee)
  13981. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13982. // Draw RX Line (Purple #a855f7)
  13983. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13984. }
  13985. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13986. if (points.length < 2) return;
  13987. const stepX = w / Math.max(points.length - 1, 1);
  13988. // Gradient area fill
  13989. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13990. grad.addColorStop(0, fillColor);
  13991. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13992. ctx.beginPath();
  13993. points.forEach((p, idx) => {
  13994. const x = left + idx * stepX;
  13995. const val = valFn(p);
  13996. const y = top + h - (val / maxVal) * h;
  13997. if (idx === 0) {
  13998. ctx.moveTo(x, y);
  13999. } else {
  14000. ctx.lineTo(x, y);
  14001. }
  14002. });
  14003. // Complete path for fill
  14004. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14005. ctx.lineTo(left, top + h);
  14006. ctx.closePath();
  14007. ctx.fillStyle = grad;
  14008. ctx.fill();
  14009. // Draw line stroke
  14010. ctx.beginPath();
  14011. ctx.lineWidth = 2.5;
  14012. ctx.strokeStyle = strokeColor;
  14013. points.forEach((p, idx) => {
  14014. const x = left + idx * stepX;
  14015. const val = valFn(p);
  14016. const y = top + h - (val / maxVal) * h;
  14017. if (idx === 0) {
  14018. ctx.moveTo(x, y);
  14019. } else {
  14020. ctx.lineTo(x, y);
  14021. }
  14022. });
  14023. ctx.stroke();
  14024. // Draw end point halo
  14025. const lastP = points[points.length - 1];
  14026. const lastX = left + (points.length - 1) * stepX;
  14027. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14028. ctx.fillStyle = strokeColor;
  14029. ctx.beginPath();
  14030. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14031. ctx.fill();
  14032. }
  14033. async function loadBwTestHistory() {
  14034. try {
  14035. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14036. if (!res.ok) return;
  14037. const list = await res.json();
  14038. renderBwTestHistory(Array.isArray(list) ? list : []);
  14039. } catch (err) {
  14040. console.error('Failed to load BwTest history:', err);
  14041. }
  14042. }
  14043. function renderBwTestHistory(list) {
  14044. const tbody = document.getElementById('bwtest-history-tbody');
  14045. if (!tbody) return;
  14046. if (list.length === 0) {
  14047. 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>`;
  14048. return;
  14049. }
  14050. tbody.innerHTML = '';
  14051. list.forEach(item => {
  14052. const s = item.summary || {};
  14053. const tr = document.createElement('tr');
  14054. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14055. const dirBadge = item.direction === 'both'
  14056. ? `<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>`
  14057. : item.direction === 'tx'
  14058. ? `<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>`
  14059. : `<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>`;
  14060. const protoBadge = item.protocol === 'tcp'
  14061. ? `<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>`
  14062. : `<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>`;
  14063. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14064. tr.innerHTML = `
  14065. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14066. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14067. <td class="py-2.5 px-4">${protoBadge}</td>
  14068. <td class="py-2.5 px-4">${dirBadge}</td>
  14069. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14070. <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>
  14071. <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>
  14072. <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>
  14073. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14074. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14075. `;
  14076. tbody.appendChild(tr);
  14077. });
  14078. }
  14079. // ======================== SETTINGS & ROUTER DNS ========================
  14080. state.settingsSubTab = 'dns';
  14081. state.dnsSettings = null;
  14082. state.dnsStaticRecords = [];
  14083. state.dnsStatus = null;
  14084. function switchSettingsSubTab(sub) {
  14085. state.settingsSubTab = sub;
  14086. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14087. const btnSys = document.getElementById('btn-settings-subtab-system');
  14088. const tabDns = document.getElementById('settings-subtab-dns');
  14089. const tabSys = document.getElementById('settings-subtab-system');
  14090. if (sub === 'dns') {
  14091. if (btnDns) {
  14092. 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';
  14093. }
  14094. if (btnSys) {
  14095. 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';
  14096. }
  14097. tabDns?.classList.remove('hidden');
  14098. tabSys?.classList.add('hidden');
  14099. loadDNSSettings();
  14100. } else {
  14101. if (btnSys) {
  14102. 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';
  14103. }
  14104. if (btnDns) {
  14105. 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';
  14106. }
  14107. tabSys?.classList.remove('hidden');
  14108. tabDns?.classList.add('hidden');
  14109. loadSystemSettings();
  14110. }
  14111. }
  14112. async function loadSettingsData(showLoading = false) {
  14113. if (state.settingsSubTab === 'system') {
  14114. await loadSystemSettings();
  14115. } else {
  14116. await loadDNSSettings();
  14117. }
  14118. }
  14119. async function loadDNSSettings() {
  14120. try {
  14121. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14122. fetch(`${API_BASE}/dns/settings`),
  14123. fetch(`${API_BASE}/dns/static`),
  14124. fetch(`${API_BASE}/dns/status`)
  14125. ]);
  14126. if (settingsRes.ok) {
  14127. state.dnsSettings = await settingsRes.json();
  14128. populateDNSSettingsForm(state.dnsSettings);
  14129. }
  14130. if (staticRes.ok) {
  14131. state.dnsStaticRecords = await staticRes.json();
  14132. renderStaticDNSList();
  14133. }
  14134. if (statusRes.ok) {
  14135. state.dnsStatus = await statusRes.json();
  14136. updateDNSStatusView(state.dnsStatus);
  14137. }
  14138. } catch (err) {
  14139. console.error('Failed to load DNS settings:', err);
  14140. }
  14141. }
  14142. function populateDNSSettingsForm(s) {
  14143. if (!s) return;
  14144. const dnsForm = document.getElementById('form-dns-settings');
  14145. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14146. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14147. if (dynamicEl) {
  14148. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14149. 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(' ');
  14150. } else {
  14151. dynamicEl.innerText = 'None';
  14152. }
  14153. }
  14154. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14155. if (isEditing) return;
  14156. const serversInput = document.getElementById('dns-servers-input');
  14157. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14158. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14159. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14160. const domainInput = document.getElementById('dns-domain-input');
  14161. if (domainInput) domainInput.value = s.domain || '';
  14162. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14163. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14164. }
  14165. function updateDNSStatusView(st) {
  14166. if (!st) return;
  14167. const preview = document.getElementById('dns-resolv-preview');
  14168. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14169. const pillText = document.getElementById('dns-live-status-text');
  14170. const pill = document.getElementById('dns-live-status-pill');
  14171. if (pill && pillText) {
  14172. if (st.service_running) {
  14173. 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';
  14174. pillText.innerText = 'DNS Service Active';
  14175. } else {
  14176. 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';
  14177. pillText.innerText = 'DNS Service Inactive';
  14178. }
  14179. }
  14180. }
  14181. function appendDNSPreset(preset) {
  14182. const input = document.getElementById('dns-servers-input');
  14183. if (!input) return;
  14184. const dnsForm = document.getElementById('form-dns-settings');
  14185. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14186. const current = input.value.trim();
  14187. if (!current) {
  14188. input.value = preset;
  14189. } else {
  14190. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14191. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14192. toAdd.forEach(ip => {
  14193. if (!existing.includes(ip)) existing.push(ip);
  14194. });
  14195. input.value = existing.join(', ');
  14196. }
  14197. }
  14198. async function saveDNSSettings(e) {
  14199. e.preventDefault();
  14200. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14201. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14202. if (servers.length === 0) {
  14203. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14204. return;
  14205. }
  14206. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14207. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14208. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14209. try {
  14210. const res = await fetch(`${API_BASE}/dns/settings`, {
  14211. method: 'POST',
  14212. headers: { 'Content-Type': 'application/json' },
  14213. body: JSON.stringify({
  14214. servers: servers,
  14215. cache_size: cacheSize,
  14216. domain: domain,
  14217. allow_remote_requests: allowRemote
  14218. })
  14219. });
  14220. const data = await res.json();
  14221. if (res.ok) {
  14222. const dnsForm = document.getElementById('form-dns-settings');
  14223. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14224. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14225. loadDNSSettings();
  14226. } else {
  14227. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14228. }
  14229. } catch (err) {
  14230. showToast('Error', err.message, 'error');
  14231. }
  14232. }
  14233. async function flushDNSCache() {
  14234. try {
  14235. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14236. if (res.ok) {
  14237. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14238. loadDNSSettings();
  14239. } else {
  14240. const err = await res.json();
  14241. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14242. }
  14243. } catch (err) {
  14244. showToast('Error', err.message, 'error');
  14245. }
  14246. }
  14247. function renderStaticDNSList() {
  14248. const tbody = document.getElementById('dns-static-tbody');
  14249. const empty = document.getElementById('dns-static-empty');
  14250. const badge = document.getElementById('dns-static-count-badge');
  14251. if (!tbody) return;
  14252. tbody.innerHTML = '';
  14253. const records = state.dnsStaticRecords || [];
  14254. if (badge) badge.innerText = `${records.length} Records`;
  14255. if (records.length === 0) {
  14256. empty?.classList.remove('hidden');
  14257. return;
  14258. }
  14259. empty?.classList.add('hidden');
  14260. records.forEach(rec => {
  14261. const tr = document.createElement('tr');
  14262. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14263. tr.innerHTML = `
  14264. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14265. <td class="py-2.5 px-4">
  14266. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14267. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14268. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14269. }">
  14270. ${rec.type || 'A'}
  14271. </span>
  14272. </td>
  14273. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14274. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14275. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14276. <td class="py-2.5 px-4">
  14277. <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'}">
  14278. ${rec.disabled ? 'Disabled' : 'Active'}
  14279. </span>
  14280. </td>
  14281. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14282. <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>
  14283. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14284. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14285. </td>
  14286. `;
  14287. tbody.appendChild(tr);
  14288. });
  14289. }
  14290. function openStaticDNSModal(id = null) {
  14291. const modal = document.getElementById('modal-static-dns');
  14292. const title = document.getElementById('modal-static-dns-title');
  14293. const form = document.getElementById('form-static-dns');
  14294. if (!modal || !form) return;
  14295. form.reset();
  14296. document.getElementById('modal-static-dns-id').value = '';
  14297. if (id) {
  14298. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14299. if (rec) {
  14300. if (title) title.innerText = 'Edit Static DNS Record';
  14301. document.getElementById('modal-static-dns-id').value = rec.id;
  14302. document.getElementById('modal-static-dns-name').value = rec.name;
  14303. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14304. document.getElementById('modal-static-dns-addr').value = rec.address;
  14305. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14306. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14307. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14308. }
  14309. } else {
  14310. if (title) title.innerText = 'Add Static DNS Record';
  14311. }
  14312. modal.classList.remove('hidden');
  14313. }
  14314. function closeStaticDNSModal() {
  14315. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14316. }
  14317. async function submitSaveStaticDNS(e) {
  14318. e.preventDefault();
  14319. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14320. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14321. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14322. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14323. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14324. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14325. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14326. if (!name || !address) {
  14327. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14328. return;
  14329. }
  14330. try {
  14331. const res = await fetch(`${API_BASE}/dns/static`, {
  14332. method: 'POST',
  14333. headers: { 'Content-Type': 'application/json' },
  14334. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14335. });
  14336. const data = await res.json();
  14337. if (res.ok) {
  14338. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14339. closeStaticDNSModal();
  14340. loadDNSSettings();
  14341. } else {
  14342. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14343. }
  14344. } catch (err) {
  14345. showToast('Error', err.message, 'error');
  14346. }
  14347. }
  14348. async function deleteStaticDNS(id) {
  14349. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14350. try {
  14351. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14352. if (res.ok) {
  14353. showToast('Deleted', 'Static DNS record deleted', 'success');
  14354. loadDNSSettings();
  14355. }
  14356. } catch (err) {
  14357. showToast('Error', err.message, 'error');
  14358. }
  14359. }
  14360. async function toggleStaticDNS(id, disabled) {
  14361. try {
  14362. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14363. method: 'POST',
  14364. headers: { 'Content-Type': 'application/json' },
  14365. body: JSON.stringify({ disabled })
  14366. });
  14367. if (res.ok) {
  14368. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14369. loadDNSSettings();
  14370. }
  14371. } catch (err) {
  14372. showToast('Error', err.message, 'error');
  14373. }
  14374. }
  14375. async function loadSystemSettings() {
  14376. try {
  14377. const sysForm = document.getElementById('form-system-settings');
  14378. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14379. const res = await fetch(`${API_BASE}/system/settings`);
  14380. if (res.ok) {
  14381. const data = await res.json();
  14382. if (!isEditing) {
  14383. const hostInput = document.getElementById('system-hostname-input');
  14384. if (hostInput) hostInput.value = data.hostname || '';
  14385. const tzInput = document.getElementById('system-timezone-input');
  14386. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14387. }
  14388. }
  14389. } catch (err) {
  14390. console.error('Failed to load system settings:', err);
  14391. }
  14392. }
  14393. async function saveSystemSettings(e) {
  14394. e.preventDefault();
  14395. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14396. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14397. try {
  14398. const res = await fetch(`${API_BASE}/system/settings`, {
  14399. method: 'POST',
  14400. headers: { 'Content-Type': 'application/json' },
  14401. body: JSON.stringify({ hostname, timezone })
  14402. });
  14403. const data = await res.json();
  14404. if (res.ok) {
  14405. const sysForm = document.getElementById('form-system-settings');
  14406. if (sysForm) sysForm.dataset.dirty = 'false';
  14407. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14408. const sideH = document.getElementById('side-hostname');
  14409. if (sideH) sideH.innerText = data.hostname;
  14410. } else {
  14411. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14412. }
  14413. } catch (err) {
  14414. showToast('Error', err.message, 'error');
  14415. }
  14416. }
  14417. // =============================================================================
  14418. // AUTHENTICATION & USER MANAGER
  14419. // =============================================================================
  14420. async function checkAuthStatus() {
  14421. try {
  14422. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14423. headers: {
  14424. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14425. }
  14426. });
  14427. if (res.ok) {
  14428. const user = await res.json();
  14429. state.currentUser = user;
  14430. updateUserProfileHeader(user);
  14431. hideLoginScreen();
  14432. state.isPolling = true;
  14433. fetchData();
  14434. initLiveTrafficStream();
  14435. return true;
  14436. } else {
  14437. showLoginScreen(false);
  14438. return false;
  14439. }
  14440. } catch (err) {
  14441. showLoginScreen(false);
  14442. return false;
  14443. }
  14444. }
  14445. function showLoginScreen(isExpired = false) {
  14446. const el = document.getElementById('login-screen');
  14447. if (el) el.classList.remove('hidden');
  14448. const errEl = document.getElementById('login-error');
  14449. const errTxt = document.getElementById('login-error-text');
  14450. if (isExpired && errEl && errTxt) {
  14451. errTxt.innerText = 'Session expired. Please sign in again.';
  14452. errEl.classList.remove('hidden');
  14453. } else if (errEl) {
  14454. errEl.classList.add('hidden');
  14455. }
  14456. const pwInput = document.getElementById('login-password');
  14457. if (pwInput) pwInput.value = '';
  14458. const userInput = document.getElementById('login-username');
  14459. if (userInput && !userInput.value) userInput.focus();
  14460. else if (pwInput) pwInput.focus();
  14461. }
  14462. function hideLoginScreen() {
  14463. const el = document.getElementById('login-screen');
  14464. if (el) el.classList.add('hidden');
  14465. const errEl = document.getElementById('login-error');
  14466. if (errEl) errEl.classList.add('hidden');
  14467. }
  14468. async function handleLoginSubmit(event) {
  14469. event.preventDefault();
  14470. const username = (document.getElementById('login-username')?.value || '').trim();
  14471. const password = document.getElementById('login-password')?.value || '';
  14472. const errEl = document.getElementById('login-error');
  14473. const errTxt = document.getElementById('login-error-text');
  14474. const btn = document.getElementById('login-submit-btn');
  14475. const btnText = document.getElementById('login-btn-text');
  14476. const spinner = document.getElementById('login-btn-spinner');
  14477. if (!username || !password) {
  14478. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14479. if (errEl) errEl.classList.remove('hidden');
  14480. return;
  14481. }
  14482. if (errEl) errEl.classList.add('hidden');
  14483. if (btn) btn.disabled = true;
  14484. if (btnText) btnText.innerText = 'Authenticating...';
  14485. if (spinner) spinner.classList.remove('hidden');
  14486. try {
  14487. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14488. method: 'POST',
  14489. headers: { 'Content-Type': 'application/json' },
  14490. body: JSON.stringify({ username, password })
  14491. });
  14492. const data = await res.json();
  14493. if (res.ok && data.success) {
  14494. localStorage.setItem('debtik_token', data.token);
  14495. state.currentUser = data.user;
  14496. updateUserProfileHeader(data.user);
  14497. hideLoginScreen();
  14498. state.isPolling = true;
  14499. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14500. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14501. navigate(hash);
  14502. fetchData();
  14503. initLiveTrafficStream();
  14504. // Ensure background telemetry polling is active
  14505. if (!window._telemetryInterval) {
  14506. window._telemetryInterval = setInterval(() => {
  14507. if (state.isPolling && state.currentUser && !document.hidden) {
  14508. fetchData(false);
  14509. }
  14510. }, 5000);
  14511. }
  14512. } else {
  14513. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14514. if (errEl) errEl.classList.remove('hidden');
  14515. }
  14516. } catch (err) {
  14517. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14518. if (errEl) errEl.classList.remove('hidden');
  14519. } finally {
  14520. if (btn) btn.disabled = false;
  14521. if (btnText) btnText.innerText = 'Sign In to Controller';
  14522. if (spinner) spinner.classList.add('hidden');
  14523. }
  14524. }
  14525. async function handleLogoutClick() {
  14526. try {
  14527. await originalFetch(`${API_BASE}/auth/logout`, {
  14528. method: 'POST',
  14529. headers: {
  14530. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14531. }
  14532. });
  14533. } catch (e) {}
  14534. stopSessionPolling();
  14535. localStorage.removeItem('debtik_token');
  14536. state.currentUser = null;
  14537. state.isPolling = false;
  14538. if (window._telemetryInterval) {
  14539. clearInterval(window._telemetryInterval);
  14540. window._telemetryInterval = null;
  14541. }
  14542. if (trafficEventSource) {
  14543. trafficEventSource.close();
  14544. trafficEventSource = null;
  14545. }
  14546. if (trafficPollFallback) {
  14547. clearInterval(trafficPollFallback);
  14548. trafficPollFallback = null;
  14549. }
  14550. showLoginScreen(false);
  14551. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14552. }
  14553. function togglePasswordVisibility(id) {
  14554. const input = document.getElementById(id);
  14555. if (!input) return;
  14556. input.type = input.type === 'password' ? 'text' : 'password';
  14557. }
  14558. function toggleUserMenu() {
  14559. const menu = document.getElementById('user-menu-dropdown');
  14560. if (menu) menu.classList.toggle('hidden');
  14561. }
  14562. function closeUserMenu() {
  14563. const menu = document.getElementById('user-menu-dropdown');
  14564. if (menu) menu.classList.add('hidden');
  14565. }
  14566. // Close user menu on outside click
  14567. document.addEventListener('click', (e) => {
  14568. const menu = document.getElementById('user-menu-dropdown');
  14569. if (!menu || menu.classList.contains('hidden')) return;
  14570. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14571. menu.classList.add('hidden');
  14572. }
  14573. });
  14574. function updateUserProfileHeader(user) {
  14575. if (!user) return;
  14576. const navName = document.getElementById('nav-user-name');
  14577. if (navName) navName.innerText = user.username;
  14578. const dropName = document.getElementById('dropdown-user-name');
  14579. if (dropName) dropName.innerText = user.username;
  14580. const navRole = document.getElementById('nav-user-role');
  14581. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14582. const navAvatar = document.getElementById('nav-user-avatar');
  14583. if (navAvatar) {
  14584. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14585. navAvatar.innerText = initials;
  14586. }
  14587. const statCurUser = document.getElementById('stat-current-user');
  14588. if (statCurUser) statCurUser.innerText = user.username;
  14589. const statCurRole = document.getElementById('stat-current-role');
  14590. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14591. // Role permissions UI visibility: hide user management for non-admins
  14592. const isFullAdmin = user.role === 'full';
  14593. const navUsers = document.getElementById('nav-users');
  14594. if (navUsers) {
  14595. if (isFullAdmin) navUsers.classList.remove('hidden');
  14596. else navUsers.classList.add('hidden');
  14597. }
  14598. const dropdownUsers = document.getElementById('dropdown-item-users');
  14599. if (dropdownUsers) {
  14600. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14601. else dropdownUsers.classList.add('hidden');
  14602. }
  14603. }
  14604. // ================= User Management CRUD =================
  14605. async function loadUsers(isManual = false) {
  14606. try {
  14607. const res = await fetch(`${API_BASE}/users`);
  14608. if (res.status === 403) {
  14609. const tbody = document.getElementById('users-table-tbody');
  14610. if (tbody) {
  14611. tbody.innerHTML = `
  14612. <tr>
  14613. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14614. <div class="inline-flex items-center gap-2">
  14615. <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>
  14616. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14617. </div>
  14618. </td>
  14619. </tr>
  14620. `;
  14621. }
  14622. return;
  14623. }
  14624. if (res.ok) {
  14625. state.users = await res.json();
  14626. renderUsersTable();
  14627. const totalUsers = document.getElementById('stat-total-users');
  14628. if (totalUsers) totalUsers.innerText = state.users.length;
  14629. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14630. const adminUsers = document.getElementById('stat-admin-users');
  14631. if (adminUsers) adminUsers.innerText = adminCount;
  14632. const badgeCount = document.getElementById('badge-users-count');
  14633. if (badgeCount) badgeCount.innerText = state.users.length;
  14634. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14635. }
  14636. } catch (err) {
  14637. console.error('Failed to load users:', err);
  14638. }
  14639. }
  14640. function renderUsersTable() {
  14641. const tbody = document.getElementById('users-table-tbody');
  14642. const emptyState = document.getElementById('users-empty-state');
  14643. if (!tbody) return;
  14644. tbody.innerHTML = '';
  14645. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14646. const filtered = (state.users || []).filter(u => {
  14647. if (!query) return true;
  14648. return u.username.toLowerCase().includes(query) ||
  14649. (u.role || '').toLowerCase().includes(query) ||
  14650. (u.comment || '').toLowerCase().includes(query);
  14651. });
  14652. if (filtered.length === 0) {
  14653. if (emptyState) emptyState.classList.remove('hidden');
  14654. return;
  14655. }
  14656. if (emptyState) emptyState.classList.add('hidden');
  14657. const currentAuthUser = state.currentUser?.username || '';
  14658. filtered.forEach(u => {
  14659. const isSelf = u.username === currentAuthUser;
  14660. const isFull = u.role === 'full';
  14661. const isWrite = u.role === 'write';
  14662. 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>`;
  14663. if (isFull) {
  14664. 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>`;
  14665. } else if (isWrite) {
  14666. 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>`;
  14667. }
  14668. const statusBadge = u.disabled
  14669. ? `<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>`
  14670. : `<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>`;
  14671. let lastLoginText = 'Never';
  14672. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14673. const dt = new Date(u.last_login_at);
  14674. lastLoginText = dt.toLocaleString();
  14675. }
  14676. const initials = u.username.slice(0, 2).toUpperCase();
  14677. const tr = document.createElement('tr');
  14678. tr.className = 'hover:bg-slate-800/40 transition group';
  14679. tr.innerHTML = `
  14680. <td class="py-3 px-4">
  14681. <div class="flex items-center gap-3">
  14682. <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">
  14683. ${initials}
  14684. </div>
  14685. <div>
  14686. <div class="font-bold text-white text-xs flex items-center gap-2">
  14687. <span>${escapeHtml(u.username)}</span>
  14688. ${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>' : ''}
  14689. </div>
  14690. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14691. </div>
  14692. </div>
  14693. </td>
  14694. <td class="py-3 px-4 font-sans">
  14695. ${roleBadge}
  14696. </td>
  14697. <td class="py-3 px-4 font-sans">
  14698. ${statusBadge}
  14699. </td>
  14700. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14701. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14702. </td>
  14703. <td class="py-3 px-4 text-slate-400 text-xs">
  14704. ${lastLoginText}
  14705. </td>
  14706. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14707. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14708. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14709. <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>
  14710. </button>
  14711. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14712. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14713. <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>
  14714. </button>
  14715. ${!isSelf ? `
  14716. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14717. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14718. <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>
  14719. </button>
  14720. ` : ''}
  14721. </td>
  14722. `;
  14723. tbody.appendChild(tr);
  14724. });
  14725. }
  14726. function openAddUserModal() {
  14727. document.getElementById('user-add-username').value = '';
  14728. document.getElementById('user-add-password').value = '';
  14729. document.getElementById('user-add-confirm').value = '';
  14730. document.getElementById('user-add-role').value = 'full';
  14731. document.getElementById('user-add-comment').value = '';
  14732. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14733. document.getElementById('user-add-username')?.focus();
  14734. }
  14735. function closeAddUserModal() {
  14736. document.getElementById('modal-add-user')?.classList.add('hidden');
  14737. }
  14738. async function submitAddUser(event) {
  14739. event.preventDefault();
  14740. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14741. const password = document.getElementById('user-add-password')?.value || '';
  14742. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14743. const role = document.getElementById('user-add-role')?.value || 'full';
  14744. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14745. if (password !== confirm) {
  14746. showToast('Validation Error', 'Passwords do not match', 'warning');
  14747. return;
  14748. }
  14749. if (password.length < 4) {
  14750. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14751. return;
  14752. }
  14753. try {
  14754. const res = await fetch(`${API_BASE}/users`, {
  14755. method: 'POST',
  14756. headers: { 'Content-Type': 'application/json' },
  14757. body: JSON.stringify({ username, password, role, comment })
  14758. });
  14759. const data = await res.json();
  14760. if (res.ok) {
  14761. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14762. closeAddUserModal();
  14763. loadUsers(false);
  14764. } else {
  14765. showToast('Error', data.message || 'Failed to create user', 'error');
  14766. }
  14767. } catch (err) {
  14768. showToast('Error', err.message, 'error');
  14769. }
  14770. }
  14771. function openEditUserModal(username) {
  14772. const user = (state.users || []).find(u => u.username === username);
  14773. if (!user) return;
  14774. document.getElementById('user-edit-username').value = user.username;
  14775. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14776. document.getElementById('user-edit-role').value = user.role || 'read';
  14777. document.getElementById('user-edit-comment').value = user.comment || '';
  14778. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14779. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14780. }
  14781. function closeEditUserModal() {
  14782. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14783. }
  14784. async function submitEditUser(event) {
  14785. event.preventDefault();
  14786. const username = document.getElementById('user-edit-username')?.value;
  14787. const role = document.getElementById('user-edit-role')?.value || 'read';
  14788. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14789. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14790. try {
  14791. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14792. method: 'PUT',
  14793. headers: { 'Content-Type': 'application/json' },
  14794. body: JSON.stringify({ role, comment, disabled })
  14795. });
  14796. const data = await res.json();
  14797. if (res.ok) {
  14798. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14799. closeEditUserModal();
  14800. loadUsers(false);
  14801. // If updated own role/disabled status, refresh self profile
  14802. if (username === state.currentUser?.username) {
  14803. checkAuthStatus();
  14804. }
  14805. } else {
  14806. showToast('Error', data.message || 'Failed to update user', 'error');
  14807. }
  14808. } catch (err) {
  14809. showToast('Error', err.message, 'error');
  14810. }
  14811. }
  14812. function openAdminResetPasswordModal(username) {
  14813. document.getElementById('admin-reset-username').value = username;
  14814. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14815. document.getElementById('admin-reset-new-pw').value = '';
  14816. document.getElementById('admin-reset-confirm-pw').value = '';
  14817. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14818. document.getElementById('admin-reset-new-pw')?.focus();
  14819. }
  14820. function closeAdminResetPasswordModal() {
  14821. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14822. }
  14823. async function submitAdminResetPassword(event) {
  14824. event.preventDefault();
  14825. const username = document.getElementById('admin-reset-username')?.value;
  14826. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14827. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14828. if (newPassword !== confirm) {
  14829. showToast('Validation Error', 'Passwords do not match', 'warning');
  14830. return;
  14831. }
  14832. if (newPassword.length < 4) {
  14833. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14834. return;
  14835. }
  14836. try {
  14837. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14838. method: 'POST',
  14839. headers: { 'Content-Type': 'application/json' },
  14840. body: JSON.stringify({ new_password: newPassword })
  14841. });
  14842. const data = await res.json();
  14843. if (res.ok) {
  14844. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14845. closeAdminResetPasswordModal();
  14846. } else {
  14847. showToast('Error', data.message || 'Failed to reset password', 'error');
  14848. }
  14849. } catch (err) {
  14850. showToast('Error', err.message, 'error');
  14851. }
  14852. }
  14853. async function deleteUser(username) {
  14854. if (username === state.currentUser?.username) {
  14855. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14856. return;
  14857. }
  14858. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14859. return;
  14860. }
  14861. try {
  14862. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14863. method: 'DELETE'
  14864. });
  14865. const data = await res.json();
  14866. if (res.ok) {
  14867. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14868. loadUsers(false);
  14869. } else {
  14870. showToast('Error', data.message || 'Failed to delete user', 'error');
  14871. }
  14872. } catch (err) {
  14873. showToast('Error', err.message, 'error');
  14874. }
  14875. }
  14876. function openSelfPasswordModal() {
  14877. document.getElementById('self-current-password').value = '';
  14878. document.getElementById('self-new-password').value = '';
  14879. document.getElementById('self-confirm-password').value = '';
  14880. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14881. document.getElementById('self-current-password')?.focus();
  14882. }
  14883. function closeSelfPasswordModal() {
  14884. document.getElementById('modal-self-password')?.classList.add('hidden');
  14885. }
  14886. async function submitSelfPassword(event) {
  14887. event.preventDefault();
  14888. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14889. const newPassword = document.getElementById('self-new-password')?.value || '';
  14890. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14891. if (newPassword !== confirm) {
  14892. showToast('Validation Error', 'New passwords do not match', 'warning');
  14893. return;
  14894. }
  14895. if (newPassword.length < 4) {
  14896. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14897. return;
  14898. }
  14899. try {
  14900. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14901. method: 'POST',
  14902. headers: { 'Content-Type': 'application/json' },
  14903. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14904. });
  14905. const data = await res.json();
  14906. if (res.ok) {
  14907. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14908. closeSelfPasswordModal();
  14909. } else {
  14910. showToast('Error', data.message || 'Failed to change password', 'error');
  14911. }
  14912. } catch (err) {
  14913. showToast('Error', err.message, 'error');
  14914. }
  14915. }
  14916. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14917. state.services = [];
  14918. async function loadServices(manual = false) {
  14919. try {
  14920. const res = await fetch(`${API_BASE}/system/services`);
  14921. if (!res.ok) throw new Error('Failed to load services');
  14922. const data = await res.json();
  14923. state.services = data || [];
  14924. renderServicesTable();
  14925. updateCertificatesBadges();
  14926. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14927. } catch (err) {
  14928. if (manual) showToast('Error', err.message, 'error');
  14929. }
  14930. }
  14931. function renderServicesTable() {
  14932. const tbody = document.getElementById('services-table-body');
  14933. if (!tbody) return;
  14934. if (!state.services || state.services.length === 0) {
  14935. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14936. return;
  14937. }
  14938. tbody.innerHTML = state.services.map(s => {
  14939. const isOff = s.disabled;
  14940. const statusBadge = isOff
  14941. ? '<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>'
  14942. : '<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>';
  14943. const toggleBtn = isOff
  14944. ? `<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>`
  14945. : `<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>`;
  14946. let certBadge = '';
  14947. if (s.name === 'www-ssl') {
  14948. if (s.certificate) {
  14949. 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>`;
  14950. } else {
  14951. 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>`;
  14952. }
  14953. }
  14954. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14955. return `
  14956. <tr class="hover:bg-slate-800/40 transition">
  14957. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14958. <td class="py-3 px-4">
  14959. <div class="flex items-center gap-2">
  14960. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14961. <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">
  14962. <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>
  14963. </button>
  14964. </div>
  14965. </td>
  14966. <td class="py-3 px-4">${statusBadge}</td>
  14967. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14968. <td class="py-3 px-4 text-right">
  14969. <div class="flex items-center justify-end gap-2">
  14970. <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">
  14971. <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>
  14972. <span>Edit</span>
  14973. </button>
  14974. ${toggleBtn}
  14975. </div>
  14976. </td>
  14977. </tr>
  14978. `;
  14979. }).join('');
  14980. }
  14981. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14982. document.getElementById('modal-service-name').value = serviceName;
  14983. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14984. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14985. document.getElementById('modal-service-port').value = currentPort;
  14986. const hintEl = document.getElementById('modal-service-port-hint');
  14987. const warnEl = document.getElementById('modal-service-warning');
  14988. const certGroup = document.getElementById('modal-service-cert-group');
  14989. const certSelect = document.getElementById('modal-service-cert-select');
  14990. if (serviceName === 'www') {
  14991. hintEl.textContent = 'Default HTTP web port: 80';
  14992. warnEl.classList.remove('hidden');
  14993. certGroup.classList.add('hidden');
  14994. } else if (serviceName === 'www-ssl') {
  14995. hintEl.textContent = 'Default HTTPS web port: 443';
  14996. warnEl.classList.remove('hidden');
  14997. certGroup.classList.remove('hidden');
  14998. const populateCertOptions = (certs) => {
  14999. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15000. (certs || []).forEach(c => {
  15001. const opt = document.createElement('option');
  15002. opt.value = c.name;
  15003. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15004. if (c.name === currentCert) opt.selected = true;
  15005. certSelect.appendChild(opt);
  15006. });
  15007. };
  15008. if (state.certificates && state.certificates.length > 0) {
  15009. populateCertOptions(state.certificates);
  15010. } else {
  15011. loadCertificates(false).then(() => {
  15012. populateCertOptions(state.certificates);
  15013. });
  15014. }
  15015. } else if (serviceName === 'telnet') {
  15016. hintEl.textContent = 'Default Telnet console port: 8282';
  15017. warnEl.classList.add('hidden');
  15018. certGroup.classList.add('hidden');
  15019. } else if (serviceName === 'ssh') {
  15020. hintEl.textContent = 'Default SSH port: 2222';
  15021. warnEl.classList.add('hidden');
  15022. certGroup.classList.add('hidden');
  15023. } else {
  15024. hintEl.textContent = '';
  15025. warnEl.classList.add('hidden');
  15026. certGroup.classList.add('hidden');
  15027. }
  15028. const modal = document.getElementById('modal-service-edit');
  15029. modal.classList.remove('hidden');
  15030. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15031. }
  15032. function closeEditServiceModal() {
  15033. const modal = document.getElementById('modal-service-edit');
  15034. if (modal) modal.classList.add('hidden');
  15035. }
  15036. async function submitSaveServicePort(event) {
  15037. event.preventDefault();
  15038. const name = document.getElementById('modal-service-name').value;
  15039. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15040. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15041. if (isNaN(port) || port < 1 || port > 65535) {
  15042. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15043. return;
  15044. }
  15045. const certSelect = document.getElementById('modal-service-cert-select');
  15046. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15047. try {
  15048. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15049. method: 'POST',
  15050. headers: { 'Content-Type': 'application/json' },
  15051. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15052. });
  15053. if (!res.ok) {
  15054. const errData = await res.json();
  15055. throw new Error(errData.message || 'Failed to update service settings');
  15056. }
  15057. closeEditServiceModal();
  15058. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15059. await loadServices();
  15060. } catch (err) {
  15061. showToast('Error', err.message, 'error');
  15062. }
  15063. }
  15064. async function toggleServiceState(serviceName, newDisabled) {
  15065. if (serviceName === 'www' && newDisabled) {
  15066. 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?")) {
  15067. return;
  15068. }
  15069. }
  15070. if (serviceName === 'www-ssl' && !newDisabled) {
  15071. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15072. if (!sslSvc || !sslSvc.certificate) {
  15073. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15074. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15075. return;
  15076. }
  15077. }
  15078. try {
  15079. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15080. method: 'POST',
  15081. headers: { 'Content-Type': 'application/json' },
  15082. body: JSON.stringify({ disabled: newDisabled })
  15083. });
  15084. if (!res.ok) {
  15085. const errData = await res.json();
  15086. throw new Error(errData.message || 'Failed to update service');
  15087. }
  15088. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15089. await loadServices();
  15090. } catch (err) {
  15091. showToast('Error', err.message, 'error');
  15092. }
  15093. }
  15094. // ==================== SYSTEM LOGS (/log) ====================
  15095. state.logs = [];
  15096. let logsTimer = null;
  15097. async function loadLogs(manual = false) {
  15098. const limitEl = document.getElementById('logs-limit-select');
  15099. const limit = limitEl ? limitEl.value : '100';
  15100. try {
  15101. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15102. if (!res.ok) throw new Error('Failed to load logs');
  15103. const data = await res.json();
  15104. state.logs = data.logs || [];
  15105. renderLogsTable();
  15106. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15107. } catch (err) {
  15108. if (manual) showToast('Error', err.message, 'error');
  15109. }
  15110. // Setup auto-refresh if enabled and on logs tab
  15111. if (!logsTimer && state.currentUser) {
  15112. logsTimer = setInterval(() => {
  15113. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15114. const auto = document.getElementById('logs-auto-refresh');
  15115. if (auto && auto.checked) {
  15116. loadLogs(false);
  15117. }
  15118. }
  15119. }, 3000);
  15120. }
  15121. }
  15122. function renderLogsTable() {
  15123. const tbody = document.getElementById('logs-table-body');
  15124. if (!tbody) return;
  15125. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15126. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15127. const filtered = state.logs.filter(entry => {
  15128. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15129. return false;
  15130. }
  15131. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15132. return false;
  15133. }
  15134. return true;
  15135. });
  15136. if (filtered.length === 0) {
  15137. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15138. return;
  15139. }
  15140. tbody.innerHTML = filtered.map(l => {
  15141. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15142. const topLower = l.topics.toLowerCase();
  15143. if (topLower.includes('auth')) {
  15144. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15145. } else if (topLower.includes('dhcp')) {
  15146. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15147. } else if (topLower.includes('route')) {
  15148. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15149. } else if (topLower.includes('firewall')) {
  15150. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15151. } else if (topLower.includes('error')) {
  15152. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15153. } else if (topLower.includes('system')) {
  15154. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15155. }
  15156. const d = new Date(l.time);
  15157. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15158. return `
  15159. <tr class="hover:bg-slate-800/40 transition">
  15160. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15161. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15162. <td class="py-2 px-3 whitespace-nowrap">
  15163. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15164. </td>
  15165. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15166. </tr>
  15167. `;
  15168. }).join('');
  15169. }
  15170. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15171. state.certificates = [];
  15172. async function loadCertificates(manual = false) {
  15173. try {
  15174. const res = await fetch(`${API_BASE}/certificates`);
  15175. if (!res.ok) throw new Error('Failed to load certificates');
  15176. state.certificates = await res.json() || [];
  15177. updateCertificatesBadges();
  15178. renderCertificatesTable();
  15179. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15180. } catch (err) {
  15181. if (manual) showToast('Error', err.message, 'error');
  15182. }
  15183. }
  15184. function updateCertificatesBadges() {
  15185. const total = (state.certificates || []).length;
  15186. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15187. const bCount = document.getElementById('badge-certs-count');
  15188. if (bCount) bCount.innerText = total;
  15189. const kpiTotal = document.getElementById('kpi-certs-total');
  15190. if (kpiTotal) kpiTotal.innerText = total;
  15191. const kpiCA = document.getElementById('kpi-certs-ca');
  15192. if (kpiCA) kpiCA.innerText = caCount;
  15193. const kpiHttps = document.getElementById('kpi-https-status');
  15194. if (kpiHttps) {
  15195. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15196. if (sslSvc) {
  15197. if (!sslSvc.disabled) {
  15198. 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>`;
  15199. } else {
  15200. 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>`;
  15201. }
  15202. }
  15203. }
  15204. }
  15205. function renderCertificatesTable() {
  15206. const tbody = document.getElementById('certs-table-body');
  15207. if (!tbody) return;
  15208. if (!state.certificates || state.certificates.length === 0) {
  15209. 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>';
  15210. return;
  15211. }
  15212. tbody.innerHTML = state.certificates.map(c => {
  15213. let typeBadge = '';
  15214. if (c.is_ca) {
  15215. 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>';
  15216. } else if (c.type === 'acme') {
  15217. 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>';
  15218. } else if (c.issuer && c.issuer !== c.common_name) {
  15219. 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>';
  15220. } else {
  15221. 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>';
  15222. }
  15223. const sansHtml = (c.sans && c.sans.length > 0)
  15224. ? 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('')
  15225. : '<span class="text-slate-500">-</span>';
  15226. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15227. let validStr = '-';
  15228. let validBadge = '';
  15229. if (validTo && !isNaN(validTo.getTime())) {
  15230. const now = new Date();
  15231. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15232. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15233. if (daysLeft < 0) {
  15234. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15235. } else if (daysLeft < 30) {
  15236. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15237. } else {
  15238. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15239. }
  15240. }
  15241. return `
  15242. <tr class="hover:bg-slate-800/40 transition">
  15243. <td class="py-3 px-4">${typeBadge}</td>
  15244. <td class="py-3 px-4">
  15245. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15246. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15247. </td>
  15248. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15249. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15250. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15251. <span>${validStr}</span> ${validBadge}
  15252. ${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>` : ''}
  15253. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15254. </td>
  15255. <td class="py-3 px-4 text-right whitespace-nowrap">
  15256. <div class="flex items-center justify-end gap-1.5">
  15257. <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">
  15258. <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>
  15259. <span>View</span>
  15260. </button>
  15261. <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">
  15262. <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>
  15263. </button>
  15264. </div>
  15265. </td>
  15266. </tr>
  15267. `;
  15268. }).join('');
  15269. }
  15270. // Create CA
  15271. function openCreateCAModal() {
  15272. document.getElementById('form-create-ca').reset();
  15273. document.getElementById('ca-days').value = '3650';
  15274. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15275. document.getElementById('ca-country').value = 'GR';
  15276. document.getElementById('ca-key-type').value = 'RSA-2048';
  15277. document.getElementById('modal-create-ca').classList.remove('hidden');
  15278. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15279. }
  15280. function closeCreateCAModal() {
  15281. document.getElementById('modal-create-ca').classList.add('hidden');
  15282. }
  15283. async function submitCreateCA(event) {
  15284. event.preventDefault();
  15285. const payload = {
  15286. name: document.getElementById('ca-name').value.trim(),
  15287. common_name: document.getElementById('ca-cn').value.trim(),
  15288. organization: document.getElementById('ca-org').value.trim(),
  15289. country: document.getElementById('ca-country').value.trim(),
  15290. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15291. key_type: document.getElementById('ca-key-type').value
  15292. };
  15293. try {
  15294. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15295. method: 'POST',
  15296. headers: { 'Content-Type': 'application/json' },
  15297. body: JSON.stringify(payload)
  15298. });
  15299. if (!res.ok) {
  15300. const errData = await res.json();
  15301. throw new Error(errData.message || 'Failed to create CA');
  15302. }
  15303. closeCreateCAModal();
  15304. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15305. await loadCertificates();
  15306. } catch (err) {
  15307. showToast('Error', err.message, 'error');
  15308. }
  15309. }
  15310. // Create Cert
  15311. function openCreateCertModal() {
  15312. document.getElementById('form-create-cert').reset();
  15313. document.getElementById('cert-days').value = '730';
  15314. document.getElementById('cert-key-type').value = 'RSA-2048';
  15315. const caSelect = document.getElementById('cert-ca-select');
  15316. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15317. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15318. const opt = document.createElement('option');
  15319. opt.value = ca.name;
  15320. opt.textContent = `${ca.name} (${ca.common_name})`;
  15321. caSelect.appendChild(opt);
  15322. });
  15323. document.getElementById('modal-create-cert').classList.remove('hidden');
  15324. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15325. }
  15326. function closeCreateCertModal() {
  15327. document.getElementById('modal-create-cert').classList.add('hidden');
  15328. }
  15329. async function submitCreateCert(event) {
  15330. event.preventDefault();
  15331. const rawSans = document.getElementById('cert-sans').value;
  15332. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15333. const caName = document.getElementById('cert-ca-select').value;
  15334. const payload = {
  15335. name: document.getElementById('cert-name').value.trim(),
  15336. common_name: document.getElementById('cert-cn').value.trim(),
  15337. ca_name: caName,
  15338. sans: sansList,
  15339. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15340. key_type: document.getElementById('cert-key-type').value,
  15341. is_server: true
  15342. };
  15343. try {
  15344. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15345. method: 'POST',
  15346. headers: { 'Content-Type': 'application/json' },
  15347. body: JSON.stringify(payload)
  15348. });
  15349. if (!res.ok) {
  15350. const errData = await res.json();
  15351. throw new Error(errData.message || 'Failed to issue certificate');
  15352. }
  15353. closeCreateCertModal();
  15354. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15355. await loadCertificates();
  15356. } catch (err) {
  15357. showToast('Error', err.message, 'error');
  15358. }
  15359. }
  15360. // Let's Encrypt
  15361. function openLetsEncryptModal() {
  15362. document.getElementById('form-letsencrypt').reset();
  15363. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15364. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15365. }
  15366. function closeLetsEncryptModal() {
  15367. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15368. }
  15369. async function submitLetsEncrypt(event) {
  15370. event.preventDefault();
  15371. const domain = document.getElementById('le-domain').value.trim();
  15372. const email = document.getElementById('le-email').value.trim();
  15373. let name = document.getElementById('le-name').value.trim();
  15374. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15375. const staging = document.getElementById('le-staging').checked;
  15376. const btn = document.getElementById('btn-submit-letsencrypt');
  15377. const origBtnHtml = btn.innerHTML;
  15378. btn.disabled = true;
  15379. 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>`;
  15380. try {
  15381. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15382. method: 'POST',
  15383. headers: { 'Content-Type': 'application/json' },
  15384. body: JSON.stringify({
  15385. name: name,
  15386. domain: domain,
  15387. email: email,
  15388. staging: staging
  15389. })
  15390. });
  15391. if (!res.ok) {
  15392. const errData = await res.json();
  15393. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15394. }
  15395. closeLetsEncryptModal();
  15396. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15397. await loadCertificates();
  15398. } catch (err) {
  15399. showToast('Let\'s Encrypt Error', err.message, 'error');
  15400. } finally {
  15401. btn.disabled = false;
  15402. btn.innerHTML = origBtnHtml;
  15403. }
  15404. }
  15405. // Import Cert
  15406. function openImportCertModal() {
  15407. document.getElementById('form-import-cert').reset();
  15408. document.getElementById('modal-import-cert').classList.remove('hidden');
  15409. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15410. }
  15411. function closeImportCertModal() {
  15412. document.getElementById('modal-import-cert').classList.add('hidden');
  15413. }
  15414. async function submitImportCert(event) {
  15415. event.preventDefault();
  15416. const payload = {
  15417. name: document.getElementById('import-cert-name').value.trim(),
  15418. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15419. key_pem: document.getElementById('import-key-pem').value.trim()
  15420. };
  15421. try {
  15422. const res = await fetch(`${API_BASE}/certificates/import`, {
  15423. method: 'POST',
  15424. headers: { 'Content-Type': 'application/json' },
  15425. body: JSON.stringify(payload)
  15426. });
  15427. if (!res.ok) {
  15428. const errData = await res.json();
  15429. throw new Error(errData.message || 'Failed to import certificate');
  15430. }
  15431. closeImportCertModal();
  15432. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15433. await loadCertificates();
  15434. } catch (err) {
  15435. showToast('Error', err.message, 'error');
  15436. }
  15437. }
  15438. // View / Export Modal
  15439. async function openViewCertModal(name) {
  15440. const c = (state.certificates || []).find(x => x.name === name);
  15441. if (!c) return;
  15442. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15443. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15444. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15445. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15446. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15447. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15448. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15449. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15450. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15451. document.getElementById('modal-view-cert').classList.remove('hidden');
  15452. try {
  15453. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15454. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15455. const data = await res.json();
  15456. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15457. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15458. } catch (err) {
  15459. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15460. document.getElementById('view-key-pem-text').value = '';
  15461. }
  15462. }
  15463. function closeViewCertModal() {
  15464. document.getElementById('modal-view-cert').classList.add('hidden');
  15465. }
  15466. function copyCertPEM() {
  15467. const text = document.getElementById('view-cert-pem-text').value;
  15468. if (!text) return;
  15469. navigator.clipboard.writeText(text).then(() => {
  15470. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15471. }).catch(() => {
  15472. showToast('Error', 'Failed to copy to clipboard', 'error');
  15473. });
  15474. }
  15475. function copyKeyPEM() {
  15476. const text = document.getElementById('view-key-pem-text').value;
  15477. if (!text) return;
  15478. navigator.clipboard.writeText(text).then(() => {
  15479. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15480. }).catch(() => {
  15481. showToast('Error', 'Failed to copy to clipboard', 'error');
  15482. });
  15483. }
  15484. async function deleteCertificate(name) {
  15485. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15486. return;
  15487. }
  15488. try {
  15489. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15490. method: 'DELETE'
  15491. });
  15492. if (!res.ok) {
  15493. const errData = await res.json();
  15494. throw new Error(errData.message || 'Failed to delete certificate');
  15495. }
  15496. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15497. await loadCertificates();
  15498. } catch (err) {
  15499. showToast('Error', err.message, 'error');
  15500. }
  15501. }
  15502. // Refresh immediately when returning to a backgrounded controller tab.
  15503. document.addEventListener('visibilitychange', () => {
  15504. if (!state.currentUser) return;
  15505. if (document.hidden) {
  15506. if (trafficEventSource) trafficEventSource.close();
  15507. trafficEventSource = null;
  15508. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15509. trafficPollFallback = null;
  15510. } else {
  15511. fetchData(false);
  15512. initLiveTrafficStream();
  15513. if (state.activeTab === 'bwtest') loadBwTestView();
  15514. }
  15515. });
  15516. async function loadUpdateStatus(populate = true) {
  15517. try {
  15518. const res = await fetch(`${API_BASE}/update/status`);
  15519. if (!res.ok) throw new Error(await responseError(res));
  15520. const data = await res.json();
  15521. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15522. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15523. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15524. document.getElementById('update-state').textContent = data.state || 'idle';
  15525. document.getElementById('update-log').textContent = data.log || '';
  15526. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15527. }
  15528. async function saveUpdateConfig() {
  15529. try {
  15530. const repository = document.getElementById('update-repository').value.trim();
  15531. const branch = 'master';
  15532. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15533. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15534. if (!res.ok) throw new Error(await responseError(res));
  15535. document.getElementById('update-install-button').disabled = true;
  15536. document.getElementById('update-available').textContent = '—';
  15537. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15538. await loadUpdateStatus(false);
  15539. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15540. }
  15541. async function checkUpdate() {
  15542. try {
  15543. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15544. if (!res.ok) throw new Error(await responseError(res));
  15545. const data = await res.json();
  15546. document.getElementById('update-available').textContent = data.available_version;
  15547. document.getElementById('update-install-button').disabled = !data.update_available;
  15548. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15549. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15550. }
  15551. async function startUpdate(action) {
  15552. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15553. try {
  15554. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15555. if (!res.ok) throw new Error(await responseError(res));
  15556. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15557. await loadUpdateStatus(false);
  15558. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15559. }
  15560. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  15561. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  15562. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  15563. function safeFirewallRow(row) {
  15564. const result = {...row};
  15565. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  15566. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  15567. return result;
  15568. }
  15569. function setFirewallDays(prefix, days) {
  15570. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  15571. 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); }
  15572. }
  15573. function getFirewallDays(prefix) {
  15574. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  15575. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  15576. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  15577. return selected.join(',');
  15578. }
  15579. async function resetFirewallRuleCounter(kind, resetDisplay) {
  15580. const id = document.getElementById(kind+'-modal-id')?.value;
  15581. if (!id) { resetDisplay(); return; }
  15582. try {
  15583. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  15584. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  15585. resetDisplay(); await loadFirewall(false);
  15586. } catch(error) { showToast('Error', error.message, 'error'); }
  15587. }
  15588. function reviewLegacyFirewallSettings(kind, id) {
  15589. if (!id) return true;
  15590. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  15591. const rule = (rows || []).find(r => r.id === id);
  15592. if (!rule) return true;
  15593. 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'];
  15594. const present = unsupported.filter(key => rule[key]);
  15595. if (!present.length) return true;
  15596. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  15597. }
  15598. function refreshFirewallRejectTypes() {
  15599. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  15600. const old=select.value;
  15601. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  15602. 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'];
  15603. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  15604. if(types.includes(old))select.value=old;
  15605. }
  15606. function setFirewallActionSelection(kind, value) {
  15607. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  15608. if(!Array.from(select.options).some(option=>option.value===value)) {
  15609. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  15610. }
  15611. select.value=value;
  15612. }