app.js 736 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376
  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) 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 (action === 'dst-nat' && chain.trim().toLowerCase() !== 'dstnat') { switchNATRuleTab('general'); showToast('NAT rule', 'The dst-nat action requires the dstnat chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  4694. 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; }
  4695. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  4696. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  4697. 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;
  4698. }
  4699. const payload = {
  4700. ip_version: Number(document.getElementById('nat-modal-family').value),
  4701. id,
  4702. chain,
  4703. action,
  4704. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4705. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4706. protocol: proto || 'all',
  4707. src_address: src,
  4708. dst_address: dst,
  4709. src_port: sport,
  4710. dst_port: dport,
  4711. any_port: anyport,
  4712. in_interface: iniface,
  4713. out_interface: outiface,
  4714. in_interface_list: inifacelist,
  4715. out_interface_list: outifacelist,
  4716. packet_mark: pktmark,
  4717. connection_mark: connmark,
  4718. routing_mark: routingmark,
  4719. connection_type: conntype,
  4720. src_address_list: srclist,
  4721. dst_address_list: dstlist,
  4722. src_geoip: srcgeo,
  4723. dst_geoip: dstgeo,
  4724. comment,
  4725. disabled: !enabled,
  4726. // Advanced tab
  4727. content: getNATFieldVal('content', false),
  4728. src_mac_address: getNATFieldVal('srcmac', true),
  4729. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4730. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4731. ipsec_policy: getNATFieldVal('ipsec', false),
  4732. dscp: getNATFieldVal('dscp', false),
  4733. tcp_mss: getNATFieldVal('tcpmss', false),
  4734. tos: document.getElementById('nat-val-tos')?.value || '',
  4735. packet_size: getNATFieldVal('pktsize', false),
  4736. random: getNATFieldVal('random', false),
  4737. icmp_options: getNATFieldVal('icmpoptions', false),
  4738. ttl: getNATFieldVal('ttl', false),
  4739. days: selectedDays,
  4740. // Extra tab
  4741. time: getNATFieldVal('time', false),
  4742. limit: getNATFieldVal('limit', false),
  4743. // Action tab
  4744. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4745. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4746. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4747. log: document.getElementById('nat-modal-log')?.checked || false,
  4748. log_prefix: getNATFieldVal('logprefix', false)
  4749. };
  4750. try {
  4751. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4752. method: 'POST',
  4753. headers: { 'Content-Type': 'application/json' },
  4754. body: JSON.stringify(payload)
  4755. });
  4756. if (res.ok) {
  4757. const data = await res.json();
  4758. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4759. loadFirewall(false);
  4760. if (closeAfter) {
  4761. closeNATModal();
  4762. } else {
  4763. if (data.id) {
  4764. document.getElementById('nat-modal-id').value = data.id;
  4765. const badge = document.getElementById('nat-modal-badge');
  4766. if (badge) badge.innerText = `#${data.id}`;
  4767. }
  4768. }
  4769. } else {
  4770. const err = await res.json();
  4771. showToast('Error', err.message || 'Failed to save rule', 'error');
  4772. }
  4773. } catch (err) {
  4774. showToast('Error', err.message, 'error');
  4775. }
  4776. }
  4777. function submitSaveNATRule(e) {
  4778. if (e && e.preventDefault) e.preventDefault();
  4779. return applyNATRule(true);
  4780. }
  4781. function startNATStatPolling() {
  4782. stopNATStatPolling();
  4783. pollNATRuleStats();
  4784. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4785. }
  4786. function stopNATStatPolling() {
  4787. if (state.natStatInterval) {
  4788. clearInterval(state.natStatInterval);
  4789. state.natStatInterval = null;
  4790. }
  4791. }
  4792. async function pollNATRuleStats() {
  4793. const id = document.getElementById('nat-modal-id')?.value;
  4794. if (!id) {
  4795. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4796. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4797. return;
  4798. }
  4799. try {
  4800. const res = await fetch(`${API_BASE}/firewall/nat`);
  4801. if (!res.ok) return;
  4802. const rules = await res.json();
  4803. const r = rules.find(x => x.id === id);
  4804. if (!r) return;
  4805. const now = Date.now();
  4806. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4807. state.natLastTimestamp = now;
  4808. const curBytes = r.bytes || 0;
  4809. const curPackets = r.packets || 0;
  4810. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  4811. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  4812. state.natLastBytes = curBytes;
  4813. state.natLastPackets = curPackets;
  4814. const rateBps = Math.round((deltaBytes * 8) / dt);
  4815. const ratePkt = Math.round(deltaPkts / dt);
  4816. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4817. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4818. state.natStatRateHistory.push(rateBps);
  4819. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4820. state.natStatPktHistory.push(ratePkt);
  4821. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4822. const bEl = document.getElementById('nat-stat-bytes');
  4823. const pEl = document.getElementById('nat-stat-packets');
  4824. const rEl = document.getElementById('nat-stat-rate');
  4825. const prEl = document.getElementById('nat-stat-pktrate');
  4826. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4827. if (pEl) pEl.value = curPackets.toLocaleString();
  4828. if (rEl) rEl.value = formatBps(rateBps);
  4829. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4830. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4831. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4832. } catch (e) {
  4833. console.error('Error polling NAT rule stats', e);
  4834. }
  4835. }
  4836. async function moveNATRule(id, dir) {
  4837. id = decodeURIComponent(id);
  4838. try {
  4839. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4840. method: 'POST',
  4841. headers: { 'Content-Type': 'application/json' },
  4842. body: JSON.stringify({ direction: dir })
  4843. });
  4844. if (res.ok) loadFirewall(false);
  4845. } catch (err) {
  4846. showToast('Error', err.message, 'error');
  4847. }
  4848. }
  4849. async function toggleNATRuleState(id, disabled) {
  4850. id = decodeURIComponent(id);
  4851. try {
  4852. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4853. method: 'POST',
  4854. headers: { 'Content-Type': 'application/json' },
  4855. body: JSON.stringify({ disabled })
  4856. });
  4857. if (res.ok) loadFirewall(false);
  4858. } catch (err) {
  4859. showToast('Error', err.message, 'error');
  4860. }
  4861. }
  4862. async function deleteNATRule(id) {
  4863. id = decodeURIComponent(id);
  4864. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4865. try {
  4866. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4867. if (res.ok) {
  4868. showToast('Deleted', 'NAT rule removed', 'success');
  4869. loadFirewall(false);
  4870. }
  4871. } catch (err) {
  4872. showToast('Error', err.message, 'error');
  4873. }
  4874. }
  4875. // ----------------- Mangle Rules -----------------
  4876. function renderMangleRules() {
  4877. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4878. const tbody = document.getElementById('mangle-table-body');
  4879. const empty = document.getElementById('mangle-empty');
  4880. if (!tbody) return;
  4881. tbody.innerHTML = '';
  4882. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4883. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4884. if (rules.length === 0) {
  4885. empty?.classList.remove('hidden');
  4886. return;
  4887. }
  4888. empty?.classList.add('hidden');
  4889. rules.forEach((raw, idx) => {
  4890. const r = safeFirewallRow(raw);
  4891. const tr = document.createElement('tr');
  4892. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4893. let markVal = '<span class="text-slate-500">-</span>';
  4894. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4895. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4896. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4897. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4898. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4899. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4900. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4901. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4902. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4903. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4904. 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>`;
  4905. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4906. tr.innerHTML = `
  4907. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4908. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4909. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4910. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4911. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4912. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4913. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4914. <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>
  4915. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4916. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4917. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4918. </td>
  4919. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4920. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4921. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4922. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4923. <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>
  4924. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4925. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4926. </td>
  4927. `;
  4928. tbody.appendChild(tr);
  4929. });
  4930. }
  4931. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4932. function switchMangleRuleTab(tab) {
  4933. state.activeMangleRuleTab = tab;
  4934. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4935. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4936. btn.classList.add('text-slate-400', 'border-transparent');
  4937. });
  4938. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4939. if (activeBtn) {
  4940. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4941. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4942. }
  4943. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4944. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4945. if (activePane) activePane.classList.remove('hidden');
  4946. if (tab === 'statistics') {
  4947. startMangleStatPolling();
  4948. } else {
  4949. stopMangleStatPolling();
  4950. }
  4951. }
  4952. function toggleMangleField(fieldKey, expand) {
  4953. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4954. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4955. if (!plusBtn || !fieldBox) return;
  4956. if (expand) {
  4957. plusBtn.classList.add('hidden');
  4958. fieldBox.classList.remove('hidden');
  4959. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4960. if (valInput) valInput.focus();
  4961. } else {
  4962. fieldBox.classList.add('hidden');
  4963. plusBtn.classList.remove('hidden');
  4964. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4965. if (valInput) {
  4966. if (valInput.tagName === 'SELECT') {
  4967. valInput.selectedIndex = 0;
  4968. } else {
  4969. valInput.value = '';
  4970. }
  4971. }
  4972. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4973. if (invInput) invInput.checked = false;
  4974. if (fieldKey === 'cs') {
  4975. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4976. const el = document.getElementById(id);
  4977. if (el) el.checked = false;
  4978. });
  4979. }
  4980. if (fieldKey === 'natstate') {
  4981. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4982. const el = document.getElementById(id);
  4983. if (el) el.checked = false;
  4984. });
  4985. }
  4986. }
  4987. }
  4988. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4989. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4990. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4991. toggleMangleField(fieldKey, true);
  4992. let strVal = String(value);
  4993. if (hasInvert) {
  4994. const inv = strVal.startsWith('!');
  4995. if (inv) strVal = strVal.slice(1);
  4996. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4997. if (invEl) invEl.checked = inv;
  4998. else if (inv) strVal = '!'+strVal;
  4999. }
  5000. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5001. 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; }
  5002. } else {
  5003. toggleMangleField(fieldKey, false);
  5004. }
  5005. }
  5006. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5007. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5008. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5009. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5010. let v = valEl ? valEl.value.trim() : '';
  5011. if (!v) return '';
  5012. if (hasInvert) {
  5013. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5014. if (invEl && invEl.checked) {
  5015. v = '!' + v.replace(/^!/, '');
  5016. }
  5017. }
  5018. return v;
  5019. }
  5020. function toggleMaximizeMangleModal() {
  5021. const win = document.getElementById('mangle-modal-window');
  5022. if (!win) return;
  5023. if (win.classList.contains('max-w-[720px]')) {
  5024. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5025. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5026. } else {
  5027. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5028. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5029. }
  5030. }
  5031. function toggleMangleActionFields() {
  5032. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5033. // Hide all dynamic rows first
  5034. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5035. const el = document.getElementById(`mangle-row-${id}`);
  5036. if (el) el.classList.add('hidden');
  5037. });
  5038. const jumpBox = document.getElementById('mangle-action-jump-box');
  5039. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5040. if (jumpBox) jumpBox.classList.add('hidden');
  5041. if (addrBox) addrBox.classList.add('hidden');
  5042. // Activate matching rows
  5043. if (act === 'mark-connection') {
  5044. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5045. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5046. } else if (act === 'mark-routing') {
  5047. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5048. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5049. } else if (act === 'mark-packet') {
  5050. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5051. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5052. } else if (act === 'change-mss') {
  5053. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5054. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5055. } else if (act === 'change-dscp') {
  5056. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5057. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5058. } else if (act === 'change-ttl') {
  5059. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5060. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5061. } else if (act === 'set-priority') {
  5062. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5063. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5064. } else if (act === 'route') {
  5065. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5066. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5067. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5068. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5069. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5070. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5071. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5072. } else if (act === 'jump') {
  5073. if (jumpBox) jumpBox.classList.remove('hidden');
  5074. } else if (act.includes('address-list') || act.includes('address list')) {
  5075. if (addrBox) addrBox.classList.remove('hidden');
  5076. }
  5077. if (act === 'log') {
  5078. const logEl = document.getElementById('mangle-modal-log');
  5079. if (logEl) logEl.checked = true;
  5080. toggleMangleField('logprefix', true);
  5081. }
  5082. }
  5083. function toggleMangleLogPrefix() {
  5084. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5085. toggleMangleField('logprefix', !!isLog);
  5086. }
  5087. const allMangleFieldKeys = [
  5088. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5089. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5090. 'routingmark', 'conntype', 'cs', 'natstate',
  5091. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5092. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5093. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5094. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5095. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5096. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5097. ];
  5098. function openAddMangleModal() {
  5099. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5100. switchMangleRuleTab('general');
  5101. const badge = document.getElementById('mangle-modal-badge');
  5102. if (badge) badge.innerText = 'New...';
  5103. document.getElementById('mangle-modal-id').value = '';
  5104. document.getElementById('mangle-modal-family').value = '4';
  5105. document.getElementById('mangle-modal-enabled').checked = true;
  5106. document.getElementById('mangle-modal-comment').value = '';
  5107. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5108. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5109. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5110. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5111. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5112. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5113. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5114. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5115. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5116. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5117. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5118. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5119. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5120. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5121. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5122. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5123. populateInterfaceSelect('mangle-val-iniface');
  5124. populateInterfaceSelect('mangle-val-outiface');
  5125. populateAddressListSelect('mangle-val-srclist');
  5126. populateAddressListSelect('mangle-val-dstlist');
  5127. populateGeoIPSelect('mangle-val-srcgeo');
  5128. populateGeoIPSelect('mangle-val-dstgeo');
  5129. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5130. resetMangleCounterDisplay();
  5131. toggleMangleActionFields();
  5132. document.getElementById('mangle-modal').classList.remove('hidden');
  5133. }
  5134. function openEditMangleModal(id) {
  5135. id = decodeURIComponent(id);
  5136. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5137. if (!r) return;
  5138. switchMangleRuleTab('general');
  5139. const badge = document.getElementById('mangle-modal-badge');
  5140. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5141. document.getElementById('mangle-modal-id').value = r.id;
  5142. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5143. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5144. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5145. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5146. setFirewallActionSelection('mangle', r.action || 'accept');
  5147. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5148. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5149. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5150. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5151. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5152. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5153. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5154. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5155. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5156. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5157. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5158. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5159. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5160. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5161. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5162. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5163. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5164. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5165. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5166. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5167. setMangleFieldVal('src', r.src_address, true);
  5168. setMangleFieldVal('dst', r.dst_address, true);
  5169. setMangleFieldVal('srclist', r.src_address_list, true);
  5170. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5171. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5172. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5173. if (r.protocol && r.protocol !== 'all') {
  5174. setMangleFieldVal('proto', r.protocol, true);
  5175. } else {
  5176. toggleMangleField('proto', false);
  5177. }
  5178. setMangleFieldVal('sport', r.src_port, true);
  5179. setMangleFieldVal('dport', r.dst_port, true);
  5180. setMangleFieldVal('anyport', r.any_port, true);
  5181. setMangleFieldVal('iniface', r.in_interface, true);
  5182. setMangleFieldVal('outiface', r.out_interface, true);
  5183. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5184. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5185. setMangleFieldVal('pktmark', r.packet_mark, true);
  5186. setMangleFieldVal('connmark', r.connection_mark, true);
  5187. setMangleFieldVal('routingmark', r.routing_mark, true);
  5188. setMangleFieldVal('conntype', r.connection_type, false);
  5189. // Connection State
  5190. const states = r.connection_state || [];
  5191. if (states.length > 0) {
  5192. toggleMangleField('cs', true);
  5193. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5194. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5195. if (el) el.checked = states.includes(s);
  5196. });
  5197. } else {
  5198. toggleMangleField('cs', false);
  5199. }
  5200. // Connection NAT State
  5201. const natStates = r.connection_nat_state || [];
  5202. if (natStates.length > 0) {
  5203. toggleMangleField('natstate', true);
  5204. ['srcnat', 'dstnat'].forEach(s => {
  5205. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5206. if (el) el.checked = natStates.includes(s);
  5207. });
  5208. } else {
  5209. toggleMangleField('natstate', false);
  5210. }
  5211. // Advanced tab fields
  5212. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5213. setMangleFieldVal('content', r.content, false);
  5214. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5215. setMangleFieldVal('connrate', r.connection_rate, false);
  5216. setMangleFieldVal('pcc', r.pcc, false);
  5217. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5218. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5219. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5220. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5221. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5222. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5223. setMangleFieldVal('tlshost', r.tls_host, false);
  5224. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5225. setMangleFieldVal('priority', r.priority, false);
  5226. setMangleFieldVal('dscp', r.dscp, false);
  5227. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5228. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5229. setMangleFieldVal('pktsize', r.packet_size, false);
  5230. setMangleFieldVal('random', r.random, false);
  5231. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5232. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5233. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5234. setMangleFieldVal('ttl', r.ttl, false);
  5235. // Extra tab fields
  5236. setMangleFieldVal('nth', r.nth, false);
  5237. setMangleFieldVal('connlimit', r.connection_limit, false);
  5238. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5239. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5240. setMangleFieldVal('hotspot', r.hotspot, false);
  5241. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5242. setMangleFieldVal('limit', r.limit, false);
  5243. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5244. setMangleFieldVal('time', r.time, false);
  5245. setMangleFieldVal('psd', r.psd, false);
  5246. // Action fields
  5247. if (r.jump_target) {
  5248. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5249. if (jtEl) jtEl.value = r.jump_target;
  5250. }
  5251. if (r.address_list) {
  5252. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5253. if (alEl) alEl.value = r.address_list;
  5254. }
  5255. if (r.address_list_timeout) {
  5256. const toEl = document.getElementById('mangle-modal-action-timeout');
  5257. if (toEl) toEl.value = r.address_list_timeout;
  5258. }
  5259. setMangleFieldVal('logprefix', r.log_prefix, false);
  5260. // Statistics
  5261. const bEl = document.getElementById('mangle-stat-bytes');
  5262. const pEl = document.getElementById('mangle-stat-packets');
  5263. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5264. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5265. state.mangleLastBytes = r.bytes || 0;
  5266. state.mangleLastPackets = r.packets || 0;
  5267. state.mangleLastTimestamp = Date.now();
  5268. state.mangleStatRateHistory = new Array(30).fill(0);
  5269. state.mangleStatPktHistory = new Array(30).fill(0);
  5270. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5271. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5272. toggleMangleActionFields();
  5273. document.getElementById('mangle-modal').classList.remove('hidden');
  5274. }
  5275. function closeMangleModal() {
  5276. stopMangleStatPolling();
  5277. document.getElementById('mangle-modal').classList.add('hidden');
  5278. }
  5279. function copyMangleRule() {
  5280. document.getElementById('mangle-modal-id').value = '';
  5281. const badge = document.getElementById('mangle-modal-badge');
  5282. if (badge) badge.innerText = 'New...';
  5283. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5284. }
  5285. function resetMangleCounterDisplay() {
  5286. state.mangleStatRateHistory = new Array(30).fill(0);
  5287. state.mangleStatPktHistory = new Array(30).fill(0);
  5288. state.mangleLastBytes = 0;
  5289. state.mangleLastPackets = 0;
  5290. state.mangleLastTimestamp = Date.now();
  5291. const bEl = document.getElementById('mangle-stat-bytes');
  5292. const pEl = document.getElementById('mangle-stat-packets');
  5293. const rEl = document.getElementById('mangle-stat-rate');
  5294. const prEl = document.getElementById('mangle-stat-pktrate');
  5295. if (bEl) bEl.value = '0 B';
  5296. if (pEl) pEl.value = '0';
  5297. if (rEl) rEl.value = '0 bps';
  5298. if (prEl) prEl.value = '0 p/s';
  5299. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5300. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5301. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5302. }
  5303. async function applyMangleRule(closeAfter = false) {
  5304. const id = document.getElementById('mangle-modal-id').value;
  5305. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5306. const chain = document.getElementById('mangle-modal-chain').value;
  5307. const action = document.getElementById('mangle-modal-action').value;
  5308. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5309. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5310. const src = getMangleFieldVal('src', true);
  5311. const dst = getMangleFieldVal('dst', true);
  5312. const srclist = getMangleFieldVal('srclist', true);
  5313. const dstlist = getMangleFieldVal('dstlist', true);
  5314. const srcgeo = getMangleFieldVal('srcgeo', true);
  5315. const dstgeo = getMangleFieldVal('dstgeo', true);
  5316. const proto = getMangleFieldVal('proto', true);
  5317. const sport = getMangleFieldVal('sport', true);
  5318. const dport = getMangleFieldVal('dport', true);
  5319. const anyport = getMangleFieldVal('anyport', true);
  5320. const iniface = getMangleFieldVal('iniface', true);
  5321. const outiface = getMangleFieldVal('outiface', true);
  5322. const inifacelist = getMangleFieldVal('inifacelist', true);
  5323. const outifacelist = getMangleFieldVal('outifacelist', true);
  5324. const pktmark = getMangleFieldVal('pktmark', true);
  5325. const connmark = getMangleFieldVal('connmark', true);
  5326. const routingmark = getMangleFieldVal('routingmark', true);
  5327. const conntype = getMangleFieldVal('conntype', false);
  5328. const states = [];
  5329. const csBox = document.getElementById('mangle-field-cs');
  5330. if (csBox && !csBox.classList.contains('hidden')) {
  5331. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5332. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5333. });
  5334. }
  5335. const natStates = [];
  5336. const natBox = document.getElementById('mangle-field-natstate');
  5337. if (natBox && !natBox.classList.contains('hidden')) {
  5338. ['srcnat', 'dstnat'].forEach(s => {
  5339. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5340. });
  5341. }
  5342. const payload = {
  5343. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5344. id,
  5345. chain,
  5346. action,
  5347. protocol: proto || 'all',
  5348. src_address: src,
  5349. dst_address: dst,
  5350. src_port: sport,
  5351. dst_port: dport,
  5352. any_port: anyport,
  5353. in_interface: iniface,
  5354. out_interface: outiface,
  5355. in_interface_list: inifacelist,
  5356. out_interface_list: outifacelist,
  5357. packet_mark: pktmark,
  5358. connection_mark: connmark,
  5359. routing_mark: routingmark,
  5360. connection_type: conntype,
  5361. connection_state: states,
  5362. connection_nat_state: natStates,
  5363. src_address_list: srclist,
  5364. dst_address_list: dstlist,
  5365. src_geoip: srcgeo,
  5366. dst_geoip: dstgeo,
  5367. comment,
  5368. disabled: !enabled,
  5369. // Advanced tab
  5370. content: getMangleFieldVal('content', false),
  5371. src_mac_address: getMangleFieldVal('srcmac', true),
  5372. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5373. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5374. ipsec_policy: getMangleFieldVal('ipsec', false),
  5375. dscp: getMangleFieldVal('dscp', false),
  5376. tcp_mss: getMangleFieldVal('tcpmss', false),
  5377. tos: document.getElementById('mangle-val-tos')?.value || '',
  5378. packet_size: getMangleFieldVal('pktsize', false),
  5379. random: getMangleFieldVal('random', false),
  5380. tcp_flags: getMangleFieldVal('tcpflags', false),
  5381. icmp_options: getMangleFieldVal('icmpoptions', false),
  5382. ttl: getMangleFieldVal('ttl', false),
  5383. // Extra tab
  5384. nth: getMangleFieldVal('nth', false),
  5385. connection_limit: getMangleFieldVal('connlimit', false),
  5386. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5387. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5388. ip_fragment: getMangleFieldVal('ipfragment', false),
  5389. limit: getMangleFieldVal('limit', false),
  5390. time: getMangleFieldVal('time', false),
  5391. // Action tab
  5392. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5393. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5394. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5395. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5396. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5397. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5398. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5399. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5400. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5401. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5402. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5403. log: document.getElementById('mangle-modal-log')?.checked || false,
  5404. log_prefix: getMangleFieldVal('logprefix', false)
  5405. };
  5406. try {
  5407. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5408. method: 'POST',
  5409. headers: { 'Content-Type': 'application/json' },
  5410. body: JSON.stringify(payload)
  5411. });
  5412. if (res.ok) {
  5413. const data = await res.json();
  5414. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5415. loadFirewall(false);
  5416. if (closeAfter) {
  5417. closeMangleModal();
  5418. } else {
  5419. if (data.id) {
  5420. document.getElementById('mangle-modal-id').value = data.id;
  5421. const badge = document.getElementById('mangle-modal-badge');
  5422. if (badge) badge.innerText = `#${data.id}`;
  5423. }
  5424. }
  5425. } else {
  5426. const err = await res.json();
  5427. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5428. }
  5429. } catch (err) {
  5430. showToast('Error', err.message, 'error');
  5431. }
  5432. }
  5433. function submitSaveMangleRule(e) {
  5434. if (e && e.preventDefault) e.preventDefault();
  5435. return applyMangleRule(true);
  5436. }
  5437. function startMangleStatPolling() {
  5438. stopMangleStatPolling();
  5439. pollMangleRuleStats();
  5440. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5441. }
  5442. function stopMangleStatPolling() {
  5443. if (state.mangleStatInterval) {
  5444. clearInterval(state.mangleStatInterval);
  5445. state.mangleStatInterval = null;
  5446. }
  5447. }
  5448. async function pollMangleRuleStats() {
  5449. const id = document.getElementById('mangle-modal-id')?.value;
  5450. if (!id) {
  5451. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5452. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5453. return;
  5454. }
  5455. try {
  5456. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5457. if (!res.ok) return;
  5458. const rules = await res.json();
  5459. const r = rules.find(x => x.id === id);
  5460. if (!r) return;
  5461. const now = Date.now();
  5462. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5463. state.mangleLastTimestamp = now;
  5464. const curBytes = r.bytes || 0;
  5465. const curPackets = r.packets || 0;
  5466. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5467. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5468. state.mangleLastBytes = curBytes;
  5469. state.mangleLastPackets = curPackets;
  5470. const rateBps = Math.round((deltaBytes * 8) / dt);
  5471. const ratePkt = Math.round(deltaPkts / dt);
  5472. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5473. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5474. state.mangleStatRateHistory.push(rateBps);
  5475. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5476. state.mangleStatPktHistory.push(ratePkt);
  5477. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5478. const bEl = document.getElementById('mangle-stat-bytes');
  5479. const pEl = document.getElementById('mangle-stat-packets');
  5480. const rEl = document.getElementById('mangle-stat-rate');
  5481. const prEl = document.getElementById('mangle-stat-pktrate');
  5482. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5483. if (pEl) pEl.value = curPackets.toLocaleString();
  5484. if (rEl) rEl.value = formatBps(rateBps);
  5485. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5486. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5487. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5488. } catch (e) {
  5489. console.error('Error polling Mangle rule stats', e);
  5490. }
  5491. }
  5492. async function moveMangleRule(id, dir) {
  5493. id = decodeURIComponent(id);
  5494. try {
  5495. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5496. method: 'POST',
  5497. headers: { 'Content-Type': 'application/json' },
  5498. body: JSON.stringify({ direction: dir })
  5499. });
  5500. if (res.ok) loadFirewall(false);
  5501. } catch (err) {
  5502. showToast('Error', err.message, 'error');
  5503. }
  5504. }
  5505. async function toggleMangleRuleState(id, disabled) {
  5506. id = decodeURIComponent(id);
  5507. try {
  5508. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5509. method: 'POST',
  5510. headers: { 'Content-Type': 'application/json' },
  5511. body: JSON.stringify({ disabled })
  5512. });
  5513. if (res.ok) loadFirewall(false);
  5514. } catch (err) {
  5515. showToast('Error', err.message, 'error');
  5516. }
  5517. }
  5518. async function deleteMangleRule(id) {
  5519. id = decodeURIComponent(id);
  5520. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5521. try {
  5522. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5523. if (res.ok) {
  5524. showToast('Deleted', 'Mangle rule removed', 'success');
  5525. loadFirewall(false);
  5526. }
  5527. } catch (err) {
  5528. showToast('Error', err.message, 'error');
  5529. }
  5530. }
  5531. // ----------------- Address Lists -----------------
  5532. function renderAddressLists() {
  5533. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5534. const tbody = document.getElementById('addrlist-table-body');
  5535. const empty = document.getElementById('addrlist-empty');
  5536. if (!tbody) return;
  5537. tbody.innerHTML = '';
  5538. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5539. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  5540. // Update filter select
  5541. const sel = document.getElementById('addrlist-filter-name');
  5542. if (sel) {
  5543. const cur = sel.value;
  5544. sel.innerHTML = '<option value="">All Lists</option>';
  5545. const set = new Set((state.addressLists || []).map(a => a.name));
  5546. set.forEach(n => {
  5547. const opt = document.createElement('option');
  5548. opt.value = n;
  5549. opt.innerText = n;
  5550. if (n === cur) opt.selected = true;
  5551. sel.appendChild(opt);
  5552. });
  5553. }
  5554. if (entries.length === 0) {
  5555. empty?.classList.remove('hidden');
  5556. return;
  5557. }
  5558. empty?.classList.add('hidden');
  5559. entries.forEach((raw, idx) => {
  5560. const e = safeFirewallRow(raw);
  5561. const tr = document.createElement('tr');
  5562. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5563. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5564. tr.innerHTML = `
  5565. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5566. <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>
  5567. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5568. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5569. <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>
  5570. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5571. ${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>
  5572. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5573. `}
  5574. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5575. </td>
  5576. `;
  5577. tbody.appendChild(tr);
  5578. });
  5579. populateCommonAddrListDatalist();
  5580. }
  5581. function openAddAddrListModal() {
  5582. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5583. document.getElementById('addrlist-modal-id').value = '';
  5584. document.getElementById('addrlist-modal-name').value = '';
  5585. document.getElementById('addrlist-modal-addr').value = '';
  5586. document.getElementById('addrlist-modal-comment').value = '';
  5587. document.getElementById('addrlist-modal-disabled').checked = false;
  5588. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5589. if (submitBtn) submitBtn.innerText = 'Add to List';
  5590. document.getElementById('addrlist-modal').classList.remove('hidden');
  5591. }
  5592. function openEditAddrListModal(id) {
  5593. id = decodeURIComponent(id);
  5594. const e = (state.addressLists || []).find(item => item.id === id);
  5595. if (!e) return;
  5596. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5597. document.getElementById('addrlist-modal-id').value = e.id;
  5598. document.getElementById('addrlist-modal-name').value = e.name;
  5599. document.getElementById('addrlist-modal-addr').value = e.address;
  5600. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5601. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5602. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5603. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5604. document.getElementById('addrlist-modal').classList.remove('hidden');
  5605. }
  5606. function closeAddrListModal() {
  5607. document.getElementById('addrlist-modal').classList.add('hidden');
  5608. }
  5609. async function submitSaveAddrList(e) {
  5610. e.preventDefault();
  5611. const id = document.getElementById('addrlist-modal-id').value;
  5612. const name = document.getElementById('addrlist-modal-name').value.trim();
  5613. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5614. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5615. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5616. try {
  5617. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5618. method: 'POST',
  5619. headers: { 'Content-Type': 'application/json' },
  5620. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5621. });
  5622. if (res.ok) {
  5623. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5624. closeAddrListModal();
  5625. loadFirewall(false);
  5626. } else {
  5627. const err = await res.json();
  5628. showToast('Error', err.message || 'Failed to save address list', 'error');
  5629. }
  5630. } catch (err) {
  5631. showToast('Error', err.message, 'error');
  5632. }
  5633. }
  5634. async function toggleAddrListState(id, disabled) {
  5635. id = decodeURIComponent(id);
  5636. try {
  5637. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5638. method: 'POST',
  5639. headers: { 'Content-Type': 'application/json' },
  5640. body: JSON.stringify({ disabled })
  5641. });
  5642. if (res.ok) {
  5643. loadFirewall(false);
  5644. }
  5645. } catch (err) {
  5646. showToast('Error', err.message, 'error');
  5647. }
  5648. }
  5649. async function deleteAddrList(id) {
  5650. id = decodeURIComponent(id);
  5651. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5652. try {
  5653. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5654. if (res.ok) {
  5655. showToast('Deleted', 'Address list item removed', 'info');
  5656. loadFirewall(false);
  5657. }
  5658. } catch (err) {
  5659. showToast('Error', err.message, 'error');
  5660. }
  5661. }
  5662. // ----------------- Geo-Location IP Management -----------------
  5663. async function loadGeoIP() {
  5664. try {
  5665. const [statusRes, countriesRes] = await Promise.all([
  5666. fetch(`${API_BASE}/firewall/geoip/status`),
  5667. fetch(`${API_BASE}/firewall/geoip/countries`)
  5668. ]);
  5669. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5670. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5671. updateGeoHeader();
  5672. renderGeoCountries();
  5673. } catch (err) {
  5674. console.error('Failed to load GeoIP:', err);
  5675. }
  5676. }
  5677. function getGeoUsageMap() {
  5678. const usage = {};
  5679. const checkRule = (r, type) => {
  5680. ['src_geoip', 'dst_geoip'].forEach(field => {
  5681. let val = (r && r[field]) || '';
  5682. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5683. if (code) {
  5684. if (!usage[code]) usage[code] = [];
  5685. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5686. if (!usage[code].includes(label)) usage[code].push(label);
  5687. }
  5688. });
  5689. };
  5690. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5691. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5692. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5693. return usage;
  5694. }
  5695. function updateGeoHeader() {
  5696. const s = state.geoStatus || {};
  5697. const statusBadge = document.getElementById('geo-status-badge');
  5698. if (statusBadge) {
  5699. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5700. statusBadge.className = s.auto_update
  5701. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5702. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5703. }
  5704. const intervalLabel = document.getElementById('geo-interval-label');
  5705. if (intervalLabel) {
  5706. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5707. }
  5708. const usageMap = getGeoUsageMap();
  5709. const inUseCount = Object.keys(usageMap).length;
  5710. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5711. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5712. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5713. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5714. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5715. if (lastSyncEl) {
  5716. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5717. const d = new Date(s.last_updated);
  5718. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5719. } else {
  5720. lastSyncEl.innerText = 'Never (Sync Pending)';
  5721. }
  5722. }
  5723. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5724. if (nextSyncEl) {
  5725. if (s.next_update && !s.next_update.startsWith('0001')) {
  5726. const d = new Date(s.next_update);
  5727. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5728. } else {
  5729. nextSyncEl.innerText = '-';
  5730. }
  5731. }
  5732. const badge = document.getElementById('fw-badge-geo');
  5733. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5734. }
  5735. function renderGeoCountries() {
  5736. const tbody = document.getElementById('geo-table-body');
  5737. const empty = document.getElementById('geo-empty');
  5738. if (!tbody) return;
  5739. tbody.innerHTML = '';
  5740. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5741. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5742. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5743. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5744. const usageMap = getGeoUsageMap();
  5745. const countries = (state.geoCountries || []).filter(c => {
  5746. const isUsed = !!usageMap[c.code];
  5747. if (inUseOnly && !isUsed) return false;
  5748. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5749. if (continent && c.continent !== continent) return false;
  5750. if (q) {
  5751. const matchCode = c.code.toLowerCase().includes(q);
  5752. const matchName = c.name.toLowerCase().includes(q);
  5753. if (!matchCode && !matchName) return false;
  5754. }
  5755. return true;
  5756. });
  5757. if (countries.length === 0) {
  5758. empty?.classList.remove('hidden');
  5759. return;
  5760. }
  5761. empty?.classList.add('hidden');
  5762. countries.forEach(c => {
  5763. const tr = document.createElement('tr');
  5764. const isUsed = !!usageMap[c.code];
  5765. const rulesUsing = usageMap[c.code] || [];
  5766. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5767. let statusHtml = '';
  5768. if (isUsed) {
  5769. 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>`;
  5770. } else if (c.subnet_count > 0) {
  5771. 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>';
  5772. } else {
  5773. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5774. }
  5775. tr.innerHTML = `
  5776. <td class="py-2.5 px-3 text-center">
  5777. <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'}">
  5778. ${c.code}
  5779. </span>
  5780. </td>
  5781. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5782. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5783. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5784. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5785. </td>
  5786. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5787. <td class="py-2.5 px-3">
  5788. ${statusHtml}
  5789. </td>
  5790. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5791. <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>
  5792. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5793. </td>
  5794. `;
  5795. tbody.appendChild(tr);
  5796. });
  5797. }
  5798. function quickFilterGeo(preset) {
  5799. const searchInput = document.getElementById('geo-search-input');
  5800. const continentSel = document.getElementById('geo-continent-filter');
  5801. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5802. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5803. if (searchInput) searchInput.value = '';
  5804. if (continentSel) continentSel.value = '';
  5805. if (inUseCheck) inUseCheck.checked = false;
  5806. if (cachedCheck) cachedCheck.checked = false;
  5807. if (preset === 'GR') {
  5808. if (searchInput) searchInput.value = 'Greece';
  5809. } else if (preset === 'Europe') {
  5810. if (continentSel) continentSel.value = 'Europe';
  5811. } else if (preset === 'HIGHRISK') {
  5812. if (searchInput) searchInput.value = 'China';
  5813. }
  5814. renderGeoCountries();
  5815. }
  5816. async function toggleGeoCountry(code, enabled) {
  5817. try {
  5818. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5819. method: 'POST',
  5820. headers: { 'Content-Type': 'application/json' },
  5821. body: JSON.stringify({ enabled })
  5822. });
  5823. if (res.ok) {
  5824. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5825. loadGeoIP();
  5826. } else {
  5827. const err = await res.json();
  5828. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5829. }
  5830. } catch (err) {
  5831. showToast('Error', err.message, 'error');
  5832. }
  5833. }
  5834. async function updateGeoCountry(code) {
  5835. try {
  5836. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5837. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5838. if (res.ok) {
  5839. const data = await res.json();
  5840. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5841. loadGeoIP();
  5842. } else {
  5843. const err = await res.json();
  5844. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5845. }
  5846. } catch (err) {
  5847. showToast('Error', err.message, 'error');
  5848. }
  5849. }
  5850. async function triggerGeoUpdateNow() {
  5851. const spinner = document.getElementById('geo-update-spinner');
  5852. if (spinner) spinner.classList.remove('hidden');
  5853. try {
  5854. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5855. if (res.ok) {
  5856. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5857. setTimeout(() => {
  5858. loadGeoIP();
  5859. if (spinner) spinner.classList.add('hidden');
  5860. }, 2500);
  5861. } else {
  5862. const err = await res.json();
  5863. showToast('Notice', err.message || 'Update in progress', 'info');
  5864. if (spinner) spinner.classList.add('hidden');
  5865. }
  5866. } catch (err) {
  5867. showToast('Error', err.message, 'error');
  5868. if (spinner) spinner.classList.add('hidden');
  5869. }
  5870. }
  5871. async function applyGeoPreset(preset) {
  5872. try {
  5873. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5874. method: 'POST',
  5875. headers: { 'Content-Type': 'application/json' },
  5876. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5877. });
  5878. if (res.ok) {
  5879. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5880. loadGeoIP();
  5881. }
  5882. } catch (err) {
  5883. showToast('Error', err.message, 'error');
  5884. }
  5885. }
  5886. function openGeoIntervalModal() {
  5887. const s = state.geoStatus || {};
  5888. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5889. const sel = document.getElementById('geo-cfg-interval');
  5890. const customBox = document.getElementById('geo-cfg-custom-box');
  5891. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5892. const curHours = s.interval_hours || 24;
  5893. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5894. if (matchOption) {
  5895. sel.value = String(curHours);
  5896. customBox.classList.add('hidden');
  5897. } else {
  5898. sel.value = 'custom';
  5899. customHoursInput.value = curHours;
  5900. customBox.classList.remove('hidden');
  5901. }
  5902. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5903. }
  5904. function closeGeoIntervalModal() {
  5905. document.getElementById('geo-interval-modal').classList.add('hidden');
  5906. }
  5907. function toggleCustomGeoInterval() {
  5908. const val = document.getElementById('geo-cfg-interval').value;
  5909. const customBox = document.getElementById('geo-cfg-custom-box');
  5910. if (val === 'custom') {
  5911. customBox.classList.remove('hidden');
  5912. } else {
  5913. customBox.classList.add('hidden');
  5914. }
  5915. }
  5916. async function submitGeoIntervalSettings(e) {
  5917. e.preventDefault();
  5918. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5919. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5920. let hours = 24;
  5921. if (intervalVal === 'custom') {
  5922. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5923. } else {
  5924. hours = parseInt(intervalVal, 10) || 24;
  5925. }
  5926. try {
  5927. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5928. method: 'POST',
  5929. headers: { 'Content-Type': 'application/json' },
  5930. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5931. });
  5932. if (res.ok) {
  5933. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5934. closeGeoIntervalModal();
  5935. loadGeoIP();
  5936. } else {
  5937. const err = await res.json();
  5938. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5939. }
  5940. } catch (err) {
  5941. showToast('Error', err.message, 'error');
  5942. }
  5943. }
  5944. async function viewGeoSubnets(code, name) {
  5945. if (!name) {
  5946. const found = (state.geoCountries || []).find(x => x.code === code);
  5947. name = found ? found.name : code;
  5948. }
  5949. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5950. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5951. const listEl = document.getElementById('geo-subnets-list');
  5952. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5953. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5954. try {
  5955. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5956. if (res.ok) {
  5957. const data = await res.json();
  5958. const subnets = data.subnets || [];
  5959. if (subnets.length === 0) {
  5960. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5961. } else {
  5962. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5963. }
  5964. } else {
  5965. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5966. }
  5967. } catch (err) {
  5968. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5969. }
  5970. }
  5971. function closeGeoSubnetsModal() {
  5972. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5973. }
  5974. // ----------------- Active Connections Tracking -----------------
  5975. async function loadConnections() {
  5976. try {
  5977. const res = await fetch(`${API_BASE}/firewall/connections`);
  5978. const data = await res.json();
  5979. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  5980. state.connections = Array.isArray(data) ? data : [];
  5981. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5982. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5983. renderConnections();
  5984. } catch (err) {
  5985. console.error('Failed to load connections:', err);
  5986. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  5987. }
  5988. }
  5989. function renderConnections() {
  5990. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5991. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5992. const tbody = document.getElementById('conns-table-body');
  5993. const empty = document.getElementById('conns-empty');
  5994. if (!tbody) return;
  5995. tbody.innerHTML = '';
  5996. const conns = (state.connections || []).filter(c => {
  5997. if (protoFilter && c.protocol !== protoFilter) return false;
  5998. if (search) {
  5999. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6000. if (!line.includes(search)) return false;
  6001. }
  6002. return true;
  6003. });
  6004. if (conns.length === 0) {
  6005. empty?.classList.remove('hidden');
  6006. return;
  6007. }
  6008. empty?.classList.add('hidden');
  6009. conns.slice(0, 150).forEach(c => {
  6010. const tr = document.createElement('tr');
  6011. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6012. let stateColor = 'text-slate-400';
  6013. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6014. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6015. tr.innerHTML = `
  6016. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6017. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6018. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6019. <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>
  6020. <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>
  6021. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6022. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6023. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6024. <td class="py-2.5 px-3 text-right font-sans">
  6025. ${['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>` : ''}
  6026. </td>
  6027. `;
  6028. tbody.appendChild(tr);
  6029. });
  6030. }
  6031. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6032. try {
  6033. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6034. method: 'POST',
  6035. headers: { 'Content-Type': 'application/json' },
  6036. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6037. });
  6038. if (res.ok) {
  6039. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6040. loadConnections();
  6041. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6042. } catch (err) {
  6043. showToast('Error', err.message, 'error');
  6044. }
  6045. }
  6046. async function resetFirewallCounters() {
  6047. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6048. try {
  6049. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6050. if (res.ok) {
  6051. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6052. loadFirewall(false);
  6053. }
  6054. } catch (err) {
  6055. showToast('Error', err.message, 'error');
  6056. }
  6057. }
  6058. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6059. function switchRoutesSubTab(tab) {
  6060. state.routesSubTab = tab;
  6061. const tabs = ['routes', 'rules', 'tables'];
  6062. tabs.forEach(t => {
  6063. const panel = document.getElementById(`routes-subtab-${t}`);
  6064. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6065. if (panel) {
  6066. if (t === tab) panel.classList.remove('hidden');
  6067. else panel.classList.add('hidden');
  6068. }
  6069. if (btn) {
  6070. if (t === tab) {
  6071. 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';
  6072. } else {
  6073. 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';
  6074. }
  6075. }
  6076. });
  6077. setTimeout(initTableSorting, 50);
  6078. }
  6079. async function loadRoutes() {
  6080. try {
  6081. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6082. fetch(`${API_BASE}/routes`),
  6083. fetch(`${API_BASE}/routing/rules`),
  6084. fetch(`${API_BASE}/routing/tables`)
  6085. ]);
  6086. if (routesRes.ok) state.routes = await routesRes.json();
  6087. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6088. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6089. const bRoutes = document.getElementById('routes-badge-routes');
  6090. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6091. const showSystem = document.getElementById('prule-show-system')?.checked;
  6092. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6093. const bRules = document.getElementById('routes-badge-rules');
  6094. if (bRules) bRules.innerText = userRules.length;
  6095. const bTables = document.getElementById('routes-badge-tables');
  6096. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6097. const bRoutesCount = document.getElementById('badge-routes-count');
  6098. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6099. renderRoutesList();
  6100. renderPolicyRules();
  6101. renderRoutingTables();
  6102. } catch (err) {
  6103. console.error('Failed to load routing:', err);
  6104. }
  6105. }
  6106. function getRouteProtocolBadge(proto) {
  6107. const p = (proto || 'static').toLowerCase();
  6108. switch (p) {
  6109. case 'bgp':
  6110. 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>`;
  6111. case 'ibgp':
  6112. 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>`;
  6113. case 'ospf':
  6114. 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>`;
  6115. case 'rip':
  6116. 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>`;
  6117. case 'static':
  6118. 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>`;
  6119. case 'connected':
  6120. 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>`;
  6121. case 'dhcp':
  6122. 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>`;
  6123. case 'multicast':
  6124. 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>`;
  6125. default:
  6126. 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>`;
  6127. }
  6128. }
  6129. function renderRoutesList() {
  6130. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6131. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6132. const tbody = document.getElementById('routes-table-body');
  6133. const empty = document.getElementById('routes-empty');
  6134. if (!tbody) return;
  6135. // Update table filter select
  6136. const sel = document.getElementById('routes-filter-table');
  6137. if (sel) {
  6138. const cur = sel.value;
  6139. sel.innerHTML = '<option value="">All Tables</option>';
  6140. (state.routingTables || []).forEach(t => {
  6141. const opt = document.createElement('option');
  6142. opt.value = t.name;
  6143. opt.innerText = t.name;
  6144. if (t.name === cur) opt.selected = true;
  6145. sel.appendChild(opt);
  6146. });
  6147. }
  6148. const routes = (state.routes || []).filter(r => {
  6149. if (tableFilter && r.routing_table !== tableFilter) return false;
  6150. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6151. if (typeFilter === 'multicast' && !r.multicast) return false;
  6152. if (typeFilter === 'static' && !r.static) return false;
  6153. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6154. if (typeFilter === 'connected' && !r.connect) return false;
  6155. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6156. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6157. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6158. return true;
  6159. });
  6160. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6161. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6162. let summaryText = `${routes.length} Routes`;
  6163. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6164. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6165. const badgeEl = document.getElementById('routes-count-badge');
  6166. if (badgeEl) badgeEl.innerText = summaryText;
  6167. if (routes.length === 0) {
  6168. empty?.classList.remove('hidden');
  6169. tbody.innerHTML = '';
  6170. return;
  6171. }
  6172. empty?.classList.add('hidden');
  6173. 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(';');
  6174. if (tbody.dataset.sig === sig) {
  6175. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6176. }
  6177. tbody.dataset.sig = sig;
  6178. tbody.innerHTML = '';
  6179. routes.forEach(r => {
  6180. const tr = document.createElement('tr');
  6181. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6182. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6183. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6184. let flags = '';
  6185. if (r.dynamic) flags += 'D';
  6186. if (r.active) flags += 'A';
  6187. if (r.connect) flags += 'C';
  6188. if (r.static) flags += 'S';
  6189. if (r.ecmp) flags += 'E';
  6190. if (r.multicast) flags += 'M';
  6191. if (r.disabled) flags += 'X';
  6192. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6193. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6194. if (r.check_gateway === 'internet') {
  6195. if (r.health_status === 'online') {
  6196. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6197. healthCell = `
  6198. <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)">
  6199. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6200. <span>Internet OK (${ms}ms)</span>
  6201. </span>
  6202. `;
  6203. } else if (r.health_status === 'offline') {
  6204. healthCell = `
  6205. <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.">
  6206. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6207. <span>Internet Down</span>
  6208. </span>
  6209. `;
  6210. } else {
  6211. healthCell = `
  6212. <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">
  6213. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6214. <span>Checking...</span>
  6215. </span>
  6216. `;
  6217. }
  6218. } else if (r.check_gateway === 'ping') {
  6219. if (r.health_status === 'online') {
  6220. healthCell = `
  6221. <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">
  6222. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6223. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6224. </span>
  6225. `;
  6226. } else if (r.health_status === 'offline') {
  6227. healthCell = `
  6228. <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">
  6229. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6230. <span>Gateway Dead</span>
  6231. </span>
  6232. `;
  6233. }
  6234. }
  6235. const flagDescriptions = [];
  6236. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6237. if (r.active) flagDescriptions.push('Active (A)');
  6238. if (r.connect) flagDescriptions.push('Connected (C)');
  6239. if (r.static) flagDescriptions.push('Static (S)');
  6240. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6241. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6242. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6243. tr.innerHTML = `
  6244. <td class="py-2.5 px-3 text-center">
  6245. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6246. 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')
  6247. }" title="Flags: ${flagDescriptions.join(', ')}">
  6248. ${flags || '-'}
  6249. </span>
  6250. </td>
  6251. <td class="py-2.5 px-3">
  6252. <div class="flex items-center gap-1.5 flex-wrap">
  6253. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6254. ${r.ecmp ? `
  6255. <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)">
  6256. <span>⚡ ECMP</span>
  6257. </span>
  6258. ` : ''}
  6259. ${r.multicast ? `
  6260. <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">
  6261. <span>IGMP</span>
  6262. </span>
  6263. ` : ''}
  6264. </div>
  6265. </td>
  6266. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6267. <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>
  6268. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6269. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6270. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6271. <td class="py-2.5 px-3">${healthCell}</td>
  6272. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6273. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6274. ${r.static ? `
  6275. <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>
  6276. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6277. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6278. ` : `
  6279. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6280. `}
  6281. </td>
  6282. `;
  6283. tbody.appendChild(tr);
  6284. });
  6285. }
  6286. function openAddRouteModal() {
  6287. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6288. document.getElementById('route-modal-id').value = '';
  6289. document.getElementById('route-modal-old-dst').value = '';
  6290. document.getElementById('route-modal-old-gw').value = '';
  6291. document.getElementById('route-modal-old-distance').value = '';
  6292. document.getElementById('route-modal-old-table').value = '';
  6293. document.getElementById('route-modal-old-iface').value = '';
  6294. const dstInput = document.getElementById('route-modal-dst');
  6295. const gwInput = document.getElementById('route-modal-gw');
  6296. const distInput = document.getElementById('route-modal-distance');
  6297. const ifaceSelect = document.getElementById('route-modal-iface');
  6298. const tableSelect = document.getElementById('route-modal-table');
  6299. const commentInput = document.getElementById('route-modal-comment');
  6300. const disCheck = document.getElementById('route-modal-disabled');
  6301. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6302. dstInput.disabled = false;
  6303. dstInput.value = '0.0.0.0/0';
  6304. gwInput.disabled = false;
  6305. gwInput.value = '';
  6306. distInput.disabled = false;
  6307. distInput.value = '1';
  6308. ifaceSelect.disabled = false;
  6309. tableSelect.disabled = false;
  6310. commentInput.disabled = false;
  6311. commentInput.value = '';
  6312. disCheck.disabled = false;
  6313. disCheck.checked = false;
  6314. if (saveBtn) saveBtn.classList.remove('hidden');
  6315. const checkGw = document.getElementById('route-modal-check-gw');
  6316. if (checkGw) checkGw.value = 'internet';
  6317. const checkTarget = document.getElementById('route-modal-check-target');
  6318. if (checkTarget) checkTarget.value = '1.1.1.1';
  6319. const checkInterval = document.getElementById('route-modal-check-interval');
  6320. if (checkInterval) checkInterval.value = '5';
  6321. const checkThresh = document.getElementById('route-modal-check-threshold');
  6322. if (checkThresh) checkThresh.value = '3';
  6323. toggleRouteCheckModeUI();
  6324. populateInterfaceSelect('route-modal-iface');
  6325. // Populate tables
  6326. tableSelect.innerHTML = '';
  6327. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6328. const opt = document.createElement('option');
  6329. opt.value = t.name;
  6330. opt.innerText = t.name;
  6331. if (t.name === 'main') opt.selected = true;
  6332. tableSelect.appendChild(opt);
  6333. });
  6334. document.getElementById('route-modal').classList.remove('hidden');
  6335. }
  6336. function openEditRouteModal(id) {
  6337. const r = (state.routes || []).find(route => route.id === id);
  6338. if (!r) return;
  6339. const isStatic = !!r.static;
  6340. document.getElementById('route-modal-title').innerText = isStatic
  6341. ? `Edit Route: ${r.dst_address}`
  6342. : `Route Properties (Read Only): ${r.dst_address}`;
  6343. document.getElementById('route-modal-id').value = r.id;
  6344. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6345. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6346. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6347. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6348. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6349. const dstInput = document.getElementById('route-modal-dst');
  6350. const gwInput = document.getElementById('route-modal-gw');
  6351. const distInput = document.getElementById('route-modal-distance');
  6352. const ifaceSelect = document.getElementById('route-modal-iface');
  6353. const tableSelect = document.getElementById('route-modal-table');
  6354. const commentInput = document.getElementById('route-modal-comment');
  6355. const disCheck = document.getElementById('route-modal-disabled');
  6356. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6357. dstInput.value = r.dst_address;
  6358. gwInput.value = r.gateway || '';
  6359. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6360. commentInput.value = r.comment || '';
  6361. disCheck.checked = !!r.disabled;
  6362. const checkGw = document.getElementById('route-modal-check-gw');
  6363. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6364. const checkTarget = document.getElementById('route-modal-check-target');
  6365. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6366. const checkInterval = document.getElementById('route-modal-check-interval');
  6367. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6368. const checkThresh = document.getElementById('route-modal-check-threshold');
  6369. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6370. toggleRouteCheckModeUI();
  6371. dstInput.disabled = !isStatic;
  6372. gwInput.disabled = !isStatic;
  6373. distInput.disabled = !isStatic;
  6374. ifaceSelect.disabled = !isStatic;
  6375. tableSelect.disabled = !isStatic;
  6376. commentInput.disabled = !isStatic;
  6377. disCheck.disabled = !isStatic;
  6378. if (checkGw) checkGw.disabled = !isStatic;
  6379. if (checkTarget) checkTarget.disabled = !isStatic;
  6380. if (checkInterval) checkInterval.disabled = !isStatic;
  6381. if (checkThresh) checkThresh.disabled = !isStatic;
  6382. if (saveBtn) {
  6383. if (isStatic) {
  6384. saveBtn.classList.remove('hidden');
  6385. } else {
  6386. saveBtn.classList.add('hidden');
  6387. }
  6388. }
  6389. populateInterfaceSelect('route-modal-iface', r.interface);
  6390. tableSelect.innerHTML = '';
  6391. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6392. const opt = document.createElement('option');
  6393. opt.value = t.name;
  6394. opt.innerText = t.name;
  6395. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6396. tableSelect.appendChild(opt);
  6397. });
  6398. document.getElementById('route-modal').classList.remove('hidden');
  6399. }
  6400. function closeRouteModal() {
  6401. document.getElementById('route-modal').classList.add('hidden');
  6402. }
  6403. function setRouteCheckTarget(ip) {
  6404. const inp = document.getElementById('route-modal-check-target');
  6405. if (inp) inp.value = ip;
  6406. }
  6407. function toggleRouteCheckModeUI() {
  6408. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6409. const targetRow = document.getElementById('route-row-check-target');
  6410. const paramsRow = document.getElementById('route-row-check-params');
  6411. if (mode === 'none') {
  6412. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6413. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6414. } else if (mode === 'ping') {
  6415. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6416. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6417. } else { // internet
  6418. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6419. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6420. }
  6421. }
  6422. async function submitSaveRoute(e) {
  6423. e.preventDefault();
  6424. const id = document.getElementById('route-modal-id').value;
  6425. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6426. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6427. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6428. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6429. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6430. const dst = document.getElementById('route-modal-dst').value.trim();
  6431. const gw = document.getElementById('route-modal-gw').value.trim();
  6432. const table = document.getElementById('route-modal-table').value;
  6433. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6434. const iface = document.getElementById('route-modal-iface').value;
  6435. const comment = document.getElementById('route-modal-comment').value.trim();
  6436. const disabled = document.getElementById('route-modal-disabled').checked;
  6437. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6438. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6439. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6440. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6441. if (!dst) {
  6442. showToast('Error', 'Destination address is required', 'error');
  6443. return;
  6444. }
  6445. if (!gw && !iface) {
  6446. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6447. return;
  6448. }
  6449. const payload = {
  6450. id,
  6451. old_dst_address: oldDst,
  6452. old_gateway: oldGw,
  6453. old_routing_table: oldTable,
  6454. old_interface: oldIface,
  6455. dst_address: dst,
  6456. gateway: gw || iface,
  6457. routing_table: table,
  6458. distance,
  6459. interface: iface,
  6460. comment,
  6461. disabled,
  6462. check_gateway,
  6463. check_target,
  6464. check_interval,
  6465. check_threshold
  6466. };
  6467. if (oldDistStr !== undefined && oldDistStr !== '') {
  6468. payload.old_distance = parseInt(oldDistStr, 10);
  6469. }
  6470. try {
  6471. const res = await fetch(`${API_BASE}/routes`, {
  6472. method: 'POST',
  6473. headers: { 'Content-Type': 'application/json' },
  6474. body: JSON.stringify(payload)
  6475. });
  6476. if (res.ok) {
  6477. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6478. closeRouteModal();
  6479. loadRoutes();
  6480. } else {
  6481. const err = await res.json();
  6482. showToast('Error', err.message || 'Failed to save route', 'error');
  6483. }
  6484. } catch (err) {
  6485. showToast('Error', err.message, 'error');
  6486. }
  6487. }
  6488. async function toggleRouteState(id, disabled) {
  6489. try {
  6490. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6491. method: 'POST',
  6492. headers: { 'Content-Type': 'application/json' },
  6493. body: JSON.stringify({ disabled })
  6494. });
  6495. if (res.ok) loadRoutes();
  6496. } catch (err) {
  6497. showToast('Error', err.message, 'error');
  6498. }
  6499. }
  6500. async function deleteRoute(id) {
  6501. if (!confirm('Are you sure you want to delete this route?')) return;
  6502. try {
  6503. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6504. if (res.ok) {
  6505. showToast('Deleted', 'Route removed', 'success');
  6506. loadRoutes();
  6507. }
  6508. } catch (err) {
  6509. showToast('Error', err.message, 'error');
  6510. }
  6511. }
  6512. // ----------------- Policy Rules (/ip route rule) -----------------
  6513. function renderPolicyRules() {
  6514. const tbody = document.getElementById('rules-table-body');
  6515. const empty = document.getElementById('rules-empty');
  6516. if (!tbody) return;
  6517. const showSystem = document.getElementById('prule-show-system')?.checked;
  6518. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6519. const countBadge = document.getElementById('rules-count-badge');
  6520. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6521. const bRules = document.getElementById('routes-badge-rules');
  6522. if (bRules) bRules.innerText = filtered.length;
  6523. if (filtered.length === 0) {
  6524. empty?.classList.remove('hidden');
  6525. tbody.innerHTML = '';
  6526. return;
  6527. }
  6528. empty?.classList.add('hidden');
  6529. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6530. if (tbody.dataset.sig === sig) return;
  6531. tbody.dataset.sig = sig;
  6532. tbody.innerHTML = '';
  6533. filtered.forEach(pr => {
  6534. const isSys = pr.is_default || pr.is_system;
  6535. const tr = document.createElement('tr');
  6536. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6537. tr.innerHTML = `
  6538. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6539. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6540. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6541. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6542. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6543. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6544. <td class="py-2.5 px-3 text-right font-sans">
  6545. ${!pr.is_default ? `
  6546. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6547. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6548. </td>
  6549. `;
  6550. tbody.appendChild(tr);
  6551. });
  6552. }
  6553. function openAddPolicyRuleModal() {
  6554. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6555. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6556. document.getElementById('prule-modal-mark').value = '';
  6557. document.getElementById('prule-modal-src').value = '';
  6558. document.getElementById('prule-modal-dst').value = '';
  6559. const sel = document.getElementById('prule-modal-table');
  6560. sel.innerHTML = '';
  6561. (state.routingTables || []).forEach(t => {
  6562. const opt = document.createElement('option');
  6563. opt.value = t.name;
  6564. opt.innerText = t.name;
  6565. sel.appendChild(opt);
  6566. });
  6567. document.getElementById('prule-modal').classList.remove('hidden');
  6568. }
  6569. function closePolicyRuleModal() {
  6570. document.getElementById('prule-modal').classList.add('hidden');
  6571. }
  6572. async function submitSavePolicyRule(e) {
  6573. e.preventDefault();
  6574. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6575. const mark = document.getElementById('prule-modal-mark').value.trim();
  6576. const src = document.getElementById('prule-modal-src').value.trim();
  6577. const dst = document.getElementById('prule-modal-dst').value.trim();
  6578. const table = document.getElementById('prule-modal-table').value;
  6579. const action = document.getElementById('prule-modal-action').value;
  6580. try {
  6581. const res = await fetch(`${API_BASE}/routing/rules`, {
  6582. method: 'POST',
  6583. headers: { 'Content-Type': 'application/json' },
  6584. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6585. });
  6586. if (res.ok) {
  6587. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6588. closePolicyRuleModal();
  6589. loadRoutes();
  6590. } else {
  6591. const err = await res.json();
  6592. showToast('Error', err.message, 'error');
  6593. }
  6594. } catch (err) {
  6595. showToast('Error', err.message, 'error');
  6596. }
  6597. }
  6598. async function deletePolicyRule(id) {
  6599. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6600. try {
  6601. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6602. if (res.ok) {
  6603. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6604. loadRoutes();
  6605. }
  6606. } catch (err) {
  6607. showToast('Error', err.message, 'error');
  6608. }
  6609. }
  6610. // ----------------- Routing Tables -----------------
  6611. function renderRoutingTables() {
  6612. const tbody = document.getElementById('tables-table-body');
  6613. if (!tbody) return;
  6614. const tables = state.routingTables || [];
  6615. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6616. if (tbody.dataset.sig === sig) return;
  6617. tbody.dataset.sig = sig;
  6618. tbody.innerHTML = '';
  6619. (state.routingTables || []).forEach(t => {
  6620. const tr = document.createElement('tr');
  6621. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6622. tr.innerHTML = `
  6623. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6624. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6625. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6626. `;
  6627. tbody.appendChild(tr);
  6628. });
  6629. }
  6630. function openAddTableModal() {
  6631. document.getElementById('table-modal-name').value = '';
  6632. document.getElementById('table-modal-id').value = '';
  6633. document.getElementById('table-modal-comment').value = '';
  6634. document.getElementById('table-modal').classList.remove('hidden');
  6635. }
  6636. function closeTableModal() {
  6637. document.getElementById('table-modal').classList.add('hidden');
  6638. }
  6639. async function submitSaveTable(e) {
  6640. e.preventDefault();
  6641. const name = document.getElementById('table-modal-name').value.trim();
  6642. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6643. const comment = document.getElementById('table-modal-comment').value.trim();
  6644. try {
  6645. const res = await fetch(`${API_BASE}/routing/tables`, {
  6646. method: 'POST',
  6647. headers: { 'Content-Type': 'application/json' },
  6648. body: JSON.stringify({ name, table_id: id, comment })
  6649. });
  6650. if (res.ok) {
  6651. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6652. closeTableModal();
  6653. loadRoutes();
  6654. } else {
  6655. const err = await res.json();
  6656. showToast('Error', err.message, 'error');
  6657. }
  6658. } catch (err) {
  6659. showToast('Error', err.message, 'error');
  6660. }
  6661. }
  6662. async function loadDebianConfig() {
  6663. const view = document.getElementById('debian-config-view');
  6664. view.innerText = 'Generating live configuration...';
  6665. try {
  6666. const res = await fetch(`${API_BASE}/debian/config`);
  6667. const data = await res.json();
  6668. view.innerText = data.content || '# Empty config';
  6669. } catch (err) {
  6670. view.innerText = 'Failed to generate Debian network config.';
  6671. }
  6672. }
  6673. async function saveDebianConfig() {
  6674. try {
  6675. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6676. const data = await res.json();
  6677. if (res.ok) {
  6678. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6679. loadDebianConfig();
  6680. }
  6681. } catch (err) {
  6682. showToast('Error', err.message, 'error');
  6683. }
  6684. }
  6685. function showToast(title, message, type = 'info') {
  6686. const container = document.getElementById('toast-container');
  6687. const toast = document.createElement('div');
  6688. const borderColors = {
  6689. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6690. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6691. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6692. };
  6693. 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}`;
  6694. toast.innerHTML = `
  6695. <div class="flex-1">
  6696. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  6697. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  6698. </div>
  6699. `;
  6700. container.appendChild(toast);
  6701. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6702. setTimeout(() => {
  6703. toast.classList.add('opacity-0', 'translate-y-2');
  6704. setTimeout(() => toast.remove(), 300);
  6705. }, 4000);
  6706. }
  6707. function formatTraffic(bytesPerSec) {
  6708. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6709. const kb = bytesPerSec / 1024;
  6710. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6711. const mb = kb / 1024;
  6712. return `${mb.toFixed(2)} MB/s`;
  6713. }
  6714. function toggleSidebar() {
  6715. const sb = document.getElementById('sidebar');
  6716. sb.classList.toggle('-translate-x-full');
  6717. }
  6718. // ======================== EoIP (Ethernet over IP) ========================
  6719. async function loadEoIP(populate = true) {
  6720. try {
  6721. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6722. const data = await res.json();
  6723. state.eoipTunnels = Array.isArray(data) ? data : [];
  6724. const badge = document.getElementById('eoip-count-badge');
  6725. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6726. const sideBadge = document.getElementById('badge-eoip-count');
  6727. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6728. renderEoIPTunnels();
  6729. } catch (err) {
  6730. console.error('Failed to load EoIP:', err);
  6731. }
  6732. }
  6733. function renderEoIPTunnels() {
  6734. const tbody = document.getElementById('eoip-table-body');
  6735. const empty = document.getElementById('eoip-empty');
  6736. if (!tbody) return;
  6737. tbody.innerHTML = '';
  6738. const tunnels = state.eoipTunnels || [];
  6739. if (tunnels.length === 0) {
  6740. empty?.classList.remove('hidden');
  6741. return;
  6742. }
  6743. empty?.classList.add('hidden');
  6744. tunnels.forEach(t => {
  6745. const tr = document.createElement('tr');
  6746. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6747. tr.innerHTML = `
  6748. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6749. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6750. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6751. <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>
  6752. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6753. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6754. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6755. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6756. <td class="py-2.5 px-3 font-mono text-[11px]">
  6757. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6758. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6759. </td>
  6760. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6761. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6762. <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>
  6763. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6764. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6765. </td>
  6766. `;
  6767. tbody.appendChild(tr);
  6768. });
  6769. }
  6770. function openAddEoIPModal() {
  6771. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6772. document.getElementById('eoip-modal-id').value = '';
  6773. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6774. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6775. document.getElementById('eoip-modal-remote').value = '';
  6776. document.getElementById('eoip-modal-ip').value = '';
  6777. document.getElementById('eoip-modal-local').value = '';
  6778. document.getElementById('eoip-modal-mac').value = '';
  6779. document.getElementById('eoip-modal-mtu').value = '1500';
  6780. document.getElementById('eoip-modal-comment').value = '';
  6781. document.getElementById('eoip-modal-clampmss').checked = true;
  6782. document.getElementById('eoip-modal-disabled').checked = false;
  6783. document.getElementById('eoip-modal').classList.remove('hidden');
  6784. }
  6785. function openEditEoIPModal(id) {
  6786. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6787. if (!t) return;
  6788. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6789. document.getElementById('eoip-modal-id').value = t.id;
  6790. document.getElementById('eoip-modal-name').value = t.name;
  6791. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6792. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6793. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6794. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6795. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6796. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6797. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6798. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6799. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6800. document.getElementById('eoip-modal').classList.remove('hidden');
  6801. }
  6802. function closeEoIPModal() {
  6803. document.getElementById('eoip-modal').classList.add('hidden');
  6804. }
  6805. async function submitSaveEoIP(e) {
  6806. e.preventDefault();
  6807. const id = document.getElementById('eoip-modal-id').value;
  6808. const name = document.getElementById('eoip-modal-name').value.trim();
  6809. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6810. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6811. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6812. const local = document.getElementById('eoip-modal-local').value.trim();
  6813. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6814. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6815. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6816. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6817. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6818. try {
  6819. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6820. method: 'POST',
  6821. headers: { 'Content-Type': 'application/json' },
  6822. body: JSON.stringify({
  6823. id,
  6824. name,
  6825. tunnel_id: tunnelId,
  6826. remote_address: remote,
  6827. ip_address: ipAddress,
  6828. local_address: local,
  6829. mac_address: mac,
  6830. mtu,
  6831. clamp_mss: clampMss,
  6832. comment,
  6833. disabled
  6834. })
  6835. });
  6836. if (res.ok) {
  6837. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6838. closeEoIPModal();
  6839. loadEoIP(false);
  6840. fetchData(false);
  6841. } else {
  6842. const err = await res.json();
  6843. showToast('Error', err.message, 'error');
  6844. }
  6845. } catch (err) {
  6846. showToast('Error', err.message, 'error');
  6847. }
  6848. }
  6849. async function toggleEoIPState(id, disabled) {
  6850. try {
  6851. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6852. method: 'POST',
  6853. headers: { 'Content-Type': 'application/json' },
  6854. body: JSON.stringify({ disabled })
  6855. });
  6856. if (res.ok) {
  6857. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6858. loadEoIP(false);
  6859. fetchData(false);
  6860. }
  6861. } catch (err) {
  6862. showToast('Error', err.message, 'error');
  6863. }
  6864. }
  6865. async function deleteEoIP(id) {
  6866. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6867. try {
  6868. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6869. if (res.ok) {
  6870. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6871. loadEoIP(false);
  6872. fetchData(false);
  6873. }
  6874. } catch (err) {
  6875. showToast('Error', err.message, 'error');
  6876. }
  6877. }
  6878. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6879. async function loadAeroTUN(populate = true) {
  6880. try {
  6881. const [tunnelsRes, statsRes] = await Promise.all([
  6882. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6883. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6884. ]);
  6885. if (tunnelsRes.ok) {
  6886. const data = await tunnelsRes.json();
  6887. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6888. }
  6889. if (statsRes.ok) {
  6890. state.aerotunStats = await statsRes.json();
  6891. }
  6892. const countBadge = document.getElementById('aerotun-count-badge');
  6893. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6894. const sideBadge = document.getElementById('badge-aerotun-count');
  6895. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6896. renderAeroTUN();
  6897. } catch (err) {
  6898. console.error('Failed to load AeroTUN:', err);
  6899. }
  6900. }
  6901. function renderAeroTUN() {
  6902. const tbody = document.getElementById('aerotun-table-body');
  6903. const empty = document.getElementById('aerotun-empty');
  6904. // Update summary cards
  6905. const stats = state.aerotunStats || {};
  6906. const tunnels = state.aerotunTunnels || [];
  6907. const statActive = document.getElementById('aerotun-stat-active');
  6908. if (statActive) {
  6909. const activeCount = tunnels.filter(t => t.connected).length;
  6910. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6911. }
  6912. const statSaved = document.getElementById('aerotun-stat-saved');
  6913. if (statSaved) {
  6914. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6915. }
  6916. const statRatio = document.getElementById('aerotun-stat-ratio');
  6917. if (statRatio) {
  6918. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6919. }
  6920. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6921. if (statTraffic) {
  6922. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6923. }
  6924. if (!tbody) return;
  6925. tbody.innerHTML = '';
  6926. if (tunnels.length === 0) {
  6927. empty?.classList.remove('hidden');
  6928. return;
  6929. }
  6930. empty?.classList.add('hidden');
  6931. tunnels.forEach(t => {
  6932. const tr = document.createElement('tr');
  6933. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6934. const modeBadge = t.mode === 'server'
  6935. ? `<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>`
  6936. : `<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>`;
  6937. const endpointInfo = t.mode === 'server'
  6938. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6939. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6940. const compBadge = t.compression
  6941. ? `<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>`
  6942. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6943. const activePeer = t.connected && t.active_peer_endpoint
  6944. ? `<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>`
  6945. : `<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>`;
  6946. const rawRx = formatBytes(t.rx_bytes || 0);
  6947. const rawTx = formatBytes(t.tx_bytes || 0);
  6948. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6949. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6950. tr.innerHTML = `
  6951. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6952. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6953. <span>${escapeHtml(t.name)}</span>
  6954. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6955. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6956. </td>
  6957. <td class="py-2.5 px-3">${modeBadge}</td>
  6958. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6959. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6960. <td class="py-2.5 px-3">${compBadge}</td>
  6961. <td class="py-2.5 px-3">${activePeer}</td>
  6962. <td class="py-2.5 px-3 font-mono text-[11px]">
  6963. <span class="text-emerald-400">↓ ${rawRx}</span>
  6964. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6965. </td>
  6966. <td class="py-2.5 px-3 font-mono text-[11px]">
  6967. <span class="text-slate-400">↓ ${wireRx}</span>
  6968. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6969. </td>
  6970. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6971. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6972. ${t.running
  6973. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6974. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6975. }
  6976. <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>
  6977. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6978. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6979. </td>
  6980. `;
  6981. tbody.appendChild(tr);
  6982. });
  6983. }
  6984. function onAeroTUNModeChange() {
  6985. const mode = document.getElementById('aerotun-modal-mode').value;
  6986. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6987. const portInput = document.getElementById('aerotun-modal-port');
  6988. if (mode === 'server') {
  6989. if (!portInput.value) portInput.value = '51830';
  6990. endpointInput.placeholder = 'Optional / learned roaming peer';
  6991. } else {
  6992. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6993. if (!portInput.value) portInput.value = '';
  6994. }
  6995. }
  6996. async function generateAeroTUNKey() {
  6997. try {
  6998. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6999. if (!res.ok) throw new Error(await responseError(res));
  7000. const data = await res.json();
  7001. document.getElementById('aerotun-modal-psk').value = data.key;
  7002. showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7003. } catch (err) {
  7004. showToast('Key Generation Failed', err.message, 'error');
  7005. }
  7006. }
  7007. function updateAeroTUNSetupHint() {
  7008. const version = document.getElementById('aerotun-modal-protocol').value;
  7009. const key = document.getElementById('aerotun-modal-public').value;
  7010. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7011. const hint = document.getElementById('aerotun-setup-hint');
  7012. if (!hint) return;
  7013. 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.';
  7014. }
  7015. async function copyAeroTUNPublicKey() {
  7016. const input = document.getElementById('aerotun-modal-public');
  7017. if (!input.value) { showToast('Save First', 'Save the disabled tunnel to create its public key', 'info'); return; }
  7018. try {
  7019. await navigator.clipboard.writeText(input.value);
  7020. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7021. } catch {
  7022. input.focus(); input.select();
  7023. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7024. }
  7025. }
  7026. function openAddAeroTUNModal() {
  7027. const tunnels = state.aerotunTunnels || [];
  7028. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7029. document.getElementById('aerotun-modal-id').value = '';
  7030. document.getElementById('aerotun-modal-protocol').value='3';
  7031. document.getElementById('aerotun-modal-public').value='';
  7032. document.getElementById('aerotun-modal-peerkey').value='';
  7033. document.getElementById('aerotun-modal-allowed').value=`10.99.${tunnels.length}.2/32`;
  7034. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  7035. document.getElementById('aerotun-modal-mode').value = 'server';
  7036. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  7037. document.getElementById('aerotun-modal-endpoint').value = '';
  7038. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  7039. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  7040. document.getElementById('aerotun-modal-psk').value = '';
  7041. document.getElementById('aerotun-modal-mtu').value = '1420';
  7042. document.getElementById('aerotun-modal-comment').value = '';
  7043. document.getElementById('aerotun-modal-compression').checked = false;
  7044. document.getElementById('aerotun-modal-defroute').checked = false;
  7045. document.getElementById('aerotun-modal-disabled').checked = true;
  7046. generateAeroTUNKey();
  7047. onAeroTUNModeChange();
  7048. updateAeroTUNSetupHint();
  7049. document.getElementById('aerotun-modal').classList.remove('hidden');
  7050. }
  7051. function openEditAeroTUNModal(id) {
  7052. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7053. if (!t) return;
  7054. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7055. document.getElementById('aerotun-modal-id').value = t.id;
  7056. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7057. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7058. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7059. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7060. document.getElementById('aerotun-modal-name').value = t.name;
  7061. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7062. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7063. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7064. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7065. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7066. document.getElementById('aerotun-modal-psk').value = '';
  7067. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7068. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7069. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7070. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7071. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7072. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7073. onAeroTUNModeChange();
  7074. updateAeroTUNSetupHint();
  7075. document.getElementById('aerotun-modal').classList.remove('hidden');
  7076. }
  7077. function closeAeroTUNModal() {
  7078. document.getElementById('aerotun-modal').classList.add('hidden');
  7079. }
  7080. async function submitSaveAeroTUN(e) {
  7081. e.preventDefault();
  7082. const id = document.getElementById('aerotun-modal-id').value;
  7083. const name = document.getElementById('aerotun-modal-name').value.trim();
  7084. const mode = document.getElementById('aerotun-modal-mode').value;
  7085. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7086. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7087. const local = document.getElementById('aerotun-modal-local').value.trim();
  7088. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7089. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7090. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  7091. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7092. const compression = document.getElementById('aerotun-modal-compression').checked;
  7093. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7094. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7095. if (mode === 'client' && !endpoint) {
  7096. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7097. return;
  7098. }
  7099. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7100. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7101. showToast('Peer Key Required', 'Save disabled first, exchange public keys, then enable', 'error');
  7102. return;
  7103. }
  7104. if (!psk && !id) {
  7105. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7106. return;
  7107. }
  7108. try {
  7109. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7110. method: 'POST',
  7111. headers: { 'Content-Type': 'application/json' },
  7112. body: JSON.stringify({
  7113. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7114. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7115. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7116. id,
  7117. name,
  7118. mode,
  7119. listen_port: port,
  7120. remote_endpoint: endpoint,
  7121. local_address: local,
  7122. peer_address: peer,
  7123. psk,
  7124. mtu,
  7125. compression,
  7126. default_route: defaultRoute,
  7127. comment,
  7128. disabled
  7129. })
  7130. });
  7131. if (res.ok) {
  7132. const saved = await res.json();
  7133. await loadAeroTUN(false);
  7134. if (!id && version === 3) {
  7135. openEditAeroTUNModal(saved.id);
  7136. showToast('Identity Saved', 'Copy the local public key and exchange keys with the peer', 'success');
  7137. } else {
  7138. closeAeroTUNModal();
  7139. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7140. }
  7141. fetchData(false);
  7142. } else {
  7143. const err = await res.text();
  7144. showToast('Error Saving Tunnel', err, 'error');
  7145. }
  7146. } catch (err) {
  7147. showToast('Network Error', err.message, 'error');
  7148. }
  7149. }
  7150. async function startAeroTUNTunnel(id) {
  7151. try {
  7152. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7153. if (res.ok) {
  7154. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7155. loadAeroTUN(false);
  7156. fetchData(false);
  7157. } else {
  7158. const err = await res.text();
  7159. showToast('Failed to Start', err, 'error');
  7160. }
  7161. } catch (err) {
  7162. showToast('Error', err.message, 'error');
  7163. }
  7164. }
  7165. async function stopAeroTUNTunnel(id) {
  7166. try {
  7167. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7168. if (res.ok) {
  7169. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7170. loadAeroTUN(false);
  7171. fetchData(false);
  7172. } else {
  7173. const err = await res.text();
  7174. showToast('Failed to Stop', err, 'error');
  7175. }
  7176. } catch (err) {
  7177. showToast('Error', err.message, 'error');
  7178. }
  7179. }
  7180. async function toggleAeroTUNState(id, disabled) {
  7181. try {
  7182. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7183. method: 'POST',
  7184. headers: { 'Content-Type': 'application/json' },
  7185. body: JSON.stringify({ disabled })
  7186. });
  7187. if (res.ok) {
  7188. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7189. loadAeroTUN(false);
  7190. fetchData(false);
  7191. }
  7192. } catch (err) {
  7193. showToast('Error', err.message, 'error');
  7194. }
  7195. }
  7196. async function deleteAeroTUN(id) {
  7197. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7198. try {
  7199. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7200. if (res.ok) {
  7201. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7202. loadAeroTUN(false);
  7203. fetchData(false);
  7204. }
  7205. } catch (err) {
  7206. showToast('Error', err.message, 'error');
  7207. }
  7208. }
  7209. // ======================== PPP Central Hub & Servers ========================
  7210. function switchPPPSubTab(tab) {
  7211. state.pppSubTab = tab;
  7212. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7213. tabs.forEach(t => {
  7214. const panel = document.getElementById(`ppp-subtab-${t}`);
  7215. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7216. if (panel) {
  7217. if (t === tab) panel.classList.remove('hidden');
  7218. else panel.classList.add('hidden');
  7219. }
  7220. if (btn) {
  7221. if (t === tab) {
  7222. 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';
  7223. } else {
  7224. 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';
  7225. }
  7226. }
  7227. });
  7228. const addBtn = document.getElementById('ppp-primary-add-btn');
  7229. if (addBtn) {
  7230. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7231. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7232. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7233. else addBtn.innerHTML = '<span>Save Config</span>';
  7234. }
  7235. if (tab === 'active') loadPPPSessions();
  7236. }
  7237. function openCurrentPPPModal() {
  7238. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7239. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7240. else if (state.pppSubTab === 'active') loadPPPSessions();
  7241. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7242. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7243. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7244. }
  7245. async function loadPPP(populateDropdowns = true) {
  7246. await Promise.all([
  7247. loadPPPSecrets(),
  7248. loadPPPProfiles(),
  7249. loadPPPServers(),
  7250. loadPPPSessions()
  7251. ]);
  7252. }
  7253. async function loadPPPSecrets() {
  7254. try {
  7255. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7256. const data = await res.json();
  7257. state.pppSecrets = Array.isArray(data) ? data : [];
  7258. const b = document.getElementById('ppp-badge-secrets');
  7259. if (b) b.innerText = state.pppSecrets.length;
  7260. const b2 = document.getElementById('secrets-count-badge');
  7261. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7262. renderPPPSecrets();
  7263. } catch (err) {
  7264. console.error('Failed to load PPP secrets:', err);
  7265. }
  7266. }
  7267. function renderPPPSecrets() {
  7268. const tbody = document.getElementById('secrets-table-body');
  7269. const empty = document.getElementById('secrets-empty');
  7270. if (!tbody) return;
  7271. tbody.innerHTML = '';
  7272. const secrets = state.pppSecrets || [];
  7273. if (secrets.length === 0) {
  7274. empty?.classList.remove('hidden');
  7275. return;
  7276. }
  7277. empty?.classList.add('hidden');
  7278. secrets.forEach(s => {
  7279. const tr = document.createElement('tr');
  7280. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7281. tr.innerHTML = `
  7282. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7283. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7284. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7285. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7286. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7287. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7288. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7289. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7290. <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>
  7291. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7292. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7293. </td>
  7294. `;
  7295. tbody.appendChild(tr);
  7296. });
  7297. }
  7298. async function loadPPPProfiles() {
  7299. try {
  7300. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7301. const data = await res.json();
  7302. state.pppProfiles = Array.isArray(data) ? data : [];
  7303. const b = document.getElementById('ppp-badge-profiles');
  7304. if (b) b.innerText = state.pppProfiles.length;
  7305. const b2 = document.getElementById('profiles-count-badge');
  7306. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7307. // Populate profile selects across modals
  7308. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7309. selects.forEach(sid => {
  7310. const el = document.getElementById(sid);
  7311. if (!el) return;
  7312. const cur = el.value;
  7313. el.innerHTML = '';
  7314. state.pppProfiles.forEach(p => {
  7315. const opt = document.createElement('option');
  7316. opt.value = p.name;
  7317. opt.innerText = `${p.name} (${p.remote_address})`;
  7318. if (p.name === cur) opt.selected = true;
  7319. el.appendChild(opt);
  7320. });
  7321. });
  7322. renderPPPProfiles();
  7323. } catch (err) {
  7324. console.error('Failed to load PPP profiles:', err);
  7325. }
  7326. }
  7327. function renderPPPProfiles() {
  7328. const tbody = document.getElementById('profiles-table-body');
  7329. if (!tbody) return;
  7330. tbody.innerHTML = '';
  7331. (state.pppProfiles || []).forEach(p => {
  7332. const isDefault = p.name.startsWith('default');
  7333. const tr = document.createElement('tr');
  7334. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7335. tr.innerHTML = `
  7336. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7337. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7338. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7339. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7340. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7341. <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>
  7342. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7343. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7344. ${!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>`}
  7345. </td>
  7346. `;
  7347. tbody.appendChild(tr);
  7348. });
  7349. }
  7350. async function loadPPPServers() {
  7351. try {
  7352. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7353. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7354. fetch(`${API_BASE}/vpn/servers/pptp`),
  7355. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7356. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7357. ]);
  7358. if (pppoeRes.ok) {
  7359. state.pppoeServer = await pppoeRes.json();
  7360. const s = state.pppoeServer;
  7361. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7362. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7363. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7364. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7365. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7366. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7367. const pill = document.getElementById('pppoe-server-status-pill');
  7368. if (pill) {
  7369. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7370. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-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';
  7371. }
  7372. setDotBadge('ppp-badge-pppoe-state', s.running);
  7373. }
  7374. if (pptpRes.ok) {
  7375. state.pptpServer = await pptpRes.json();
  7376. const s = state.pptpServer;
  7377. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7378. document.getElementById('pptp-server-port').value = s.port || 1723;
  7379. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7380. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7381. const pill = document.getElementById('pptp-server-status-pill');
  7382. if (pill) {
  7383. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7384. 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';
  7385. }
  7386. setDotBadge('ppp-badge-pptp-state', s.running);
  7387. }
  7388. if (l2tpRes.ok) {
  7389. state.l2tpServer = await l2tpRes.json();
  7390. const s = state.l2tpServer;
  7391. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7392. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7393. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7394. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7395. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7396. const pill = document.getElementById('l2tp-server-status-pill');
  7397. if (pill) {
  7398. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7399. 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';
  7400. }
  7401. setDotBadge('ppp-badge-l2tp-state', s.running);
  7402. }
  7403. if (ipsecRes.ok) {
  7404. state.ipsecServer = await ipsecRes.json();
  7405. const s = state.ipsecServer;
  7406. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7407. if (modalEn) modalEn.checked = !!s.enabled;
  7408. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7409. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7410. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7411. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7412. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7413. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7414. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7415. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7416. const pill = document.getElementById('modal-ipsec-server-status');
  7417. if (pill) {
  7418. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7419. 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';
  7420. }
  7421. }
  7422. } catch (err) {
  7423. console.error('Failed to load VPN servers:', err);
  7424. }
  7425. }
  7426. async function loadPPPSessions() {
  7427. try {
  7428. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7429. const data = await res.json();
  7430. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7431. const b = document.getElementById('ppp-badge-active');
  7432. if (b) b.innerText = state.pppActiveSessions.length;
  7433. const sideB = document.getElementById('badge-ppp-sessions');
  7434. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7435. renderPPPSessions();
  7436. } catch (err) {
  7437. console.error('Failed to load active PPP sessions:', err);
  7438. }
  7439. }
  7440. function renderPPPSessions() {
  7441. const tbody = document.getElementById('active-ppp-table-body');
  7442. const empty = document.getElementById('active-ppp-empty');
  7443. if (!tbody) return;
  7444. tbody.innerHTML = '';
  7445. const list = state.pppActiveSessions || [];
  7446. if (list.length === 0) {
  7447. empty?.classList.remove('hidden');
  7448. return;
  7449. }
  7450. empty?.classList.add('hidden');
  7451. list.forEach(s => {
  7452. const tr = document.createElement('tr');
  7453. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7454. tr.innerHTML = `
  7455. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7456. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7457. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7458. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7459. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7460. <td class="py-2.5 px-3 text-[11px]">
  7461. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7462. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7463. </td>
  7464. <td class="py-2.5 px-3 text-right font-sans">
  7465. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7466. </td>
  7467. `;
  7468. tbody.appendChild(tr);
  7469. });
  7470. }
  7471. async function disconnectPPPSession(iface) {
  7472. if (!confirm(`Disconnect session ${iface}?`)) return;
  7473. try {
  7474. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7475. if (res.ok) {
  7476. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7477. loadPPPSessions();
  7478. }
  7479. } catch (err) {
  7480. showToast('Error', err.message, 'error');
  7481. }
  7482. }
  7483. // PPP Secret Modal handlers
  7484. function openAddPPPSecretModal() {
  7485. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7486. document.getElementById('secret-modal-id').value = '';
  7487. document.getElementById('secret-modal-name').value = '';
  7488. document.getElementById('secret-modal-password').value = '';
  7489. document.getElementById('secret-modal-service').value = 'any';
  7490. document.getElementById('secret-modal-profile').value = 'default';
  7491. document.getElementById('secret-modal-local').value = '';
  7492. document.getElementById('secret-modal-remote').value = '';
  7493. document.getElementById('secret-modal-comment').value = '';
  7494. document.getElementById('secret-modal-disabled').checked = false;
  7495. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7496. }
  7497. function openEditPPPSecretModal(id) {
  7498. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7499. if (!s) return;
  7500. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7501. document.getElementById('secret-modal-id').value = s.id;
  7502. document.getElementById('secret-modal-name').value = s.name;
  7503. document.getElementById('secret-modal-password').value = s.password;
  7504. document.getElementById('secret-modal-service').value = s.service || 'any';
  7505. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7506. document.getElementById('secret-modal-local').value = s.local_address || '';
  7507. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7508. document.getElementById('secret-modal-comment').value = s.comment || '';
  7509. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7510. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7511. }
  7512. function closePPPSecretModal() {
  7513. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7514. }
  7515. async function submitSavePPPSecret(e) {
  7516. e.preventDefault();
  7517. const id = document.getElementById('secret-modal-id').value;
  7518. const name = document.getElementById('secret-modal-name').value.trim();
  7519. const password = document.getElementById('secret-modal-password').value.trim();
  7520. const service = document.getElementById('secret-modal-service').value;
  7521. const profile = document.getElementById('secret-modal-profile').value;
  7522. const local = document.getElementById('secret-modal-local').value.trim();
  7523. const remote = document.getElementById('secret-modal-remote').value.trim();
  7524. const comment = document.getElementById('secret-modal-comment').value.trim();
  7525. const disabled = document.getElementById('secret-modal-disabled').checked;
  7526. try {
  7527. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7528. method: 'POST',
  7529. headers: { 'Content-Type': 'application/json' },
  7530. body: JSON.stringify({
  7531. id,
  7532. name,
  7533. password,
  7534. service,
  7535. profile,
  7536. local_address: local,
  7537. remote_address: remote,
  7538. comment,
  7539. disabled
  7540. })
  7541. });
  7542. if (res.ok) {
  7543. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7544. closePPPSecretModal();
  7545. loadPPPSecrets();
  7546. } else {
  7547. const err = await res.json();
  7548. showToast('Error', err.message, 'error');
  7549. }
  7550. } catch (err) {
  7551. showToast('Error', err.message, 'error');
  7552. }
  7553. }
  7554. async function togglePPPSecretState(id, disabled) {
  7555. try {
  7556. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7557. method: 'POST',
  7558. headers: { 'Content-Type': 'application/json' },
  7559. body: JSON.stringify({ disabled })
  7560. });
  7561. if (res.ok) {
  7562. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7563. loadPPPSecrets();
  7564. }
  7565. } catch (err) {
  7566. showToast('Error', err.message, 'error');
  7567. }
  7568. }
  7569. async function deletePPPSecret(id) {
  7570. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7571. try {
  7572. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7573. if (res.ok) {
  7574. showToast('Deleted', 'Secret account removed', 'success');
  7575. loadPPPSecrets();
  7576. }
  7577. } catch (err) {
  7578. showToast('Error', err.message, 'error');
  7579. }
  7580. }
  7581. // PPP Profile Modal handlers
  7582. function openAddPPPProfileModal() {
  7583. document.getElementById('profile-modal-name').value = '';
  7584. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7585. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7586. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7587. document.getElementById('profile-modal-encryption').value = 'required';
  7588. document.getElementById('profile-modal-onlyone').checked = true;
  7589. document.getElementById('profile-modal-comment').value = '';
  7590. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7591. }
  7592. function closePPPProfileModal() {
  7593. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7594. }
  7595. async function submitSavePPPProfile(e) {
  7596. e.preventDefault();
  7597. const name = document.getElementById('profile-modal-name').value.trim();
  7598. const local = document.getElementById('profile-modal-local').value.trim();
  7599. const remote = document.getElementById('profile-modal-remote').value.trim();
  7600. const dns = document.getElementById('profile-modal-dns').value.trim();
  7601. const enc = document.getElementById('profile-modal-encryption').value;
  7602. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7603. const comment = document.getElementById('profile-modal-comment').value.trim();
  7604. try {
  7605. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7606. method: 'POST',
  7607. headers: { 'Content-Type': 'application/json' },
  7608. body: JSON.stringify({
  7609. id: name,
  7610. name,
  7611. local_address: local,
  7612. remote_address: remote,
  7613. dns_servers: dns,
  7614. use_encryption: enc,
  7615. only_one: onlyone,
  7616. comment
  7617. })
  7618. });
  7619. if (res.ok) {
  7620. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7621. closePPPProfileModal();
  7622. loadPPPProfiles();
  7623. } else {
  7624. const err = await res.json();
  7625. showToast('Error', err.message, 'error');
  7626. }
  7627. } catch (err) {
  7628. showToast('Error', err.message, 'error');
  7629. }
  7630. }
  7631. async function deletePPPProfile(name) {
  7632. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7633. try {
  7634. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7635. if (res.ok) {
  7636. showToast('Deleted', 'Profile removed', 'success');
  7637. loadPPPProfiles();
  7638. } else {
  7639. const err = await res.json();
  7640. showToast('Error', err.message, 'error');
  7641. }
  7642. } catch (err) {
  7643. showToast('Error', err.message, 'error');
  7644. }
  7645. }
  7646. // Server Config submissions
  7647. async function savePPPoEServerConfig(e) {
  7648. e.preventDefault();
  7649. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7650. const name = document.getElementById('pppoe-server-name').value.trim();
  7651. const iface = document.getElementById('pppoe-server-iface').value;
  7652. const profile = document.getElementById('pppoe-server-profile').value;
  7653. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7654. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7655. try {
  7656. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7657. method: 'POST',
  7658. headers: { 'Content-Type': 'application/json' },
  7659. body: JSON.stringify({
  7660. enabled,
  7661. service_name: name,
  7662. interface: iface,
  7663. default_profile: profile,
  7664. max_mtu: mtu,
  7665. max_mru: mtu,
  7666. one_session_per_host: onesession
  7667. })
  7668. });
  7669. if (res.ok) {
  7670. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7671. loadPPPServers();
  7672. fetchData(false);
  7673. } else {
  7674. const err = await res.json();
  7675. showToast('Error', err.message, 'error');
  7676. }
  7677. } catch (err) {
  7678. showToast('Error', err.message, 'error');
  7679. }
  7680. }
  7681. async function savePPTPServerConfig(e) {
  7682. e.preventDefault();
  7683. const enabled = document.getElementById('pptp-server-enabled').checked;
  7684. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7685. const profile = document.getElementById('pptp-server-profile').value;
  7686. const mppe = document.getElementById('pptp-server-mppe').checked;
  7687. try {
  7688. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7689. method: 'POST',
  7690. headers: { 'Content-Type': 'application/json' },
  7691. body: JSON.stringify({
  7692. enabled,
  7693. port,
  7694. default_profile: profile,
  7695. require_mppe: mppe
  7696. })
  7697. });
  7698. if (res.ok) {
  7699. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7700. loadPPPServers();
  7701. fetchData(false);
  7702. } else {
  7703. const err = await res.json();
  7704. showToast('Error', err.message, 'error');
  7705. }
  7706. } catch (err) {
  7707. showToast('Error', err.message, 'error');
  7708. }
  7709. }
  7710. async function saveL2TPServerConfig(e) {
  7711. e.preventDefault();
  7712. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7713. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7714. const profile = document.getElementById('l2tp-server-profile').value;
  7715. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7716. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7717. try {
  7718. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7719. method: 'POST',
  7720. headers: { 'Content-Type': 'application/json' },
  7721. body: JSON.stringify({
  7722. enabled,
  7723. port,
  7724. default_profile: profile,
  7725. use_ipsec: useipsec,
  7726. ipsec_secret: psk
  7727. })
  7728. });
  7729. if (res.ok) {
  7730. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7731. loadPPPServers();
  7732. fetchData(false);
  7733. } else {
  7734. const err = await res.json();
  7735. showToast('Error', err.message, 'error');
  7736. }
  7737. } catch (err) {
  7738. showToast('Error', err.message, 'error');
  7739. }
  7740. }
  7741. // IPSec Server Modal
  7742. function openIPSecServerModal() {
  7743. loadPPPServers();
  7744. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7745. }
  7746. function closeIPSecServerModal() {
  7747. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7748. }
  7749. async function submitSaveIPSecServer(e) {
  7750. e.preventDefault();
  7751. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7752. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7753. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7754. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7755. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7756. try {
  7757. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7758. method: 'POST',
  7759. headers: { 'Content-Type': 'application/json' },
  7760. body: JSON.stringify({
  7761. enabled,
  7762. preshared_key: psk,
  7763. pool_address: pool,
  7764. dns_servers: dns,
  7765. local_subnet: subnet
  7766. })
  7767. });
  7768. if (res.ok) {
  7769. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7770. closeIPSecServerModal();
  7771. loadPPPServers();
  7772. fetchData(false);
  7773. } else {
  7774. const err = await res.json();
  7775. showToast('Error', err.message, 'error');
  7776. }
  7777. } catch (err) {
  7778. showToast('Error', err.message, 'error');
  7779. }
  7780. }
  7781. // WireGuard Client Config Viewer
  7782. let currentWGClientConf = '';
  7783. async function openWGClientConfModal(iface, clientIP) {
  7784. try {
  7785. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7786. method: 'POST',
  7787. headers: { 'Content-Type': 'application/json' },
  7788. body: JSON.stringify({
  7789. interface: iface,
  7790. address: clientIP || '10.10.0.2/32',
  7791. dns: '1.1.1.1, 8.8.8.8'
  7792. })
  7793. });
  7794. if (res.ok) {
  7795. const data = await res.json();
  7796. currentWGClientConf = data.config;
  7797. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7798. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7799. } else {
  7800. const err = await res.json();
  7801. showToast('Error', err.message, 'error');
  7802. }
  7803. } catch (err) {
  7804. showToast('Error', err.message, 'error');
  7805. }
  7806. }
  7807. function closeWGClientConfModal() {
  7808. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7809. }
  7810. function copyWGClientConf() {
  7811. if (!currentWGClientConf) return;
  7812. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7813. }
  7814. function downloadWGClientConf() {
  7815. if (!currentWGClientConf) return;
  7816. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7817. const a = document.createElement('a');
  7818. a.href = URL.createObjectURL(blob);
  7819. a.download = 'wireguard-client.conf';
  7820. document.body.appendChild(a);
  7821. a.click();
  7822. document.body.removeChild(a);
  7823. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7824. }
  7825. // =========================================================================
  7826. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7827. // =========================================================================
  7828. state.activeDynSubTab = 'bgp-peers';
  7829. state.activeBgpSubTab = 'bgp-peers';
  7830. state.activeOspfTab = 'instances';
  7831. state.bgpInstance = null;
  7832. state.bgpPeers = [];
  7833. state.bgpNets = [];
  7834. state.bgpRoutes = [];
  7835. state.ospfInstance = null;
  7836. state.ospfInstances = [];
  7837. state.ospfAreas = [];
  7838. state.ospfAreaRanges = [];
  7839. state.ospfTemplates = [];
  7840. state.ospfLiveInterfaces = [];
  7841. state.ospfStaticNbrs = [];
  7842. state.ospfNeighbors = [];
  7843. state.ospfLSA = [];
  7844. state.ospfRoutes = [];
  7845. state.selectedOspfRow = {
  7846. instances: null,
  7847. areas: null,
  7848. 'area-ranges': null,
  7849. templates: null,
  7850. interfaces: null,
  7851. 'static-nbrs': null,
  7852. neighbors: null,
  7853. lsa: null,
  7854. };
  7855. state.ospfSort = {
  7856. instances: { col: 'name', asc: true },
  7857. areas: { col: 'name', asc: true },
  7858. ranges: { col: 'area', asc: true },
  7859. templates: { col: 'interfaces', asc: true },
  7860. live_ifaces: { col: 'interface', asc: true },
  7861. snbrs: { col: 'address', asc: true },
  7862. neighbors: { col: 'address', asc: true },
  7863. lsa: { col: 'instance', asc: true },
  7864. };
  7865. function switchBgpSubTab(subTab) {
  7866. state.activeBgpSubTab = subTab;
  7867. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7868. tabs.forEach(t => {
  7869. const el = document.getElementById(`dyn-subtab-${t}`);
  7870. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7871. if (el) el.classList.toggle('hidden', t !== subTab);
  7872. if (btn) {
  7873. if (t === subTab) {
  7874. 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';
  7875. } else {
  7876. 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';
  7877. }
  7878. }
  7879. });
  7880. }
  7881. function switchOspfTab(tabName) {
  7882. state.activeOspfTab = tabName;
  7883. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7884. tabs.forEach(t => {
  7885. const pane = document.getElementById(`ospf-pane-${t}`);
  7886. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7887. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7888. if (btn) {
  7889. if (t === tabName) {
  7890. 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';
  7891. } else {
  7892. 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';
  7893. }
  7894. }
  7895. });
  7896. }
  7897. function switchOspfSubTab(tab) {
  7898. // Legacy alias
  7899. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7900. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7901. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7902. else switchOspfTab('instances');
  7903. }
  7904. function switchDynSubTab(subTab) {
  7905. if (subTab.startsWith('bgp')) {
  7906. if (state.activeTab !== 'bgp') navigate('bgp');
  7907. switchBgpSubTab(subTab);
  7908. } else if (subTab.startsWith('ospf')) {
  7909. if (state.activeTab !== 'ospf') navigate('ospf');
  7910. switchOspfTab('instances');
  7911. }
  7912. }
  7913. async function loadDynamicRouting(showToastMsg = false) {
  7914. try {
  7915. const fetchSafeJson = async (url) => {
  7916. try {
  7917. const r = await fetch(url);
  7918. return r.ok ? await r.json() : null;
  7919. } catch (e) {
  7920. return null;
  7921. }
  7922. };
  7923. const [
  7924. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7925. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7926. selectRules, commLists, asLists
  7927. ] = await Promise.all([
  7928. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7929. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7930. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7931. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7932. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7933. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7934. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7935. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7936. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7937. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7938. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7939. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7940. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7941. fetchSafeJson(`${API_BASE}/routing/filters`),
  7942. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7943. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7944. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7945. ]);
  7946. if (sum) state.dynSummary = sum;
  7947. if (bgpInst) state.bgpInstance = bgpInst;
  7948. if (bgpPeers) state.bgpPeers = bgpPeers;
  7949. if (bgpNets) state.bgpNets = bgpNets;
  7950. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7951. if (ospfInsts) state.ospfInstances = ospfInsts;
  7952. if (ospfAreas) state.ospfAreas = ospfAreas;
  7953. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7954. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7955. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7956. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7957. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7958. if (ospfLsa) state.ospfLSA = ospfLsa;
  7959. if (filters) state.routingFilters = filters;
  7960. if (selectRules) state.routingSelectRules = selectRules;
  7961. if (commLists) state.routingCommunityLists = commLists;
  7962. if (asLists) state.routingASLists = asLists;
  7963. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7964. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7965. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7966. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7967. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7968. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7969. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7970. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7971. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7972. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7973. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7974. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7975. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7976. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7977. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7978. } catch (err) {
  7979. console.error('Failed to load dynamic routing:', err);
  7980. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7981. }
  7982. }
  7983. async function loadOspfAll() {
  7984. await loadDynamicRouting(true);
  7985. }
  7986. function renderBgpStatusPill() {
  7987. const pills = document.querySelectorAll('.bgp-live-status-pill');
  7988. pills.forEach(pill => {
  7989. const inst = state.bgpInstance;
  7990. if (!inst || !inst.enabled) {
  7991. 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';
  7992. pill.innerText = 'BGP DISABLED';
  7993. } else if (inst.running) {
  7994. 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';
  7995. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7996. } else {
  7997. 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';
  7998. pill.innerText = 'BGP STARTING...';
  7999. }
  8000. });
  8001. }
  8002. function renderBgpPeers() {
  8003. const tbody = document.getElementById('bgp-peers-table-body');
  8004. if (!tbody) return;
  8005. const empty = document.getElementById('bgp-peers-empty');
  8006. const countBadge = document.getElementById('bgp-peers-count-badge');
  8007. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8008. const peers = state.bgpPeers || [];
  8009. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8010. if (navBadge) navBadge.innerText = peers.length;
  8011. if (peers.length === 0) {
  8012. tbody.innerHTML = '';
  8013. if (empty) empty.classList.remove('hidden');
  8014. return;
  8015. }
  8016. if (empty) empty.classList.add('hidden');
  8017. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8018. if (tbody.dataset.sig === sig) return;
  8019. tbody.dataset.sig = sig;
  8020. tbody.innerHTML = peers.map(p => {
  8021. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8022. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8023. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8024. let stateBadge = '';
  8025. if (p.disabled) {
  8026. 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>';
  8027. } else if (p.state === 'Established') {
  8028. 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>';
  8029. } else if (p.state === 'Connect' || p.state === 'Active') {
  8030. 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>`;
  8031. } else {
  8032. 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>`;
  8033. }
  8034. return `
  8035. <tr class="hover:bg-slate-800/40 transition">
  8036. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8037. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8038. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8039. <td class="py-2.5 px-3">
  8040. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8041. ${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>`}
  8042. </td>
  8043. <td class="py-2.5 px-3">${stateBadge}</td>
  8044. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8045. <td class="py-2.5 px-3 text-slate-300">
  8046. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8047. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8048. </td>
  8049. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8050. ${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> ` : ''}
  8051. ${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>` : ''}
  8052. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8053. </td>
  8054. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8055. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8056. <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'}">
  8057. ${p.disabled ? 'Enable' : 'Disable'}
  8058. </button>
  8059. <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">
  8060. Edit
  8061. </button>
  8062. <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">
  8063. Delete
  8064. </button>
  8065. </td>
  8066. </tr>
  8067. `;
  8068. }).join('');
  8069. }
  8070. function renderBgpNetworks() {
  8071. const tbody = document.getElementById('bgp-nets-table-body');
  8072. if (!tbody) return;
  8073. const empty = document.getElementById('bgp-nets-empty');
  8074. const countBadge = document.getElementById('bgp-nets-count-badge');
  8075. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8076. const nets = state.bgpNets || [];
  8077. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8078. if (navBadge) navBadge.innerText = nets.length;
  8079. if (nets.length === 0) {
  8080. tbody.innerHTML = '';
  8081. if (empty) empty.classList.remove('hidden');
  8082. return;
  8083. }
  8084. if (empty) empty.classList.add('hidden');
  8085. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8086. if (tbody.dataset.sig === sig) return;
  8087. tbody.dataset.sig = sig;
  8088. tbody.innerHTML = nets.map(n => `
  8089. <tr class="hover:bg-slate-800/40 transition">
  8090. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8091. <td class="py-2.5 px-3">
  8092. ${n.disabled
  8093. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8094. : '<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>'}
  8095. </td>
  8096. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8097. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8098. <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">
  8099. Delete
  8100. </button>
  8101. </td>
  8102. </tr>
  8103. `).join('');
  8104. }
  8105. function renderBgpRoutes() {
  8106. const tbody = document.getElementById('bgp-routes-table-body');
  8107. if (!tbody) return;
  8108. const empty = document.getElementById('bgp-routes-empty');
  8109. const countBadge = document.getElementById('bgp-routes-count-badge');
  8110. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8111. const routes = state.bgpRoutes || [];
  8112. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8113. if (navBadge) navBadge.innerText = routes.length;
  8114. if (routes.length === 0) {
  8115. tbody.innerHTML = '';
  8116. if (empty) empty.classList.remove('hidden');
  8117. return;
  8118. }
  8119. if (empty) empty.classList.add('hidden');
  8120. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8121. if (tbody.dataset.sig === sig) return;
  8122. tbody.dataset.sig = sig;
  8123. tbody.innerHTML = routes.map(r => `
  8124. <tr class="hover:bg-slate-800/40 transition">
  8125. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8126. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8127. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8128. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8129. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8130. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8131. </tr>
  8132. `).join('');
  8133. }
  8134. // =========================================================================
  8135. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8136. // =========================================================================
  8137. function sortOspfTable(tab, col) {
  8138. if (!state.ospfSort) state.ospfSort = {};
  8139. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8140. if (state.ospfSort[tab].col === col) {
  8141. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8142. } else {
  8143. state.ospfSort[tab].col = col;
  8144. state.ospfSort[tab].asc = true;
  8145. }
  8146. const asc = state.ospfSort[tab].asc;
  8147. let list = [];
  8148. if (tab === 'instances') list = state.ospfInstances || [];
  8149. else if (tab === 'areas') list = state.ospfAreas || [];
  8150. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8151. else if (tab === 'templates') list = state.ospfTemplates || [];
  8152. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8153. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8154. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8155. else if (tab === 'lsa') list = state.ospfLSA || [];
  8156. list.sort((a, b) => {
  8157. let valA = a[col] ?? '';
  8158. let valB = b[col] ?? '';
  8159. if (typeof valA === 'number' && typeof valB === 'number') {
  8160. return asc ? valA - valB : valB - valA;
  8161. }
  8162. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8163. });
  8164. if (tab === 'instances') renderOspfInstances();
  8165. else if (tab === 'areas') renderOspfAreas();
  8166. else if (tab === 'ranges') renderOspfAreaRanges();
  8167. else if (tab === 'templates') renderOspfTemplates();
  8168. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8169. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8170. else if (tab === 'neighbors') renderOspfNeighbors();
  8171. else if (tab === 'lsa') renderOspfLSA();
  8172. }
  8173. function selectOspfRow(tab, id) {
  8174. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8175. state.selectedOspfRow[tab] = id;
  8176. if (tab === 'instances') {
  8177. renderOspfInstances();
  8178. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8179. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8180. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8181. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8182. if (btnEn) btnEn.disabled = false;
  8183. if (btnDis) btnDis.disabled = false;
  8184. if (btnRem) btnRem.disabled = false;
  8185. if (btnCom) btnCom.disabled = false;
  8186. } else if (tab === 'areas') {
  8187. renderOspfAreas();
  8188. const btnEn = document.getElementById('btn-ospf-area-enable');
  8189. const btnDis = document.getElementById('btn-ospf-area-disable');
  8190. const btnRem = document.getElementById('btn-ospf-area-remove');
  8191. const btnCom = document.getElementById('btn-ospf-area-comment');
  8192. if (btnEn) btnEn.disabled = false;
  8193. if (btnDis) btnDis.disabled = false;
  8194. if (btnRem) btnRem.disabled = false;
  8195. if (btnCom) btnCom.disabled = false;
  8196. } else if (tab === 'ranges') {
  8197. renderOspfAreaRanges();
  8198. const btnEn = document.getElementById('btn-ospf-range-enable');
  8199. const btnDis = document.getElementById('btn-ospf-range-disable');
  8200. const btnRem = document.getElementById('btn-ospf-range-remove');
  8201. const btnCom = document.getElementById('btn-ospf-range-comment');
  8202. if (btnEn) btnEn.disabled = false;
  8203. if (btnDis) btnDis.disabled = false;
  8204. if (btnRem) btnRem.disabled = false;
  8205. if (btnCom) btnCom.disabled = false;
  8206. } else if (tab === 'templates') {
  8207. renderOspfTemplates();
  8208. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8209. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8210. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8211. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8212. if (btnEn) btnEn.disabled = false;
  8213. if (btnDis) btnDis.disabled = false;
  8214. if (btnRem) btnRem.disabled = false;
  8215. if (btnCom) btnCom.disabled = false;
  8216. } else if (tab === 'snbrs') {
  8217. renderOspfStaticNbrs();
  8218. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8219. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8220. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8221. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8222. if (btnEn) btnEn.disabled = false;
  8223. if (btnDis) btnDis.disabled = false;
  8224. if (btnRem) btnRem.disabled = false;
  8225. if (btnCom) btnCom.disabled = false;
  8226. }
  8227. }
  8228. // TAB 1: INSTANCES
  8229. function renderOspfInstances() {
  8230. const tbody = document.getElementById('ospf-instances-table-body');
  8231. if (!tbody) return;
  8232. const countEl = document.getElementById('ospf-instances-footer-count');
  8233. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8234. let list = state.ospfInstances || [];
  8235. if (filter) {
  8236. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8237. }
  8238. if (countEl) countEl.innerText = list.length;
  8239. const selId = state.selectedOspfRow?.instances;
  8240. tbody.innerHTML = list.map((inst, idx) => {
  8241. const isSel = inst.id === selId;
  8242. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8243. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8244. return `
  8245. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8246. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8247. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8248. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8249. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8250. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8251. </td>
  8252. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8253. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8254. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8255. </tr>
  8256. `;
  8257. }).join('');
  8258. }
  8259. // TAB 2: AREAS
  8260. function renderOspfAreas() {
  8261. const tbody = document.getElementById('ospf-areas-table-body');
  8262. if (!tbody) return;
  8263. const countEl = document.getElementById('ospf-areas-footer-count');
  8264. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8265. let list = state.ospfAreas || [];
  8266. if (filter) {
  8267. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8268. }
  8269. if (countEl) countEl.innerText = list.length;
  8270. const selId = state.selectedOspfRow?.areas;
  8271. tbody.innerHTML = list.map((a, idx) => {
  8272. const isSel = a.id === selId;
  8273. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8274. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8275. return `
  8276. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8277. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8278. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8279. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8280. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8281. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8282. </td>
  8283. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8284. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8285. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8286. </tr>
  8287. `;
  8288. }).join('');
  8289. }
  8290. // TAB 3: AREA RANGES
  8291. function renderOspfAreaRanges() {
  8292. const tbody = document.getElementById('ospf-ranges-table-body');
  8293. if (!tbody) return;
  8294. const countEl = document.getElementById('ospf-ranges-footer-count');
  8295. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8296. let list = state.ospfAreaRanges || [];
  8297. if (filter) {
  8298. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8299. }
  8300. if (countEl) countEl.innerText = list.length;
  8301. const selId = state.selectedOspfRow?.['area-ranges'];
  8302. tbody.innerHTML = list.map((r, idx) => {
  8303. const isSel = r.id === selId;
  8304. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8305. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8306. return `
  8307. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8308. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8309. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8310. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8311. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8312. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8313. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8314. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8315. </tr>
  8316. `;
  8317. }).join('');
  8318. }
  8319. // TAB 4: INTERFACE TEMPLATES
  8320. function renderOspfTemplates() {
  8321. const tbody = document.getElementById('ospf-templates-table-body');
  8322. if (!tbody) return;
  8323. const countEl = document.getElementById('ospf-templates-footer-count');
  8324. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8325. let list = state.ospfTemplates || [];
  8326. if (filter) {
  8327. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8328. }
  8329. if (countEl) countEl.innerText = list.length;
  8330. const selId = state.selectedOspfRow?.templates;
  8331. tbody.innerHTML = list.map((t, idx) => {
  8332. const isSel = t.id === selId;
  8333. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8334. const ifaces = t.interfaces || t.interface || 'all';
  8335. const nets = t.networks || t.network || '';
  8336. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8337. return `
  8338. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8339. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8340. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8341. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8342. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8343. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8344. </td>
  8345. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8346. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8347. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8348. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8349. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8350. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8351. </tr>
  8352. `;
  8353. }).join('');
  8354. }
  8355. // TAB 5: LIVE INTERFACES
  8356. function renderOspfLiveInterfaces() {
  8357. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8358. if (!tbody) return;
  8359. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8360. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8361. let list = state.ospfLiveInterfaces || [];
  8362. if (filter) {
  8363. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8364. }
  8365. if (countEl) countEl.innerText = list.length;
  8366. tbody.innerHTML = list.map(i => `
  8367. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8368. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8369. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8370. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8371. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8372. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8373. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8374. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8375. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8376. </tr>
  8377. `).join('');
  8378. }
  8379. // TAB 6: STATIC NEIGHBORS
  8380. function renderOspfStaticNbrs() {
  8381. const tbody = document.getElementById('ospf-snbrs-table-body');
  8382. if (!tbody) return;
  8383. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8384. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8385. let list = state.ospfStaticNbrs || [];
  8386. if (filter) {
  8387. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8388. }
  8389. if (countEl) countEl.innerText = list.length;
  8390. const selId = state.selectedOspfRow?.['static-nbrs'];
  8391. tbody.innerHTML = list.map((n, idx) => {
  8392. const isSel = n.id === selId;
  8393. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8394. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8395. return `
  8396. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8397. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8398. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8399. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8400. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8401. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8402. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8403. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8404. </tr>
  8405. `;
  8406. }).join('');
  8407. }
  8408. // TAB 7: LIVE NEIGHBORS
  8409. function renderOspfNeighbors() {
  8410. const tbody = document.getElementById('ospf-neighbors-table-body');
  8411. if (!tbody) return;
  8412. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8413. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8414. let list = state.ospfNeighbors || [];
  8415. if (filter) {
  8416. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8417. }
  8418. if (countEl) countEl.innerText = list.length;
  8419. tbody.innerHTML = list.map(n => `
  8420. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8421. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8422. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8423. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8424. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8425. </td>
  8426. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8427. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8428. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8429. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8430. </tr>
  8431. `).join('');
  8432. }
  8433. // TAB 8: LINK-STATE DATABASE (LSA)
  8434. function renderOspfLSA() {
  8435. const tbody = document.getElementById('ospf-lsa-table-body');
  8436. if (!tbody) return;
  8437. const countEl = document.getElementById('ospf-lsa-footer-count');
  8438. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8439. let list = state.ospfLSA || [];
  8440. if (filter) {
  8441. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8442. }
  8443. if (countEl) countEl.innerText = list.length;
  8444. tbody.innerHTML = list.map(l => `
  8445. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8446. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8447. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8448. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8449. </td>
  8450. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8451. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8452. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8453. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8454. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8455. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8456. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8457. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8458. </tr>
  8459. `).join('');
  8460. }
  8461. function renderOspfStatusPill() {
  8462. // Maintained for backward compatibility
  8463. const pill = document.getElementById('ospf-live-status-pill');
  8464. if (!pill) return;
  8465. 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';
  8466. pill.innerText = 'OSPF ACTIVE';
  8467. }
  8468. function renderOspfInterfaces() {
  8469. renderOspfTemplates();
  8470. }
  8471. function renderOspfRoutes() {
  8472. // Routes retained in background
  8473. }
  8474. // BGP Modals & Actions
  8475. function openBgpInstanceModal() {
  8476. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8477. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8478. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8479. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8480. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8481. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8482. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8483. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8484. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8485. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8486. }
  8487. function closeBgpInstanceModal() {
  8488. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8489. }
  8490. async function submitBgpInstance(e) {
  8491. e.preventDefault();
  8492. const payload = {
  8493. enabled: document.getElementById('modal-bgp-enabled').checked,
  8494. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8495. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8496. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8497. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8498. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8499. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8500. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8501. };
  8502. try {
  8503. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8504. method: 'POST',
  8505. headers: { 'Content-Type': 'application/json' },
  8506. body: JSON.stringify(payload)
  8507. });
  8508. if (res.ok) {
  8509. closeBgpInstanceModal();
  8510. showToast('Success', 'BGP instance configuration updated', 'success');
  8511. loadDynamicRouting();
  8512. } else {
  8513. const err = await res.json();
  8514. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8515. }
  8516. } catch (err) {
  8517. showToast('Error', err.message, 'error');
  8518. }
  8519. }
  8520. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8521. function switchBgpPeerModalTab(tab) {
  8522. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8523. tabs.forEach(t => {
  8524. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8525. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8526. if (t === tab) {
  8527. if (pane) pane.classList.remove('hidden');
  8528. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8529. } else {
  8530. if (pane) pane.classList.add('hidden');
  8531. 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';
  8532. }
  8533. });
  8534. }
  8535. function addOutputNetworkRow(val = '') {
  8536. const container = document.getElementById('modal-bgp-output-networks-container');
  8537. if (!container) return;
  8538. const row = document.createElement('div');
  8539. row.className = 'flex items-center gap-2 output-net-row';
  8540. row.innerHTML = `
  8541. <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">
  8542. <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>
  8543. `;
  8544. container.appendChild(row);
  8545. }
  8546. function parseBgpTime(val) {
  8547. if (!val) return 0;
  8548. val = String(val).trim();
  8549. if (val.includes(':')) {
  8550. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8551. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8552. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8553. }
  8554. return parseInt(val, 10) || 0;
  8555. }
  8556. function formatBgpTime(secs) {
  8557. if (!secs || secs <= 0) return '00:00:00';
  8558. const h = Math.floor(secs / 3600);
  8559. const m = Math.floor((secs % 3600) / 60);
  8560. const s = secs % 60;
  8561. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8562. }
  8563. function populateBgpRoutingTables() {
  8564. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8565. if (!sel) return;
  8566. const cur = sel.value || 'main';
  8567. sel.innerHTML = '<option value="main">main</option>';
  8568. (state.routingTables || []).forEach(t => {
  8569. if (t.name !== 'main') {
  8570. const opt = document.createElement('option');
  8571. opt.value = t.name;
  8572. opt.innerText = t.name;
  8573. sel.appendChild(opt);
  8574. }
  8575. });
  8576. sel.value = cur;
  8577. }
  8578. function openAddBgpPeerModal() {
  8579. document.getElementById('bgp-peer-form').reset();
  8580. document.getElementById('modal-bgp-peer-id').value = '';
  8581. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8582. // General Tab
  8583. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8584. document.getElementById('modal-bgp-peer-comment').value = '';
  8585. document.getElementById('modal-bgp-peer-name').value = '';
  8586. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8587. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8588. document.getElementById('modal-bgp-peer-local-as').value = '';
  8589. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8590. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8591. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8592. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8593. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8594. document.getElementById('modal-bgp-peer-router-id').value = '';
  8595. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8596. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8597. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8598. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8599. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8600. document.getElementById('modal-bgp-peer-local-port').value = '';
  8601. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8602. document.getElementById('modal-bgp-peer-password').value = '';
  8603. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8604. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8605. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8606. document.getElementById('modal-bgp-peer-connect').checked = true;
  8607. document.getElementById('modal-bgp-peer-listen').checked = true;
  8608. // Extra Tab
  8609. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8610. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8611. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8612. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8613. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8614. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8615. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8616. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8617. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8618. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8619. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8620. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8621. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8622. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8623. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8624. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8625. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8626. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8627. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8628. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8629. // Attributes Tab
  8630. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8631. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8632. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8633. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8634. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8635. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8636. // Filter Tab
  8637. populateFilterChainsDatalist();
  8638. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8639. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8640. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8641. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8642. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8643. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8644. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8645. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8646. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8647. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8648. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8649. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8650. populateBgpRoutingTables();
  8651. const container = document.getElementById('modal-bgp-output-networks-container');
  8652. if (container) {
  8653. container.innerHTML = '';
  8654. addOutputNetworkRow('');
  8655. }
  8656. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8657. if (removeBtn) removeBtn.classList.add('hidden');
  8658. switchBgpPeerModalTab('general');
  8659. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8660. }
  8661. function populateFilterChainsDatalist() {
  8662. const dl = document.getElementById('filter-chains-list');
  8663. if (!dl) return;
  8664. const chains = new Set();
  8665. (state.routingFilters || []).forEach(f => {
  8666. if (f.chain) chains.add(f.chain);
  8667. });
  8668. if (chains.size === 0) {
  8669. chains.add('awmn');
  8670. chains.add('bgp-in');
  8671. chains.add('bgp-out');
  8672. }
  8673. dl.innerHTML = '';
  8674. chains.forEach(c => {
  8675. const opt = document.createElement('option');
  8676. opt.value = c;
  8677. dl.appendChild(opt);
  8678. });
  8679. }
  8680. function openEditBgpPeerModal(id) {
  8681. const p = (state.bgpPeers || []).find(item => item.id === id);
  8682. if (!p) return;
  8683. populateBgpRoutingTables();
  8684. populateFilterChainsDatalist();
  8685. document.getElementById('modal-bgp-peer-id').value = p.id;
  8686. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8687. // General Tab
  8688. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8689. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8690. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8691. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8692. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8693. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8694. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8695. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8696. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8697. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8698. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8699. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8700. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8701. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8702. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8703. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8704. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8705. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8706. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8707. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8708. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8709. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8710. // Extra Tab
  8711. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8712. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8713. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8714. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8715. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8716. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8717. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8718. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8719. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8720. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8721. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8722. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8723. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8724. 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;
  8725. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8726. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8727. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8728. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8729. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8730. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8731. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8732. // Attributes Tab
  8733. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8734. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8735. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8736. 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;
  8737. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8738. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8739. // Filter Tab
  8740. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8741. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8742. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8743. 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 || '';
  8744. 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 || '';
  8745. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8746. 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 || '';
  8747. 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 || '';
  8748. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8749. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8750. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8751. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8752. // Output Networks
  8753. const container = document.getElementById('modal-bgp-output-networks-container');
  8754. if (container) {
  8755. container.innerHTML = '';
  8756. if (p.output_networks && p.output_networks.length > 0) {
  8757. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8758. } else {
  8759. addOutputNetworkRow('');
  8760. }
  8761. }
  8762. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8763. if (removeBtn) removeBtn.classList.remove('hidden');
  8764. switchBgpPeerModalTab('general');
  8765. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8766. }
  8767. function copyCurrentBgpPeer() {
  8768. document.getElementById('modal-bgp-peer-id').value = '';
  8769. const nameEl = document.getElementById('modal-bgp-peer-name');
  8770. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8771. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8772. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8773. if (removeBtn) removeBtn.classList.add('hidden');
  8774. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8775. }
  8776. function removeCurrentBgpPeer() {
  8777. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8778. if (!id) return;
  8779. deleteBgpPeer(id);
  8780. closeBgpPeerModal();
  8781. }
  8782. function closeBgpPeerModal() {
  8783. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8784. }
  8785. function getBgpPeerFormData() {
  8786. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8787. const outputNetworks = [];
  8788. netInputs.forEach(inp => {
  8789. const v = inp.value.trim();
  8790. if (v) outputNetworks.push(v);
  8791. });
  8792. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8793. return {
  8794. id: document.getElementById('modal-bgp-peer-id').value,
  8795. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8796. enabled: enabled,
  8797. disabled: !enabled,
  8798. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8799. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8800. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8801. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8802. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8803. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8804. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8805. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8806. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8807. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8808. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8809. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8810. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8811. password: document.getElementById('modal-bgp-peer-password').value,
  8812. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8813. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8814. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8815. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8816. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8817. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8818. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8819. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8820. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8821. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8822. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8823. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8824. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8825. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8826. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8827. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8828. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8829. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8830. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8831. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8832. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8833. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8834. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8835. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8836. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8837. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8838. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8839. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8840. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8841. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8842. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8843. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8844. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8845. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8846. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8847. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8848. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8849. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8850. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8851. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8852. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8853. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8854. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8855. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8856. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8857. output_networks: outputNetworks
  8858. };
  8859. }
  8860. async function submitBgpPeer(e) {
  8861. if (e) e.preventDefault();
  8862. const payload = getBgpPeerFormData();
  8863. try {
  8864. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8865. method: 'POST',
  8866. headers: { 'Content-Type': 'application/json' },
  8867. body: JSON.stringify(payload)
  8868. });
  8869. if (res.ok) {
  8870. closeBgpPeerModal();
  8871. showToast('Success', 'BGP Connection saved', 'success');
  8872. loadDynamicRouting();
  8873. } else {
  8874. const err = await res.json();
  8875. showToast('Error', err.error || 'Failed to save peer', 'error');
  8876. }
  8877. } catch (err) {
  8878. showToast('Error', err.message, 'error');
  8879. }
  8880. }
  8881. async function applyBgpPeerModal(e) {
  8882. if (e) e.preventDefault();
  8883. const payload = getBgpPeerFormData();
  8884. try {
  8885. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8886. method: 'POST',
  8887. headers: { 'Content-Type': 'application/json' },
  8888. body: JSON.stringify(payload)
  8889. });
  8890. if (res.ok) {
  8891. const data = await res.json();
  8892. if (data.peer && data.peer.id) {
  8893. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8894. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8895. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8896. }
  8897. showToast('Applied', 'BGP Connection applied', 'success');
  8898. loadDynamicRouting();
  8899. } else {
  8900. const err = await res.json();
  8901. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8902. }
  8903. } catch (err) {
  8904. showToast('Error', err.message, 'error');
  8905. }
  8906. }
  8907. async function deleteBgpPeer(id) {
  8908. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8909. try {
  8910. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8911. if (res.ok) {
  8912. showToast('Deleted', 'BGP peer removed', 'success');
  8913. loadDynamicRouting();
  8914. }
  8915. } catch (err) {
  8916. showToast('Error', err.message, 'error');
  8917. }
  8918. }
  8919. async function toggleBgpPeerState(id, disabled) {
  8920. try {
  8921. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8922. method: 'POST',
  8923. headers: { 'Content-Type': 'application/json' },
  8924. body: JSON.stringify({ disabled })
  8925. });
  8926. if (res.ok) {
  8927. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8928. loadDynamicRouting();
  8929. }
  8930. } catch (err) {
  8931. showToast('Error', err.message, 'error');
  8932. }
  8933. }
  8934. function openAddBgpNetworkModal() {
  8935. document.getElementById('bgp-network-form').reset();
  8936. document.getElementById('modal-bgp-net-id').value = '';
  8937. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8938. }
  8939. function closeBgpNetworkModal() {
  8940. document.getElementById('bgp-network-modal').classList.add('hidden');
  8941. }
  8942. async function submitBgpNetwork(e) {
  8943. e.preventDefault();
  8944. const payload = {
  8945. id: document.getElementById('modal-bgp-net-id').value,
  8946. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8947. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8948. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8949. };
  8950. try {
  8951. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8952. method: 'POST',
  8953. headers: { 'Content-Type': 'application/json' },
  8954. body: JSON.stringify(payload)
  8955. });
  8956. if (res.ok) {
  8957. closeBgpNetworkModal();
  8958. showToast('Success', 'BGP network advertisement saved', 'success');
  8959. loadDynamicRouting();
  8960. } else {
  8961. const err = await res.json();
  8962. showToast('Error', err.error || 'Failed to save network', 'error');
  8963. }
  8964. } catch (err) {
  8965. showToast('Error', err.message, 'error');
  8966. }
  8967. }
  8968. async function deleteBgpNetwork(id) {
  8969. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8970. try {
  8971. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8972. if (res.ok) {
  8973. showToast('Deleted', 'Network advertisement removed', 'success');
  8974. loadDynamicRouting();
  8975. }
  8976. } catch (err) {
  8977. showToast('Error', err.message, 'error');
  8978. }
  8979. }
  8980. // =========================================================================
  8981. // DEBTIK v7 OSPF MODALS & ACTIONS
  8982. // =========================================================================
  8983. // --- 1. OSPF INSTANCE ---
  8984. function openOspfInstanceModal(id = null) {
  8985. const isEdit = !!id;
  8986. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8987. id: '',
  8988. name: 'Default',
  8989. version: 2,
  8990. vrf: 'main',
  8991. router_id: '192.168.131.56',
  8992. routing_table: 'main',
  8993. enabled: true,
  8994. redistribute_connected: false,
  8995. redistribute_static: true,
  8996. redistribute_bgp: false,
  8997. comment: ''
  8998. };
  8999. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9000. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9001. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9002. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9003. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9004. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9005. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9006. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9007. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9008. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9009. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9010. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9011. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9012. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9013. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9014. }
  9015. function openEditOspfInstanceModal(id) {
  9016. openOspfInstanceModal(id);
  9017. }
  9018. function closeOspfInstanceModal() {
  9019. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9020. }
  9021. async function submitOspfInstance(e) {
  9022. if (e) e.preventDefault();
  9023. const payload = {
  9024. id: document.getElementById('modal-ospf-inst-id').value,
  9025. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9026. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9027. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9028. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9029. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9030. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9031. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9032. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9033. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9034. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9035. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9036. };
  9037. try {
  9038. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9039. method: 'POST',
  9040. headers: { 'Content-Type': 'application/json' },
  9041. body: JSON.stringify(payload)
  9042. });
  9043. if (res.ok) {
  9044. closeOspfInstanceModal();
  9045. showToast('Saved', 'OSPF instance updated', 'success');
  9046. loadDynamicRouting();
  9047. } else {
  9048. const err = await res.json();
  9049. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9050. }
  9051. } catch (err) {
  9052. showToast('Error', err.message, 'error');
  9053. }
  9054. }
  9055. function applyOspfInstanceForm() {
  9056. submitOspfInstance(null);
  9057. }
  9058. function copyOspfInstance() {
  9059. document.getElementById('modal-ospf-inst-id').value = '';
  9060. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9061. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9062. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9063. }
  9064. async function deleteCurrentOspfInstance() {
  9065. const id = document.getElementById('modal-ospf-inst-id').value;
  9066. if (!id) return;
  9067. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9068. try {
  9069. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9070. if (res.ok) {
  9071. closeOspfInstanceModal();
  9072. showToast('Removed', 'OSPF instance deleted', 'success');
  9073. loadDynamicRouting();
  9074. }
  9075. } catch (err) {
  9076. showToast('Error', err.message, 'error');
  9077. }
  9078. }
  9079. async function enableSelectedOspfInstance() {
  9080. const id = state.selectedOspfRow?.instances;
  9081. if (!id) return;
  9082. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9083. method: 'POST',
  9084. headers: { 'Content-Type': 'application/json' },
  9085. body: JSON.stringify({ disabled: false })
  9086. });
  9087. loadDynamicRouting();
  9088. }
  9089. async function disableSelectedOspfInstance() {
  9090. const id = state.selectedOspfRow?.instances;
  9091. if (!id) return;
  9092. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9093. method: 'POST',
  9094. headers: { 'Content-Type': 'application/json' },
  9095. body: JSON.stringify({ disabled: true })
  9096. });
  9097. loadDynamicRouting();
  9098. }
  9099. async function removeSelectedOspfInstance() {
  9100. const id = state.selectedOspfRow?.instances;
  9101. if (!id) return;
  9102. if (!confirm('Delete selected OSPF instance?')) return;
  9103. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9104. loadDynamicRouting();
  9105. }
  9106. async function promptCommentOspfInstance() {
  9107. const id = state.selectedOspfRow?.instances;
  9108. if (!id) return;
  9109. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9110. if (!inst) return;
  9111. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9112. if (comment === null) return;
  9113. inst.comment = comment;
  9114. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9115. method: 'POST',
  9116. headers: { 'Content-Type': 'application/json' },
  9117. body: JSON.stringify(inst)
  9118. });
  9119. loadDynamicRouting();
  9120. }
  9121. // --- 2. OSPF AREA ---
  9122. function populateOspfAreaDropdowns() {
  9123. const instSelect = document.getElementById('modal-ospf-area-instance');
  9124. if (instSelect) {
  9125. const cur = instSelect.value;
  9126. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9127. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9128. if (cur) instSelect.value = cur;
  9129. }
  9130. }
  9131. function openOspfAreaModal(id = null) {
  9132. const isEdit = !!id;
  9133. populateOspfAreaDropdowns();
  9134. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9135. id: '',
  9136. name: 'Default',
  9137. instance: 'Default',
  9138. area_id: '0.0.0.0',
  9139. area_type: 'default',
  9140. default_cost: 1,
  9141. no_summaries: false,
  9142. disabled: false,
  9143. comment: ''
  9144. };
  9145. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9146. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9147. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9148. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9149. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9150. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9151. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9152. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9153. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9154. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9155. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9156. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9157. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9158. }
  9159. function openEditOspfAreaModal(id) {
  9160. openOspfAreaModal(id);
  9161. }
  9162. function closeOspfAreaModal() {
  9163. document.getElementById('ospf-area-modal').classList.add('hidden');
  9164. }
  9165. async function submitOspfArea(e) {
  9166. if (e) e.preventDefault();
  9167. const payload = {
  9168. id: document.getElementById('modal-ospf-area-id').value,
  9169. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9170. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9171. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9172. area_type: document.getElementById('modal-ospf-area-type').value,
  9173. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9174. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9175. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9176. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9177. };
  9178. try {
  9179. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9180. method: 'POST',
  9181. headers: { 'Content-Type': 'application/json' },
  9182. body: JSON.stringify(payload)
  9183. });
  9184. if (res.ok) {
  9185. closeOspfAreaModal();
  9186. showToast('Saved', 'OSPF area saved', 'success');
  9187. loadDynamicRouting();
  9188. } else {
  9189. const err = await res.json();
  9190. showToast('Error', err.error || 'Failed to save area', 'error');
  9191. }
  9192. } catch (err) {
  9193. showToast('Error', err.message, 'error');
  9194. }
  9195. }
  9196. function applyOspfAreaForm() {
  9197. submitOspfArea(null);
  9198. }
  9199. function copyOspfArea() {
  9200. document.getElementById('modal-ospf-area-id').value = '';
  9201. document.getElementById('modal-ospf-area-name').value += '-copy';
  9202. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9203. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9204. }
  9205. async function deleteCurrentOspfArea() {
  9206. const id = document.getElementById('modal-ospf-area-id').value;
  9207. if (!id) return;
  9208. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9209. try {
  9210. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9211. if (res.ok) {
  9212. closeOspfAreaModal();
  9213. showToast('Removed', 'OSPF area deleted', 'success');
  9214. loadDynamicRouting();
  9215. }
  9216. } catch (err) {
  9217. showToast('Error', err.message, 'error');
  9218. }
  9219. }
  9220. async function enableSelectedOspfArea() {
  9221. const id = state.selectedOspfRow?.areas;
  9222. if (!id) return;
  9223. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9224. method: 'POST',
  9225. headers: { 'Content-Type': 'application/json' },
  9226. body: JSON.stringify({ disabled: false })
  9227. });
  9228. loadDynamicRouting();
  9229. }
  9230. async function disableSelectedOspfArea() {
  9231. const id = state.selectedOspfRow?.areas;
  9232. if (!id) return;
  9233. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9234. method: 'POST',
  9235. headers: { 'Content-Type': 'application/json' },
  9236. body: JSON.stringify({ disabled: true })
  9237. });
  9238. loadDynamicRouting();
  9239. }
  9240. async function removeSelectedOspfArea() {
  9241. const id = state.selectedOspfRow?.areas;
  9242. if (!id) return;
  9243. if (!confirm('Delete selected OSPF area?')) return;
  9244. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9245. loadDynamicRouting();
  9246. }
  9247. async function promptCommentOspfArea() {
  9248. const id = state.selectedOspfRow?.areas;
  9249. if (!id) return;
  9250. const area = (state.ospfAreas || []).find(a => a.id === id);
  9251. if (!area) return;
  9252. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9253. if (comment === null) return;
  9254. area.comment = comment;
  9255. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9256. method: 'POST',
  9257. headers: { 'Content-Type': 'application/json' },
  9258. body: JSON.stringify(area)
  9259. });
  9260. loadDynamicRouting();
  9261. }
  9262. // --- 3. OSPF AREA RANGE ---
  9263. function populateAreaRangeDropdowns() {
  9264. const select = document.getElementById('modal-ospf-range-area');
  9265. if (select) {
  9266. const cur = select.value;
  9267. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9268. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9269. if (cur) select.value = cur;
  9270. }
  9271. }
  9272. function openOspfAreaRangeModal(id = null) {
  9273. const isEdit = !!id;
  9274. populateAreaRangeDropdowns();
  9275. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9276. id: '',
  9277. area: 'Default',
  9278. prefix: '',
  9279. cost: 1,
  9280. advertise: true,
  9281. disabled: false,
  9282. comment: ''
  9283. };
  9284. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9285. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9286. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9287. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9288. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9289. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9290. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9291. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9292. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9293. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9294. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9295. }
  9296. function openEditOspfAreaRangeModal(id) {
  9297. openOspfAreaRangeModal(id);
  9298. }
  9299. function closeOspfAreaRangeModal() {
  9300. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9301. }
  9302. async function submitOspfAreaRange(e) {
  9303. if (e) e.preventDefault();
  9304. const payload = {
  9305. id: document.getElementById('modal-ospf-range-id').value,
  9306. area: document.getElementById('modal-ospf-range-area').value,
  9307. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9308. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9309. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9310. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9311. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9312. };
  9313. try {
  9314. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9315. method: 'POST',
  9316. headers: { 'Content-Type': 'application/json' },
  9317. body: JSON.stringify(payload)
  9318. });
  9319. if (res.ok) {
  9320. closeOspfAreaRangeModal();
  9321. showToast('Saved', 'Area range saved', 'success');
  9322. loadDynamicRouting();
  9323. } else {
  9324. const err = await res.json();
  9325. showToast('Error', err.error || 'Failed to save area range', 'error');
  9326. }
  9327. } catch (err) {
  9328. showToast('Error', err.message, 'error');
  9329. }
  9330. }
  9331. function applyOspfAreaRangeForm() {
  9332. submitOspfAreaRange(null);
  9333. }
  9334. async function deleteCurrentOspfAreaRange() {
  9335. const id = document.getElementById('modal-ospf-range-id').value;
  9336. if (!id) return;
  9337. if (!confirm('Delete this area range?')) return;
  9338. try {
  9339. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9340. closeOspfAreaRangeModal();
  9341. showToast('Removed', 'Area range removed', 'success');
  9342. loadDynamicRouting();
  9343. } catch (err) {
  9344. showToast('Error', err.message, 'error');
  9345. }
  9346. }
  9347. async function enableSelectedOspfAreaRange() {
  9348. const id = state.selectedOspfRow?.['area-ranges'];
  9349. if (!id) return;
  9350. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9351. if (!r) return;
  9352. r.disabled = false;
  9353. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9354. loadDynamicRouting();
  9355. }
  9356. async function disableSelectedOspfAreaRange() {
  9357. const id = state.selectedOspfRow?.['area-ranges'];
  9358. if (!id) return;
  9359. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9360. if (!r) return;
  9361. r.disabled = true;
  9362. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9363. loadDynamicRouting();
  9364. }
  9365. async function removeSelectedOspfAreaRange() {
  9366. const id = state.selectedOspfRow?.['area-ranges'];
  9367. if (!id) return;
  9368. if (!confirm('Delete selected area range?')) return;
  9369. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9370. loadDynamicRouting();
  9371. }
  9372. async function promptCommentOspfAreaRange() {
  9373. const id = state.selectedOspfRow?.['area-ranges'];
  9374. if (!id) return;
  9375. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9376. if (!r) return;
  9377. const comment = prompt('Enter comment for area range:', r.comment || '');
  9378. if (comment === null) return;
  9379. r.comment = comment;
  9380. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9381. loadDynamicRouting();
  9382. }
  9383. // --- 4. OSPF INTERFACE TEMPLATE ---
  9384. function switchOspfTemplateTab(tab) {
  9385. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9386. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9387. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9388. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9389. if (tab === 'general') {
  9390. if (tabGen) tabGen.classList.remove('hidden');
  9391. if (tabAuth) tabAuth.classList.add('hidden');
  9392. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9393. 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';
  9394. } else {
  9395. if (tabGen) tabGen.classList.add('hidden');
  9396. if (tabAuth) tabAuth.classList.remove('hidden');
  9397. 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';
  9398. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9399. }
  9400. }
  9401. function populateTemplateAreaDropdowns() {
  9402. const select = document.getElementById('modal-ospf-tmpl-area');
  9403. if (select) {
  9404. const cur = select.value;
  9405. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9406. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9407. if (cur) select.value = cur;
  9408. }
  9409. }
  9410. function openOspfTemplateModal(id = null) {
  9411. const isEdit = !!id;
  9412. populateTemplateAreaDropdowns();
  9413. switchOspfTemplateTab('general');
  9414. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9415. id: '',
  9416. interfaces: '',
  9417. area: 'Default',
  9418. networks: '',
  9419. network_type: 'broadcast',
  9420. cost: 1,
  9421. priority: 128,
  9422. passive: false,
  9423. hello_interval: 10,
  9424. dead_interval: 40,
  9425. auth: 'none',
  9426. auth_key: '',
  9427. disabled: false,
  9428. comment: ''
  9429. };
  9430. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9431. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9432. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9433. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9434. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9435. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9436. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9437. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9438. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9439. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9440. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9441. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9442. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9443. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9444. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9445. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9446. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9447. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9448. }
  9449. function openEditOspfTemplateModal(id) {
  9450. openOspfTemplateModal(id);
  9451. }
  9452. function closeOspfTemplateModal() {
  9453. document.getElementById('ospf-template-modal').classList.add('hidden');
  9454. }
  9455. async function submitOspfTemplate(e) {
  9456. if (e) e.preventDefault();
  9457. const payload = {
  9458. id: document.getElementById('modal-ospf-tmpl-id').value,
  9459. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9460. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9461. area: document.getElementById('modal-ospf-tmpl-area').value,
  9462. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9463. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9464. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9465. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9466. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9467. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9468. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9469. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9470. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9471. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9472. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9473. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9474. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9475. };
  9476. try {
  9477. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9478. method: 'POST',
  9479. headers: { 'Content-Type': 'application/json' },
  9480. body: JSON.stringify(payload)
  9481. });
  9482. if (res.ok) {
  9483. closeOspfTemplateModal();
  9484. showToast('Saved', 'Interface template saved', 'success');
  9485. loadDynamicRouting();
  9486. } else {
  9487. const err = await res.json();
  9488. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9489. }
  9490. } catch (err) {
  9491. showToast('Error', err.message, 'error');
  9492. }
  9493. }
  9494. function applyOspfTemplateForm() {
  9495. submitOspfTemplate(null);
  9496. }
  9497. function copyOspfTemplate() {
  9498. document.getElementById('modal-ospf-tmpl-id').value = '';
  9499. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9500. showToast('Copied', 'Duplicated as new template', 'info');
  9501. }
  9502. async function deleteCurrentOspfTemplate() {
  9503. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9504. if (!id) return;
  9505. if (!confirm('Delete this interface template?')) return;
  9506. try {
  9507. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9508. closeOspfTemplateModal();
  9509. showToast('Removed', 'Interface template deleted', 'success');
  9510. loadDynamicRouting();
  9511. } catch (err) {
  9512. showToast('Error', err.message, 'error');
  9513. }
  9514. }
  9515. async function enableSelectedOspfTemplate() {
  9516. const id = state.selectedOspfRow?.templates;
  9517. if (!id) return;
  9518. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9519. method: 'POST',
  9520. headers: { 'Content-Type': 'application/json' },
  9521. body: JSON.stringify({ disabled: false })
  9522. });
  9523. loadDynamicRouting();
  9524. }
  9525. async function disableSelectedOspfTemplate() {
  9526. const id = state.selectedOspfRow?.templates;
  9527. if (!id) return;
  9528. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9529. method: 'POST',
  9530. headers: { 'Content-Type': 'application/json' },
  9531. body: JSON.stringify({ disabled: true })
  9532. });
  9533. loadDynamicRouting();
  9534. }
  9535. async function removeSelectedOspfTemplate() {
  9536. const id = state.selectedOspfRow?.templates;
  9537. if (!id) return;
  9538. if (!confirm('Delete selected interface template?')) return;
  9539. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9540. loadDynamicRouting();
  9541. }
  9542. async function promptCommentOspfTemplate() {
  9543. const id = state.selectedOspfRow?.templates;
  9544. if (!id) return;
  9545. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9546. if (!tmpl) return;
  9547. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9548. if (comment === null) return;
  9549. tmpl.comment = comment;
  9550. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9551. method: 'POST',
  9552. headers: { 'Content-Type': 'application/json' },
  9553. body: JSON.stringify(tmpl)
  9554. });
  9555. loadDynamicRouting();
  9556. }
  9557. // --- 5. OSPF STATIC NEIGHBOR ---
  9558. function populateStaticNbrAreaDropdowns() {
  9559. const select = document.getElementById('modal-ospf-snbr-area');
  9560. if (select) {
  9561. const cur = select.value;
  9562. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9563. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9564. if (cur) select.value = cur;
  9565. }
  9566. }
  9567. function openOspfStaticNbrModal(id = null) {
  9568. const isEdit = !!id;
  9569. populateStaticNbrAreaDropdowns();
  9570. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9571. id: '',
  9572. address: '',
  9573. area: 'Default',
  9574. poll_interval: 120,
  9575. cost: 1,
  9576. disabled: false,
  9577. comment: ''
  9578. };
  9579. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9580. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9581. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9582. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9583. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9584. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9585. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9586. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9587. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9588. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9589. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9590. }
  9591. function openEditOspfStaticNbrModal(id) {
  9592. openOspfStaticNbrModal(id);
  9593. }
  9594. function closeOspfStaticNbrModal() {
  9595. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9596. }
  9597. async function submitOspfStaticNbr(e) {
  9598. if (e) e.preventDefault();
  9599. const payload = {
  9600. id: document.getElementById('modal-ospf-snbr-id').value,
  9601. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9602. area: document.getElementById('modal-ospf-snbr-area').value,
  9603. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9604. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9605. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9606. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9607. };
  9608. try {
  9609. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9610. method: 'POST',
  9611. headers: { 'Content-Type': 'application/json' },
  9612. body: JSON.stringify(payload)
  9613. });
  9614. if (res.ok) {
  9615. closeOspfStaticNbrModal();
  9616. showToast('Saved', 'Static neighbor saved', 'success');
  9617. loadDynamicRouting();
  9618. } else {
  9619. const err = await res.json();
  9620. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9621. }
  9622. } catch (err) {
  9623. showToast('Error', err.message, 'error');
  9624. }
  9625. }
  9626. function applyOspfStaticNbrForm() {
  9627. submitOspfStaticNbr(null);
  9628. }
  9629. async function deleteCurrentOspfStaticNbr() {
  9630. const id = document.getElementById('modal-ospf-snbr-id').value;
  9631. if (!id) return;
  9632. if (!confirm('Delete this static neighbor?')) return;
  9633. try {
  9634. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9635. closeOspfStaticNbrModal();
  9636. showToast('Removed', 'Static neighbor removed', 'success');
  9637. loadDynamicRouting();
  9638. } catch (err) {
  9639. showToast('Error', err.message, 'error');
  9640. }
  9641. }
  9642. async function enableSelectedOspfStaticNbr() {
  9643. const id = state.selectedOspfRow?.['static-nbrs'];
  9644. if (!id) return;
  9645. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9646. if (!n) return;
  9647. n.disabled = false;
  9648. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9649. loadDynamicRouting();
  9650. }
  9651. async function disableSelectedOspfStaticNbr() {
  9652. const id = state.selectedOspfRow?.['static-nbrs'];
  9653. if (!id) return;
  9654. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9655. if (!n) return;
  9656. n.disabled = true;
  9657. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9658. loadDynamicRouting();
  9659. }
  9660. async function removeSelectedOspfStaticNbr() {
  9661. const id = state.selectedOspfRow?.['static-nbrs'];
  9662. if (!id) return;
  9663. if (!confirm('Delete selected static neighbor?')) return;
  9664. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9665. loadDynamicRouting();
  9666. }
  9667. async function promptCommentOspfStaticNbr() {
  9668. const id = state.selectedOspfRow?.['static-nbrs'];
  9669. if (!id) return;
  9670. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9671. if (!n) return;
  9672. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9673. if (comment === null) return;
  9674. n.comment = comment;
  9675. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9676. loadDynamicRouting();
  9677. }
  9678. // Backward-compat aliases
  9679. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9680. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9681. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9682. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9683. function deleteOspfInterface(id) {
  9684. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9685. }
  9686. function toggleOspfInterfaceState(id, disabled) {
  9687. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9688. method: 'POST',
  9689. headers: { 'Content-Type': 'application/json' },
  9690. body: JSON.stringify({ disabled })
  9691. }).then(() => loadDynamicRouting());
  9692. }
  9693. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9694. function deleteOspfArea(id) {
  9695. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9696. }
  9697. // ============================================================================
  9698. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9699. // ============================================================================
  9700. function switchBridgeSubTab(tab) {
  9701. state.bridgeSubTab = tab;
  9702. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9703. tabs.forEach(t => {
  9704. const panel = document.getElementById(`bridge-subtab-${t}`);
  9705. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9706. if (panel) {
  9707. if (t === tab) panel.classList.remove('hidden');
  9708. else panel.classList.add('hidden');
  9709. }
  9710. if (btn) {
  9711. if (t === tab) {
  9712. 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';
  9713. } else {
  9714. 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';
  9715. }
  9716. }
  9717. });
  9718. const addBtn = document.getElementById('bridge-top-action-btn');
  9719. if (addBtn) {
  9720. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9721. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9722. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9723. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9724. }
  9725. if (tab === 'hosts') loadBridgeHosts();
  9726. setTimeout(initTableSorting, 50);
  9727. }
  9728. function openCurrentBridgeModal() {
  9729. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9730. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9731. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9732. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9733. }
  9734. async function loadBridge() {
  9735. try {
  9736. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9737. fetch(`${API_BASE}/bridge/bridges`),
  9738. fetch(`${API_BASE}/bridge/ports`),
  9739. fetch(`${API_BASE}/bridge/vlans`),
  9740. fetch(`${API_BASE}/bridge/summary`),
  9741. fetch(`${API_BASE}/vpn/eoip`),
  9742. fetch(`${API_BASE}/vlans`)
  9743. ]);
  9744. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9745. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9746. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9747. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9748. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9749. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9750. // Badges & Stats
  9751. const bBridges = document.getElementById('bridge-badge-bridges');
  9752. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9753. const bPorts = document.getElementById('bridge-badge-ports');
  9754. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9755. const bVlans = document.getElementById('bridge-badge-vlans');
  9756. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9757. const bHosts = document.getElementById('bridge-badge-hosts');
  9758. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9759. const sBr = document.getElementById('bridge-stat-bridges');
  9760. if (sBr) sBr.innerText = (state.bridges || []).length;
  9761. const sPorts = document.getElementById('bridge-stat-ports');
  9762. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9763. const sHosts = document.getElementById('bridge-stat-hosts');
  9764. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9765. renderBridges();
  9766. renderBridgePorts();
  9767. renderBridgeVLANs();
  9768. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9769. } catch (err) {
  9770. console.error('Failed to load bridge subsystem:', err);
  9771. }
  9772. }
  9773. // ----------------- Bridges -----------------
  9774. function renderBridges() {
  9775. const tbody = document.getElementById('bridge-table-body');
  9776. const empty = document.getElementById('bridge-empty-bridges');
  9777. const countBadge = document.getElementById('bridge-count-badge');
  9778. if (!tbody) return;
  9779. tbody.innerHTML = '';
  9780. const bridges = state.bridges || [];
  9781. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9782. if (bridges.length === 0) {
  9783. empty?.classList.remove('hidden');
  9784. return;
  9785. }
  9786. empty?.classList.add('hidden');
  9787. bridges.forEach((b, idx) => {
  9788. const tr = document.createElement('tr');
  9789. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9790. // Format IP addresses pill list
  9791. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9792. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9793. ipsHtml = b.ip_addresses.map(ip => `
  9794. <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">
  9795. <span>${ip}</span>
  9796. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9797. </span>
  9798. `).join(' ');
  9799. }
  9800. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9801. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9802. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9803. tr.innerHTML = `
  9804. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9805. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9806. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9807. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9808. </td>
  9809. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9810. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9811. <td class="py-2.5 px-3">
  9812. <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>
  9813. </td>
  9814. <td class="py-2.5 px-3 text-center">
  9815. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9816. </td>
  9817. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9818. <td class="py-2.5 px-3">
  9819. <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>
  9820. </td>
  9821. <td class="py-2.5 px-3">
  9822. <div class="flex items-center gap-1.5 flex-wrap">
  9823. ${ipsHtml}
  9824. <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>
  9825. </div>
  9826. </td>
  9827. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9828. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9829. </td>
  9830. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9831. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9832. <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>
  9833. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9834. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9835. </td>
  9836. `;
  9837. tbody.appendChild(tr);
  9838. });
  9839. }
  9840. function openAddBridgeModal() {
  9841. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9842. document.getElementById('bridge-modal-id').value = '';
  9843. document.getElementById('bridge-modal-name').value = 'bridge1';
  9844. document.getElementById('bridge-modal-name').disabled = false;
  9845. document.getElementById('bridge-modal-mtu').value = '1500';
  9846. document.getElementById('bridge-modal-mac').value = '';
  9847. document.getElementById('bridge-modal-stp').value = 'stp';
  9848. document.getElementById('bridge-modal-priority').value = '32768';
  9849. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9850. document.getElementById('bridge-modal-pvid').value = '1';
  9851. document.getElementById('bridge-modal-fastforward').checked = true;
  9852. document.getElementById('bridge-modal-comment').value = '';
  9853. document.getElementById('bridge-modal-disabled').checked = false;
  9854. toggleBridgeModalVlanFiltering();
  9855. document.getElementById('bridge-modal').classList.remove('hidden');
  9856. }
  9857. function openEditBridgeModal(id) {
  9858. const b = (state.bridges || []).find(x => x.id === id);
  9859. if (!b) return;
  9860. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9861. document.getElementById('bridge-modal-id').value = b.id;
  9862. document.getElementById('bridge-modal-name').value = b.name;
  9863. document.getElementById('bridge-modal-name').disabled = true;
  9864. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9865. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9866. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  9867. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9868. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9869. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9870. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9871. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9872. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9873. toggleBridgeModalVlanFiltering();
  9874. document.getElementById('bridge-modal').classList.remove('hidden');
  9875. }
  9876. function closeBridgeModal() {
  9877. document.getElementById('bridge-modal').classList.add('hidden');
  9878. }
  9879. function toggleBridgeModalVlanFiltering() {
  9880. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9881. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9882. if (pvidBox) {
  9883. if (chk) pvidBox.classList.remove('opacity-40');
  9884. else pvidBox.classList.add('opacity-40');
  9885. }
  9886. }
  9887. async function submitSaveBridge(e) {
  9888. e.preventDefault();
  9889. const id = document.getElementById('bridge-modal-id').value;
  9890. const name = document.getElementById('bridge-modal-name').value.trim();
  9891. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9892. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9893. const stp = document.getElementById('bridge-modal-stp').value;
  9894. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9895. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9896. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9897. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9898. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9899. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9900. try {
  9901. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9902. method: 'POST',
  9903. headers: { 'Content-Type': 'application/json' },
  9904. body: JSON.stringify({
  9905. id,
  9906. name,
  9907. mtu,
  9908. mac_address: mac,
  9909. stp,
  9910. priority,
  9911. vlan_filtering: vlanFiltering,
  9912. pvid,
  9913. fast_forward: fastForward,
  9914. comment,
  9915. disabled
  9916. })
  9917. });
  9918. if (res.ok) {
  9919. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9920. closeBridgeModal();
  9921. loadBridge();
  9922. fetchData(false);
  9923. } else {
  9924. const err = await res.json();
  9925. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9926. }
  9927. } catch (err) {
  9928. showToast('Error', err.message, 'error');
  9929. }
  9930. }
  9931. async function toggleBridgeState(id, disabled) {
  9932. try {
  9933. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9934. method: 'POST',
  9935. headers: { 'Content-Type': 'application/json' },
  9936. body: JSON.stringify({ disabled })
  9937. });
  9938. if (res.ok) {
  9939. loadBridge();
  9940. fetchData(false);
  9941. }
  9942. } catch (err) {
  9943. showToast('Error', err.message, 'error');
  9944. }
  9945. }
  9946. async function deleteBridge(id) {
  9947. const b = (state.bridges || []).find(x => x.id === id);
  9948. const name = b ? b.name : id;
  9949. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9950. try {
  9951. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9952. if (res.ok) {
  9953. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9954. loadBridge();
  9955. fetchData(false);
  9956. } else {
  9957. const err = await res.json();
  9958. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9959. }
  9960. } catch (err) {
  9961. showToast('Error', err.message, 'error');
  9962. }
  9963. }
  9964. // ----------------- Bridge IP Assignments -----------------
  9965. function openAddBridgeIPModal(id, name) {
  9966. document.getElementById('bridge-ip-modal-id').value = id;
  9967. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9968. document.getElementById('bridge-ip-modal-cidr').value = '';
  9969. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9970. }
  9971. function closeBridgeIPModal() {
  9972. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9973. }
  9974. async function submitAddBridgeIP(e) {
  9975. e.preventDefault();
  9976. const id = document.getElementById('bridge-ip-modal-id').value;
  9977. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9978. try {
  9979. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9980. method: 'POST',
  9981. headers: { 'Content-Type': 'application/json' },
  9982. body: JSON.stringify({ ip })
  9983. });
  9984. if (res.ok) {
  9985. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9986. closeBridgeIPModal();
  9987. loadBridge();
  9988. fetchData(false);
  9989. } else {
  9990. const err = await res.json();
  9991. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9992. }
  9993. } catch (err) {
  9994. showToast('Error', err.message, 'error');
  9995. }
  9996. }
  9997. async function deleteBridgeIP(id, ip) {
  9998. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9999. try {
  10000. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10001. method: 'DELETE',
  10002. headers: { 'Content-Type': 'application/json' },
  10003. body: JSON.stringify({ ip })
  10004. });
  10005. if (res.ok) {
  10006. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10007. loadBridge();
  10008. fetchData(false);
  10009. }
  10010. } catch (err) {
  10011. showToast('Error', err.message, 'error');
  10012. }
  10013. }
  10014. // ----------------- Bridge Ports -----------------
  10015. function renderBridgePorts() {
  10016. const tbody = document.getElementById('bridge-ports-table-body');
  10017. const empty = document.getElementById('bridge-empty-ports');
  10018. const countBadge = document.getElementById('bridge-ports-count-badge');
  10019. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10020. if (!tbody) return;
  10021. tbody.innerHTML = '';
  10022. // Update filter select
  10023. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10024. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10025. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10026. if (ports.length === 0) {
  10027. empty?.classList.remove('hidden');
  10028. return;
  10029. }
  10030. empty?.classList.add('hidden');
  10031. ports.forEach((p, idx) => {
  10032. const tr = document.createElement('tr');
  10033. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10034. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10035. tr.innerHTML = `
  10036. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10037. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10038. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10039. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10040. </td>
  10041. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10042. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10043. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10044. <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>
  10045. <td class="py-2.5 px-3">
  10046. ${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>'}
  10047. </td>
  10048. <td class="py-2.5 px-3">
  10049. <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>
  10050. </td>
  10051. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10052. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10053. <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>
  10054. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10055. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10056. </td>
  10057. `;
  10058. tbody.appendChild(tr);
  10059. });
  10060. }
  10061. function openAddBridgePortModal() {
  10062. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10063. document.getElementById('bridge-port-modal-id').value = '';
  10064. populateBridgeSelect('bridge-port-modal-bridge');
  10065. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10066. document.getElementById('bridge-port-modal-pvid').value = '1';
  10067. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10068. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10069. document.getElementById('bridge-port-modal-horizon').value = '0';
  10070. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10071. document.getElementById('bridge-port-modal-priority').value = '128';
  10072. document.getElementById('bridge-port-modal-learn').checked = true;
  10073. document.getElementById('bridge-port-modal-comment').value = '';
  10074. document.getElementById('bridge-port-modal-disabled').checked = false;
  10075. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10076. }
  10077. function openEditBridgePortModal(id) {
  10078. const p = (state.bridgePorts || []).find(x => x.id === id);
  10079. if (!p) return;
  10080. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10081. document.getElementById('bridge-port-modal-id').value = p.id;
  10082. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10083. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10084. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10085. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10086. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10087. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10088. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10089. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10090. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10091. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10092. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10093. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10094. }
  10095. function closeBridgePortModal() {
  10096. document.getElementById('bridge-port-modal').classList.add('hidden');
  10097. }
  10098. async function submitSaveBridgePort(e) {
  10099. e.preventDefault();
  10100. const id = document.getElementById('bridge-port-modal-id').value;
  10101. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10102. const iface = document.getElementById('bridge-port-modal-interface').value;
  10103. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10104. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10105. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10106. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10107. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10108. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10109. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10110. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10111. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10112. try {
  10113. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10114. method: 'POST',
  10115. headers: { 'Content-Type': 'application/json' },
  10116. body: JSON.stringify({
  10117. id,
  10118. bridge,
  10119. interface: iface,
  10120. pvid,
  10121. frame_types: frameTypes,
  10122. ingress_filtering: ingressFiltering,
  10123. horizon,
  10124. path_cost: pathCost,
  10125. priority,
  10126. learn,
  10127. comment,
  10128. disabled
  10129. })
  10130. });
  10131. if (res.ok) {
  10132. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10133. closeBridgePortModal();
  10134. loadBridge();
  10135. fetchData(false);
  10136. } else {
  10137. const err = await res.json();
  10138. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10139. }
  10140. } catch (err) {
  10141. showToast('Error', err.message, 'error');
  10142. }
  10143. }
  10144. async function toggleBridgePortState(id, disabled) {
  10145. try {
  10146. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10147. method: 'POST',
  10148. headers: { 'Content-Type': 'application/json' },
  10149. body: JSON.stringify({ disabled })
  10150. });
  10151. if (res.ok) {
  10152. loadBridge();
  10153. fetchData(false);
  10154. }
  10155. } catch (err) {
  10156. showToast('Error', err.message, 'error');
  10157. }
  10158. }
  10159. async function deleteBridgePort(id) {
  10160. const p = (state.bridgePorts || []).find(x => x.id === id);
  10161. const iface = p ? p.interface : id;
  10162. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10163. try {
  10164. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10165. if (res.ok) {
  10166. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10167. loadBridge();
  10168. fetchData(false);
  10169. }
  10170. } catch (err) {
  10171. showToast('Error', err.message, 'error');
  10172. }
  10173. }
  10174. // ----------------- Bridge VLANs -----------------
  10175. function renderBridgeVLANs() {
  10176. const tbody = document.getElementById('bridge-vlans-table-body');
  10177. const empty = document.getElementById('bridge-empty-vlans');
  10178. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10179. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10180. if (!tbody) return;
  10181. tbody.innerHTML = '';
  10182. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10183. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10184. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10185. if (vlans.length === 0) {
  10186. empty?.classList.remove('hidden');
  10187. return;
  10188. }
  10189. empty?.classList.add('hidden');
  10190. vlans.forEach((v, idx) => {
  10191. const tr = document.createElement('tr');
  10192. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10193. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10194. ? 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(' ')
  10195. : '<span class="text-slate-600">none</span>';
  10196. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10197. ? 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(' ')
  10198. : '<span class="text-slate-600">none</span>';
  10199. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10200. tr.innerHTML = `
  10201. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10202. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10203. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10204. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10205. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10206. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10207. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10208. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10209. <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>
  10210. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10211. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10212. </td>
  10213. `;
  10214. tbody.appendChild(tr);
  10215. });
  10216. }
  10217. function openAddBridgeVLANModal() {
  10218. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10219. document.getElementById('bridge-vlan-modal-id').value = '';
  10220. populateBridgeSelect('bridge-vlan-modal-bridge');
  10221. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10222. document.getElementById('bridge-vlan-modal-comment').value = '';
  10223. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10224. updateBridgeVlanPortCheckboxes();
  10225. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10226. }
  10227. function openEditBridgeVLANModal(id) {
  10228. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10229. if (!v) return;
  10230. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10231. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10232. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10233. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10234. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10235. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10236. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10237. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10238. }
  10239. function closeBridgeVlanModal() {
  10240. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10241. }
  10242. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10243. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10244. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10245. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10246. if (!taggedBox || !untaggedBox) return;
  10247. // Ports belonging to the selected bridge
  10248. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10249. if (memberPorts.length === 0) {
  10250. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10251. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10252. return;
  10253. }
  10254. taggedBox.innerHTML = memberPorts.map(p => `
  10255. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10256. <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">
  10257. <span>${p.interface}</span>
  10258. </label>
  10259. `).join('');
  10260. untaggedBox.innerHTML = memberPorts.map(p => `
  10261. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10262. <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">
  10263. <span>${p.interface}</span>
  10264. </label>
  10265. `).join('');
  10266. }
  10267. async function submitSaveBridgeVLAN(e) {
  10268. e.preventDefault();
  10269. const id = document.getElementById('bridge-vlan-modal-id').value;
  10270. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10271. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10272. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10273. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10274. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10275. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10276. try {
  10277. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10278. method: 'POST',
  10279. headers: { 'Content-Type': 'application/json' },
  10280. body: JSON.stringify({
  10281. id,
  10282. bridge,
  10283. vlan_ids: vlanIDs,
  10284. tagged,
  10285. untagged,
  10286. comment,
  10287. disabled
  10288. })
  10289. });
  10290. if (res.ok) {
  10291. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10292. closeBridgeVlanModal();
  10293. loadBridge();
  10294. } else {
  10295. const err = await res.json();
  10296. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10297. }
  10298. } catch (err) {
  10299. showToast('Error', err.message, 'error');
  10300. }
  10301. }
  10302. async function toggleBridgeVLANState(id, disabled) {
  10303. try {
  10304. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10305. method: 'POST',
  10306. headers: { 'Content-Type': 'application/json' },
  10307. body: JSON.stringify({ disabled })
  10308. });
  10309. if (res.ok) loadBridge();
  10310. } catch (err) {
  10311. showToast('Error', err.message, 'error');
  10312. }
  10313. }
  10314. async function deleteBridgeVLAN(id) {
  10315. if (!confirm('Delete this bridge VLAN entry?')) return;
  10316. try {
  10317. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10318. if (res.ok) {
  10319. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10320. loadBridge();
  10321. }
  10322. } catch (err) {
  10323. showToast('Error', err.message, 'error');
  10324. }
  10325. }
  10326. // ----------------- Hosts / MAC Table -----------------
  10327. async function loadBridgeHosts() {
  10328. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10329. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10330. try {
  10331. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10332. const res = await fetch(url);
  10333. if (res.ok) {
  10334. state.bridgeHosts = await res.json();
  10335. renderBridgeHosts();
  10336. }
  10337. } catch (err) {
  10338. console.error('Failed to load bridge hosts:', err);
  10339. }
  10340. }
  10341. function renderBridgeHosts() {
  10342. const tbody = document.getElementById('bridge-hosts-table-body');
  10343. const empty = document.getElementById('bridge-empty-hosts');
  10344. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10345. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10346. if (!tbody) return;
  10347. tbody.innerHTML = '';
  10348. const hosts = (state.bridgeHosts || []).filter(h => {
  10349. if (!search) return true;
  10350. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10351. });
  10352. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10353. if (hosts.length === 0) {
  10354. empty?.classList.remove('hidden');
  10355. return;
  10356. }
  10357. empty?.classList.add('hidden');
  10358. hosts.forEach(h => {
  10359. const tr = document.createElement('tr');
  10360. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10361. let flagBadges = '';
  10362. 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>';
  10363. 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>';
  10364. 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>';
  10365. tr.innerHTML = `
  10366. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10367. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10368. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10369. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10370. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10371. <td class="py-2.5 px-3">${flagBadges}</td>
  10372. `;
  10373. tbody.appendChild(tr);
  10374. });
  10375. }
  10376. async function flushBridgeHosts() {
  10377. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10378. if (!selBridge) {
  10379. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10380. return;
  10381. }
  10382. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10383. try {
  10384. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10385. method: 'POST',
  10386. headers: { 'Content-Type': 'application/json' },
  10387. body: JSON.stringify({ bridge: selBridge })
  10388. });
  10389. if (res.ok) {
  10390. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10391. loadBridgeHosts();
  10392. }
  10393. } catch (err) {
  10394. showToast('Error', err.message, 'error');
  10395. }
  10396. }
  10397. // ----------------- Helpers -----------------
  10398. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10399. const sel = document.getElementById(selectId);
  10400. if (!sel) return;
  10401. const prevVal = currentVal || sel.value;
  10402. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10403. (state.bridges || []).forEach(b => {
  10404. const opt = document.createElement('option');
  10405. opt.value = b.name;
  10406. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10407. if (b.name === prevVal) opt.selected = true;
  10408. sel.appendChild(opt);
  10409. });
  10410. }
  10411. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10412. const sel = document.getElementById(selectId);
  10413. if (!sel) return;
  10414. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10415. // 1. Physical Interfaces
  10416. const grpPhys = document.createElement('optgroup');
  10417. grpPhys.label = 'Physical Interfaces';
  10418. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10419. const opt = document.createElement('option');
  10420. opt.value = i.name;
  10421. opt.innerText = `${i.name} (${i.role || i.type})`;
  10422. if (i.name === currentVal) opt.selected = true;
  10423. grpPhys.appendChild(opt);
  10424. });
  10425. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10426. // 2. VLAN Sub-interfaces
  10427. const grpVlans = document.createElement('optgroup');
  10428. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10429. (state.vlans || []).forEach(v => {
  10430. const opt = document.createElement('option');
  10431. opt.value = v.name;
  10432. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10433. if (v.name === currentVal) opt.selected = true;
  10434. grpVlans.appendChild(opt);
  10435. });
  10436. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10437. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10438. const grpEoip = document.createElement('optgroup');
  10439. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10440. (state.eoipTunnels || []).forEach(t => {
  10441. const opt = document.createElement('option');
  10442. opt.value = t.name;
  10443. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10444. if (t.name === currentVal) opt.selected = true;
  10445. grpEoip.appendChild(opt);
  10446. });
  10447. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10448. }
  10449. // -------------------------------------------------------------
  10450. // DebTik Routing Filters Management (/routing filter)
  10451. // -------------------------------------------------------------
  10452. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10453. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10454. if (!state.rfSort) state.rfSort = {};
  10455. function switchRoutingFilterTab(tab) {
  10456. state.activeRoutingFilterTab = tab;
  10457. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10458. tabs.forEach(t => {
  10459. const btn = document.getElementById(`tab-rf-${t}`);
  10460. const content = document.getElementById(`tab-content-rf-${t}`);
  10461. if (btn) {
  10462. if (t === tab) {
  10463. 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';
  10464. } else {
  10465. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10466. }
  10467. }
  10468. if (content) {
  10469. if (t === tab) content.classList.remove('hidden');
  10470. else content.classList.add('hidden');
  10471. }
  10472. });
  10473. const chainContainer = document.getElementById('rf-chain-filter-container');
  10474. if (chainContainer) {
  10475. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10476. else chainContainer.classList.add('hidden');
  10477. }
  10478. renderRoutingFilters();
  10479. }
  10480. function selectFilterRow(tab, id) {
  10481. if (state.selectedFilterRow[tab] === id) {
  10482. delete state.selectedFilterRow[tab];
  10483. } else {
  10484. state.selectedFilterRow[tab] = id;
  10485. }
  10486. if (tab === 'rules') renderRoutingFilterRules();
  10487. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10488. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10489. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10490. }
  10491. function openRoutingFilterNewModal() {
  10492. const tab = state.activeRoutingFilterTab || 'rules';
  10493. if (tab === 'rules') openAddRoutingFilterModal();
  10494. else if (tab === 'select-rules') openAddSelectRuleModal();
  10495. else if (tab === 'community-lists') openAddCommunityListModal();
  10496. else if (tab === 'as-lists') openAddASListModal();
  10497. }
  10498. function toggleSelectedRoutingFilter(disabled) {
  10499. const tab = state.activeRoutingFilterTab || 'rules';
  10500. const id = state.selectedFilterRow[tab];
  10501. if (!id) {
  10502. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10503. return;
  10504. }
  10505. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10506. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10507. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10508. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10509. }
  10510. function removeSelectedRoutingFilter() {
  10511. const tab = state.activeRoutingFilterTab || 'rules';
  10512. const id = state.selectedFilterRow[tab];
  10513. if (!id) {
  10514. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10515. return;
  10516. }
  10517. if (tab === 'rules') deleteRoutingFilter(id);
  10518. else if (tab === 'select-rules') deleteSelectRule(id);
  10519. else if (tab === 'community-lists') deleteCommunityList(id);
  10520. else if (tab === 'as-lists') deleteASList(id);
  10521. }
  10522. function searchRoutingFilters(q) {
  10523. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10524. renderRoutingFilters();
  10525. }
  10526. function sortFilterTable(tab, col) {
  10527. if (!state.rfSort) state.rfSort = {};
  10528. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10529. if (state.rfSort[tab].col === col) {
  10530. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10531. } else {
  10532. state.rfSort[tab].col = col;
  10533. state.rfSort[tab].asc = true;
  10534. }
  10535. const asc = state.rfSort[tab].asc;
  10536. let list = [];
  10537. if (tab === 'rules') list = state.routingFilters || [];
  10538. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10539. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10540. else if (tab === 'as-lists') list = state.routingASLists || [];
  10541. list.sort((a, b) => {
  10542. let valA = a[col] ?? '';
  10543. let valB = b[col] ?? '';
  10544. if (col === 'flags') {
  10545. valA = a.disabled ? 'X' : 'A';
  10546. valB = b.disabled ? 'X' : 'A';
  10547. }
  10548. if (typeof valA === 'number' && typeof valB === 'number') {
  10549. return asc ? valA - valB : valB - valA;
  10550. }
  10551. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10552. });
  10553. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10554. allCols.forEach(c => {
  10555. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10556. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10557. });
  10558. if (tab === 'rules') renderRoutingFilterRules();
  10559. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10560. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10561. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10562. }
  10563. function renderRoutingFilters() {
  10564. const navBadge = document.getElementById('badge-filters-count');
  10565. const allRules = state.routingFilters || [];
  10566. if (navBadge) navBadge.innerText = allRules.length;
  10567. // Populate chain filter select options and datalist
  10568. const chainSelect = document.getElementById('routing-filter-chain-select');
  10569. const chainDatalist = document.getElementById('dl-routing-chains');
  10570. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10571. if (chainSelect) {
  10572. const currentVal = state.filterChainSelected || 'all';
  10573. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10574. uniqueChains.map(ch => {
  10575. const count = allRules.filter(r => r.chain === ch).length;
  10576. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10577. }).join('');
  10578. chainSelect.value = currentVal;
  10579. }
  10580. if (chainDatalist) {
  10581. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10582. }
  10583. renderRoutingFilterRules();
  10584. renderRoutingFilterSelectRules();
  10585. renderRoutingFilterCommunityLists();
  10586. renderRoutingFilterASLists();
  10587. }
  10588. function filterRoutingFiltersByChain(chain) {
  10589. state.filterChainSelected = chain;
  10590. renderRoutingFilters();
  10591. }
  10592. // -------------------------------------------------------------
  10593. // TAB 1: RULES (/routing filter rule)
  10594. // -------------------------------------------------------------
  10595. function renderRoutingFilterRules() {
  10596. const tbody = document.getElementById('routing-filter-rules-tbody');
  10597. if (!tbody) return;
  10598. const empty = document.getElementById('rf-rules-empty');
  10599. const statusCount = document.getElementById('rf-status-count');
  10600. let list = (state.routingFilters || []).slice();
  10601. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10602. list = list.filter(r => r.chain === state.filterChainSelected);
  10603. }
  10604. const q = state.rfSearchQuery;
  10605. if (q) {
  10606. list = list.filter(r =>
  10607. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10608. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10609. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10610. (r.comment && r.comment.toLowerCase().includes(q))
  10611. );
  10612. }
  10613. if (!state.rfSort?.['rules']) {
  10614. list.sort((a, b) => {
  10615. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10616. return (a.rule_order || 0) - (b.rule_order || 0);
  10617. });
  10618. }
  10619. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10620. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10621. }
  10622. if (list.length === 0) {
  10623. tbody.innerHTML = '';
  10624. if (empty) empty.classList.remove('hidden');
  10625. return;
  10626. }
  10627. if (empty) empty.classList.add('hidden');
  10628. tbody.innerHTML = list.map(r => {
  10629. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10630. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10631. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10632. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10633. let ruleDisplay = '';
  10634. if (r.rule && r.rule.trim() !== '') {
  10635. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10636. } else {
  10637. let conds = [];
  10638. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10639. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10640. let act = r.action || 'accept';
  10641. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10642. }
  10643. return `
  10644. <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'}">
  10645. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10646. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10647. <td class="py-2 px-3">
  10648. <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>
  10649. </td>
  10650. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10651. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10652. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10653. <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>
  10654. <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>
  10655. <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'}">
  10656. ${r.disabled ? 'Enable' : 'Disable'}
  10657. </button>
  10658. <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">
  10659. Edit
  10660. </button>
  10661. <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">
  10662. ✕
  10663. </button>
  10664. </td>
  10665. </tr>
  10666. `;
  10667. }).join('');
  10668. }
  10669. // -------------------------------------------------------------
  10670. // TAB 2: SELECT RULES (/routing filter select-rule)
  10671. // -------------------------------------------------------------
  10672. function renderRoutingFilterSelectRules() {
  10673. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10674. if (!tbody) return;
  10675. const empty = document.getElementById('rf-select-rules-empty');
  10676. const statusCount = document.getElementById('rf-status-count');
  10677. let list = (state.routingSelectRules || []).slice();
  10678. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10679. list = list.filter(r => r.chain === state.filterChainSelected);
  10680. }
  10681. const q = state.rfSearchQuery;
  10682. if (q) {
  10683. list = list.filter(r =>
  10684. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10685. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10686. (r.comment && r.comment.toLowerCase().includes(q))
  10687. );
  10688. }
  10689. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10690. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10691. }
  10692. if (list.length === 0) {
  10693. tbody.innerHTML = '';
  10694. if (empty) empty.classList.remove('hidden');
  10695. return;
  10696. }
  10697. if (empty) empty.classList.add('hidden');
  10698. tbody.innerHTML = list.map(r => {
  10699. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10700. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10701. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10702. return `
  10703. <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'}">
  10704. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10705. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10706. <td class="py-2 px-3">
  10707. <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>
  10708. </td>
  10709. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10710. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10711. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10712. <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'}">
  10713. ${r.disabled ? 'Enable' : 'Disable'}
  10714. </button>
  10715. <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">
  10716. Edit
  10717. </button>
  10718. <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">
  10719. ✕
  10720. </button>
  10721. </td>
  10722. </tr>
  10723. `;
  10724. }).join('');
  10725. }
  10726. // -------------------------------------------------------------
  10727. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10728. // -------------------------------------------------------------
  10729. function renderRoutingFilterCommunityLists() {
  10730. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10731. if (!tbody) return;
  10732. const empty = document.getElementById('rf-comm-lists-empty');
  10733. const statusCount = document.getElementById('rf-status-count');
  10734. let list = (state.routingCommunityLists || []).slice();
  10735. const q = state.rfSearchQuery;
  10736. if (q) {
  10737. list = list.filter(cl =>
  10738. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10739. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10740. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10741. );
  10742. }
  10743. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10744. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10745. }
  10746. if (list.length === 0) {
  10747. tbody.innerHTML = '';
  10748. if (empty) empty.classList.remove('hidden');
  10749. return;
  10750. }
  10751. if (empty) empty.classList.add('hidden');
  10752. tbody.innerHTML = list.map(cl => {
  10753. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10754. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10755. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10756. const commBadges = (cl.communities || []).map(c =>
  10757. `<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>`
  10758. ).join(' ');
  10759. return `
  10760. <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'}">
  10761. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10762. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10763. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10764. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10765. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10766. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10767. <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'}">
  10768. ${cl.disabled ? 'Enable' : 'Disable'}
  10769. </button>
  10770. <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">
  10771. Edit
  10772. </button>
  10773. <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">
  10774. ✕
  10775. </button>
  10776. </td>
  10777. </tr>
  10778. `;
  10779. }).join('');
  10780. }
  10781. // -------------------------------------------------------------
  10782. // TAB 4: AS LISTS (/routing filter num-list)
  10783. // -------------------------------------------------------------
  10784. function renderRoutingFilterASLists() {
  10785. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10786. if (!tbody) return;
  10787. const empty = document.getElementById('rf-as-lists-empty');
  10788. const statusCount = document.getElementById('rf-status-count');
  10789. let list = (state.routingASLists || []).slice();
  10790. const q = state.rfSearchQuery;
  10791. if (q) {
  10792. list = list.filter(al =>
  10793. (al.name && al.name.toLowerCase().includes(q)) ||
  10794. (al.range && al.range.toLowerCase().includes(q)) ||
  10795. (al.comment && al.comment.toLowerCase().includes(q))
  10796. );
  10797. }
  10798. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10799. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10800. }
  10801. if (list.length === 0) {
  10802. tbody.innerHTML = '';
  10803. if (empty) empty.classList.remove('hidden');
  10804. return;
  10805. }
  10806. if (empty) empty.classList.add('hidden');
  10807. tbody.innerHTML = list.map(al => {
  10808. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10809. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10810. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10811. return `
  10812. <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'}">
  10813. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10814. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10815. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10816. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10817. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10818. <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'}">
  10819. ${al.disabled ? 'Enable' : 'Disable'}
  10820. </button>
  10821. <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">
  10822. Edit
  10823. </button>
  10824. <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">
  10825. ✕
  10826. </button>
  10827. </td>
  10828. </tr>
  10829. `;
  10830. }).join('');
  10831. }
  10832. // -------------------------------------------------------------
  10833. // SNIPPETS & WIZARD HELPERS
  10834. // -------------------------------------------------------------
  10835. function insertRuleSnippet(type) {
  10836. const textarea = document.getElementById('modal-rf-rule');
  10837. if (!textarea) return;
  10838. let snippet = '';
  10839. switch (type) {
  10840. case 'accept-default':
  10841. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10842. break;
  10843. case 'drop-rfc1918':
  10844. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10845. break;
  10846. case 'len-24':
  10847. snippet = 'if (dst-len > 24) { reject; }';
  10848. break;
  10849. case 'local-pref-150':
  10850. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10851. break;
  10852. case 'as-prepend-2':
  10853. snippet = 'set bgp-path-prepend 2; accept;';
  10854. break;
  10855. case 'set-comm':
  10856. snippet = 'set bgp-communities.add 65000:100; accept;';
  10857. break;
  10858. case 'match-comm':
  10859. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10860. break;
  10861. case 'reject-all':
  10862. snippet = 'reject;';
  10863. break;
  10864. }
  10865. if (!snippet) return;
  10866. if (!textarea.value.trim()) {
  10867. textarea.value = snippet;
  10868. } else {
  10869. textarea.value = textarea.value.trim() + '\n' + snippet;
  10870. }
  10871. }
  10872. function generateScriptFromWizard() {
  10873. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10874. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10875. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10876. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10877. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10878. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10879. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10880. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10881. const conds = [];
  10882. if (pfx) {
  10883. if (pfxLen) {
  10884. if (pfxLen.includes('-')) {
  10885. const parts = pfxLen.split('-');
  10886. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10887. } else {
  10888. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10889. }
  10890. } else {
  10891. conds.push(`dst in ${pfx}`);
  10892. }
  10893. }
  10894. if (proto && proto !== 'any') {
  10895. conds.push(`protocol ${proto}`);
  10896. }
  10897. if (asp) {
  10898. conds.push(`bgp-as-path "${asp}"`);
  10899. }
  10900. if (comm) {
  10901. conds.push(`bgp-communities includes ${comm}`);
  10902. }
  10903. const actions = [];
  10904. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10905. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10906. actions.push(`${act};`);
  10907. let code = '';
  10908. if (conds.length > 0) {
  10909. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10910. } else {
  10911. code = actions.join(' ');
  10912. }
  10913. const textarea = document.getElementById('modal-rf-rule');
  10914. if (textarea) textarea.value = code;
  10915. }
  10916. // -------------------------------------------------------------
  10917. // MODAL CRUD: RULES (/routing filter rule)
  10918. // -------------------------------------------------------------
  10919. function openAddRoutingFilterModal(defaultChain = '') {
  10920. const form = document.getElementById('routing-filter-form');
  10921. if (form) form.reset();
  10922. const idEl = document.getElementById('modal-rf-id');
  10923. if (idEl) idEl.value = '';
  10924. const titleEl = document.getElementById('modal-rf-title');
  10925. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10926. const chainEl = document.getElementById('modal-rf-chain');
  10927. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10928. const orderEl = document.getElementById('modal-rf-order');
  10929. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10930. const ruleEl = document.getElementById('modal-rf-rule');
  10931. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10932. const disEl = document.getElementById('modal-rf-disabled');
  10933. if (disEl) disEl.checked = false;
  10934. const modal = document.getElementById('modal-routing-filter');
  10935. if (modal) modal.classList.remove('hidden');
  10936. }
  10937. function openEditRoutingFilterModal(id) {
  10938. const r = (state.routingFilters || []).find(item => item.id === id);
  10939. if (!r) return;
  10940. const idEl = document.getElementById('modal-rf-id');
  10941. if (idEl) idEl.value = r.id;
  10942. const titleEl = document.getElementById('modal-rf-title');
  10943. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10944. const chainEl = document.getElementById('modal-rf-chain');
  10945. if (chainEl) chainEl.value = r.chain || '';
  10946. const orderEl = document.getElementById('modal-rf-order');
  10947. if (orderEl) orderEl.value = r.rule_order || 10;
  10948. const ruleEl = document.getElementById('modal-rf-rule');
  10949. if (ruleEl) {
  10950. if (r.rule) {
  10951. ruleEl.value = r.rule;
  10952. } else {
  10953. let conds = [];
  10954. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10955. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10956. let act = r.action || 'accept';
  10957. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10958. }
  10959. }
  10960. const comEl = document.getElementById('modal-rf-comment');
  10961. if (comEl) comEl.value = r.comment || '';
  10962. const disEl = document.getElementById('modal-rf-disabled');
  10963. if (disEl) disEl.checked = !!r.disabled;
  10964. const modal = document.getElementById('modal-routing-filter');
  10965. if (modal) modal.classList.remove('hidden');
  10966. }
  10967. function closeRoutingFilterModal() {
  10968. const modal = document.getElementById('modal-routing-filter');
  10969. if (modal) modal.classList.add('hidden');
  10970. }
  10971. async function submitRoutingFilter(e) {
  10972. if (e) e.preventDefault();
  10973. const payload = {
  10974. id: document.getElementById('modal-rf-id').value,
  10975. chain: document.getElementById('modal-rf-chain').value.trim(),
  10976. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10977. rule: document.getElementById('modal-rf-rule').value.trim(),
  10978. comment: document.getElementById('modal-rf-comment').value.trim(),
  10979. disabled: document.getElementById('modal-rf-disabled').checked
  10980. };
  10981. try {
  10982. const res = await fetch(`${API_BASE}/routing/filters`, {
  10983. method: 'POST',
  10984. headers: { 'Content-Type': 'application/json' },
  10985. body: JSON.stringify(payload)
  10986. });
  10987. if (res.ok) {
  10988. closeRoutingFilterModal();
  10989. showToast('Success', 'Routing filter rule saved', 'success');
  10990. loadDynamicRouting();
  10991. } else {
  10992. const err = await res.json();
  10993. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10994. }
  10995. } catch (err) {
  10996. showToast('Error', err.message, 'error');
  10997. }
  10998. }
  10999. async function applyRoutingFilterForm() {
  11000. const payload = {
  11001. id: document.getElementById('modal-rf-id').value,
  11002. chain: document.getElementById('modal-rf-chain').value.trim(),
  11003. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11004. rule: document.getElementById('modal-rf-rule').value.trim(),
  11005. comment: document.getElementById('modal-rf-comment').value.trim(),
  11006. disabled: document.getElementById('modal-rf-disabled').checked
  11007. };
  11008. try {
  11009. const res = await fetch(`${API_BASE}/routing/filters`, {
  11010. method: 'POST',
  11011. headers: { 'Content-Type': 'application/json' },
  11012. body: JSON.stringify(payload)
  11013. });
  11014. if (res.ok) {
  11015. const data = await res.json();
  11016. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11017. showToast('Applied', 'Routing filter configuration applied', 'success');
  11018. loadDynamicRouting();
  11019. } else {
  11020. const err = await res.json();
  11021. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11022. }
  11023. } catch (err) {
  11024. showToast('Error', err.message, 'error');
  11025. }
  11026. }
  11027. async function moveRoutingFilterOrder(id, delta) {
  11028. const list = state.routingFilters || [];
  11029. const idx = list.findIndex(r => r.id === id);
  11030. if (idx < 0) return;
  11031. const targetIdx = idx + delta;
  11032. if (targetIdx < 0 || targetIdx >= list.length) return;
  11033. const currentOrder = list[idx].rule_order || 10;
  11034. const targetOrder = list[targetIdx].rule_order || 20;
  11035. list[idx].rule_order = targetOrder;
  11036. list[targetIdx].rule_order = currentOrder;
  11037. try {
  11038. await fetch(`${API_BASE}/routing/filters`, {
  11039. method: 'POST',
  11040. headers: { 'Content-Type': 'application/json' },
  11041. body: JSON.stringify(list[idx])
  11042. });
  11043. await fetch(`${API_BASE}/routing/filters`, {
  11044. method: 'POST',
  11045. headers: { 'Content-Type': 'application/json' },
  11046. body: JSON.stringify(list[targetIdx])
  11047. });
  11048. loadDynamicRouting();
  11049. } catch (e) {
  11050. console.error('Reorder error:', e);
  11051. }
  11052. }
  11053. async function deleteRoutingFilter(id) {
  11054. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11055. try {
  11056. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11057. if (res.ok) {
  11058. showToast('Deleted', 'Routing filter rule removed', 'info');
  11059. loadDynamicRouting();
  11060. } else {
  11061. const err = await res.json();
  11062. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11063. }
  11064. } catch (err) {
  11065. showToast('Error', err.message, 'error');
  11066. }
  11067. }
  11068. async function toggleRoutingFilterState(id, disabled) {
  11069. try {
  11070. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11071. method: 'POST',
  11072. headers: { 'Content-Type': 'application/json' },
  11073. body: JSON.stringify({ disabled })
  11074. });
  11075. if (res.ok) {
  11076. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11077. loadDynamicRouting();
  11078. } else {
  11079. const err = await res.json();
  11080. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11081. }
  11082. } catch (err) {
  11083. showToast('Error', err.message, 'error');
  11084. }
  11085. }
  11086. // -------------------------------------------------------------
  11087. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11088. // -------------------------------------------------------------
  11089. function openAddSelectRuleModal() {
  11090. document.getElementById('modal-rf-sr-id').value = '';
  11091. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11092. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11093. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11094. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11095. document.getElementById('modal-rf-sr-comment').value = '';
  11096. document.getElementById('modal-rf-sr-disabled').checked = false;
  11097. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11098. }
  11099. function openEditSelectRuleModal(id) {
  11100. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11101. if (!r) return;
  11102. document.getElementById('modal-rf-sr-id').value = r.id;
  11103. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11104. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11105. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11106. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11107. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11108. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11109. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11110. }
  11111. function closeSelectRuleModal() {
  11112. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11113. }
  11114. async function submitSelectRule(e) {
  11115. e.preventDefault();
  11116. const payload = {
  11117. id: document.getElementById('modal-rf-sr-id').value,
  11118. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11119. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11120. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11121. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11122. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11123. };
  11124. try {
  11125. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11126. method: 'POST',
  11127. headers: { 'Content-Type': 'application/json' },
  11128. body: JSON.stringify(payload)
  11129. });
  11130. if (res.ok) {
  11131. closeSelectRuleModal();
  11132. showToast('Success', 'Select rule saved', 'success');
  11133. loadDynamicRouting();
  11134. } else {
  11135. const err = await res.json();
  11136. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11137. }
  11138. } catch (err) {
  11139. showToast('Error', err.message, 'error');
  11140. }
  11141. }
  11142. async function deleteSelectRule(id) {
  11143. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11144. try {
  11145. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11146. if (res.ok) {
  11147. showToast('Deleted', 'Select rule removed', 'info');
  11148. loadDynamicRouting();
  11149. } else {
  11150. const err = await res.json();
  11151. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11152. }
  11153. } catch (err) {
  11154. showToast('Error', err.message, 'error');
  11155. }
  11156. }
  11157. async function toggleSelectRuleState(id, disabled) {
  11158. try {
  11159. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11160. method: 'POST',
  11161. headers: { 'Content-Type': 'application/json' },
  11162. body: JSON.stringify({ disabled })
  11163. });
  11164. if (res.ok) {
  11165. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11166. loadDynamicRouting();
  11167. } else {
  11168. const err = await res.json();
  11169. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11170. }
  11171. } catch (err) {
  11172. showToast('Error', err.message, 'error');
  11173. }
  11174. }
  11175. // -------------------------------------------------------------
  11176. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11177. // -------------------------------------------------------------
  11178. function openAddCommunityListModal() {
  11179. document.getElementById('modal-rf-cl-id').value = '';
  11180. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11181. document.getElementById('modal-rf-cl-name').value = '';
  11182. document.getElementById('modal-rf-cl-communities').value = '';
  11183. document.getElementById('modal-rf-cl-regexp').value = '';
  11184. document.getElementById('modal-rf-cl-comment').value = '';
  11185. document.getElementById('modal-rf-cl-disabled').checked = false;
  11186. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11187. }
  11188. function openEditCommunityListModal(id) {
  11189. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11190. if (!cl) return;
  11191. document.getElementById('modal-rf-cl-id').value = cl.id;
  11192. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11193. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11194. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11195. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11196. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11197. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11198. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11199. }
  11200. function closeCommunityListModal() {
  11201. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11202. }
  11203. async function submitCommunityList(e) {
  11204. e.preventDefault();
  11205. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11206. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11207. const payload = {
  11208. id: document.getElementById('modal-rf-cl-id').value,
  11209. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11210. communities: comms,
  11211. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11212. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11213. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11214. };
  11215. try {
  11216. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11217. method: 'POST',
  11218. headers: { 'Content-Type': 'application/json' },
  11219. body: JSON.stringify(payload)
  11220. });
  11221. if (res.ok) {
  11222. closeCommunityListModal();
  11223. showToast('Success', 'Community list saved', 'success');
  11224. loadDynamicRouting();
  11225. } else {
  11226. const err = await res.json();
  11227. showToast('Error', err.error || 'Failed to save community list', 'error');
  11228. }
  11229. } catch (err) {
  11230. showToast('Error', err.message, 'error');
  11231. }
  11232. }
  11233. async function deleteCommunityList(id) {
  11234. if (!confirm('Are you sure you want to delete this community list?')) return;
  11235. try {
  11236. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11237. if (res.ok) {
  11238. showToast('Deleted', 'Community list removed', 'info');
  11239. loadDynamicRouting();
  11240. } else {
  11241. const err = await res.json();
  11242. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11243. }
  11244. } catch (err) {
  11245. showToast('Error', err.message, 'error');
  11246. }
  11247. }
  11248. async function toggleCommunityListState(id, disabled) {
  11249. try {
  11250. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11251. method: 'POST',
  11252. headers: { 'Content-Type': 'application/json' },
  11253. body: JSON.stringify({ disabled })
  11254. });
  11255. if (res.ok) {
  11256. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11257. loadDynamicRouting();
  11258. } else {
  11259. const err = await res.json();
  11260. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11261. }
  11262. } catch (err) {
  11263. showToast('Error', err.message, 'error');
  11264. }
  11265. }
  11266. // -------------------------------------------------------------
  11267. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11268. // -------------------------------------------------------------
  11269. function openAddASListModal() {
  11270. document.getElementById('modal-rf-al-id').value = '';
  11271. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11272. document.getElementById('modal-rf-al-name').value = '';
  11273. document.getElementById('modal-rf-al-range').value = '';
  11274. document.getElementById('modal-rf-al-comment').value = '';
  11275. document.getElementById('modal-rf-al-disabled').checked = false;
  11276. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11277. }
  11278. function openEditASListModal(id) {
  11279. const al = (state.routingASLists || []).find(item => item.id === id);
  11280. if (!al) return;
  11281. document.getElementById('modal-rf-al-id').value = al.id;
  11282. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11283. document.getElementById('modal-rf-al-name').value = al.name || '';
  11284. document.getElementById('modal-rf-al-range').value = al.range || '';
  11285. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11286. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11287. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11288. }
  11289. function closeASListModal() {
  11290. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11291. }
  11292. async function submitASList(e) {
  11293. e.preventDefault();
  11294. const payload = {
  11295. id: document.getElementById('modal-rf-al-id').value,
  11296. name: document.getElementById('modal-rf-al-name').value.trim(),
  11297. range: document.getElementById('modal-rf-al-range').value.trim(),
  11298. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11299. disabled: document.getElementById('modal-rf-al-disabled').checked
  11300. };
  11301. try {
  11302. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11303. method: 'POST',
  11304. headers: { 'Content-Type': 'application/json' },
  11305. body: JSON.stringify(payload)
  11306. });
  11307. if (res.ok) {
  11308. closeASListModal();
  11309. showToast('Success', 'AS number list saved', 'success');
  11310. loadDynamicRouting();
  11311. } else {
  11312. const err = await res.json();
  11313. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11314. }
  11315. } catch (err) {
  11316. showToast('Error', err.message, 'error');
  11317. }
  11318. }
  11319. async function deleteASList(id) {
  11320. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11321. try {
  11322. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11323. if (res.ok) {
  11324. showToast('Deleted', 'AS list removed', 'info');
  11325. loadDynamicRouting();
  11326. } else {
  11327. const err = await res.json();
  11328. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11329. }
  11330. } catch (err) {
  11331. showToast('Error', err.message, 'error');
  11332. }
  11333. }
  11334. async function toggleASListState(id, disabled) {
  11335. try {
  11336. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11337. method: 'POST',
  11338. headers: { 'Content-Type': 'application/json' },
  11339. body: JSON.stringify({ disabled })
  11340. });
  11341. if (res.ok) {
  11342. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11343. loadDynamicRouting();
  11344. } else {
  11345. const err = await res.json();
  11346. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11347. }
  11348. } catch (err) {
  11349. showToast('Error', err.message, 'error');
  11350. }
  11351. }
  11352. // ==========================================
  11353. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11354. // ==========================================
  11355. function loadToolsView() {
  11356. populateToolsInterfaces();
  11357. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11358. }
  11359. function populateToolsInterfaces() {
  11360. const pingSel = document.getElementById('tools-ping-iface');
  11361. const traceSel = document.getElementById('tools-tr-iface');
  11362. let opts = '<option value="">Auto (Default Route)</option>';
  11363. if (Array.isArray(state.interfaces)) {
  11364. state.interfaces.forEach(iface => {
  11365. if (iface.name) {
  11366. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11367. }
  11368. });
  11369. }
  11370. if (pingSel) {
  11371. const cur = pingSel.value;
  11372. pingSel.innerHTML = opts;
  11373. if (cur) pingSel.value = cur;
  11374. }
  11375. if (traceSel) {
  11376. const cur = traceSel.value;
  11377. traceSel.innerHTML = opts;
  11378. if (cur) traceSel.value = cur;
  11379. }
  11380. }
  11381. function switchToolsSubTab(subTab) {
  11382. state.activeToolsSubTab = subTab;
  11383. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11384. tabs.forEach(t => {
  11385. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11386. const view = document.getElementById(`tools-view-${t}`);
  11387. if (btn) {
  11388. if (t === subTab) {
  11389. 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';
  11390. } else {
  11391. 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';
  11392. }
  11393. }
  11394. if (view) {
  11395. if (t === subTab) {
  11396. view.classList.remove('hidden');
  11397. } else {
  11398. view.classList.add('hidden');
  11399. }
  11400. }
  11401. });
  11402. }
  11403. function setPortPreset(port) {
  11404. const input = document.getElementById('tools-port-num');
  11405. if (input) input.value = port;
  11406. }
  11407. let pingAbortController = null;
  11408. let tracerouteAbortController = null;
  11409. function clearPingTable() {
  11410. const tbody = document.getElementById('tools-ping-tbody');
  11411. if (tbody) tbody.innerHTML = '';
  11412. const rawEl = document.getElementById('tools-ping-raw');
  11413. if (rawEl) rawEl.innerText = '';
  11414. const sentEl = document.getElementById('tools-ping-stat-sent');
  11415. if (sentEl) sentEl.innerText = '0';
  11416. const recvEl = document.getElementById('tools-ping-stat-recv');
  11417. if (recvEl) recvEl.innerText = '0';
  11418. const lossEl = document.getElementById('tools-ping-stat-loss');
  11419. if (lossEl) lossEl.innerText = '0%';
  11420. const avgEl = document.getElementById('tools-ping-stat-avg');
  11421. if (avgEl) avgEl.innerText = '0 ms';
  11422. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11423. if (minMaxEl) minMaxEl.innerText = '-';
  11424. const badge = document.getElementById('tools-ping-status-badge');
  11425. if (badge) {
  11426. badge.className = '';
  11427. badge.innerText = '';
  11428. }
  11429. }
  11430. function clearTracerouteTable() {
  11431. const tbody = document.getElementById('tools-tr-tbody');
  11432. if (tbody) tbody.innerHTML = '';
  11433. const rawEl = document.getElementById('tools-tr-raw');
  11434. if (rawEl) rawEl.innerText = '';
  11435. const statHops = document.getElementById('tools-tr-hops-count');
  11436. if (statHops) statHops.innerText = '0 Hops';
  11437. }
  11438. function resetPingButton() {
  11439. const btn = document.getElementById('tools-ping-btn');
  11440. const btnText = document.getElementById('tools-ping-btn-text');
  11441. const spinner = document.getElementById('tools-ping-spinner');
  11442. if (btn) {
  11443. btn.disabled = false;
  11444. 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';
  11445. }
  11446. if (btnText) btnText.innerText = 'Start Ping';
  11447. if (spinner) spinner.classList.add('hidden');
  11448. }
  11449. function setPingRunningButton() {
  11450. const btn = document.getElementById('tools-ping-btn');
  11451. const btnText = document.getElementById('tools-ping-btn-text');
  11452. const spinner = document.getElementById('tools-ping-spinner');
  11453. if (btn) {
  11454. btn.disabled = false;
  11455. 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';
  11456. }
  11457. if (btnText) btnText.innerText = 'Stop Ping';
  11458. if (spinner) spinner.classList.remove('hidden');
  11459. }
  11460. function resetTracerouteButton() {
  11461. const btn = document.getElementById('tools-tr-btn');
  11462. const btnText = document.getElementById('tools-tr-btn-text');
  11463. const spinner = document.getElementById('tools-tr-spinner');
  11464. if (btn) {
  11465. btn.disabled = false;
  11466. 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';
  11467. }
  11468. if (btnText) btnText.innerText = 'Start Traceroute';
  11469. if (spinner) spinner.classList.add('hidden');
  11470. }
  11471. function setTracerouteRunningButton() {
  11472. const btn = document.getElementById('tools-tr-btn');
  11473. const btnText = document.getElementById('tools-tr-btn-text');
  11474. const spinner = document.getElementById('tools-tr-spinner');
  11475. if (btn) {
  11476. btn.disabled = false;
  11477. 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';
  11478. }
  11479. if (btnText) btnText.innerText = 'Stop Traceroute';
  11480. if (spinner) spinner.classList.remove('hidden');
  11481. }
  11482. async function executePing(e) {
  11483. if (e) e.preventDefault();
  11484. // If already running, clicking the button stops the stream!
  11485. if (pingAbortController) {
  11486. pingAbortController.abort();
  11487. pingAbortController = null;
  11488. resetPingButton();
  11489. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11490. return;
  11491. }
  11492. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11493. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11494. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11495. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11496. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11497. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11498. if (!target) {
  11499. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11500. return;
  11501. }
  11502. clearPingTable();
  11503. const resCard = document.getElementById('tools-ping-results');
  11504. if (resCard) resCard.classList.remove('hidden');
  11505. pingAbortController = new AbortController();
  11506. setPingRunningButton();
  11507. try {
  11508. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11509. method: 'POST',
  11510. headers: { 'Content-Type': 'application/json' },
  11511. body: JSON.stringify({
  11512. target,
  11513. count,
  11514. size,
  11515. timeout,
  11516. interface: iface,
  11517. dont_frag: dontFrag
  11518. }),
  11519. signal: pingAbortController.signal
  11520. });
  11521. if (!res.ok) {
  11522. const errText = await res.text();
  11523. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11524. resetPingButton();
  11525. pingAbortController = null;
  11526. return;
  11527. }
  11528. const reader = res.body.getReader();
  11529. const decoder = new TextDecoder('utf-8');
  11530. let buffer = '';
  11531. while (true) {
  11532. const { done, value } = await reader.read();
  11533. if (done) break;
  11534. buffer += decoder.decode(value, { stream: true });
  11535. const blocks = buffer.split('\n\n');
  11536. buffer = blocks.pop() || '';
  11537. for (const block of blocks) {
  11538. const trimmed = block.trim();
  11539. if (!trimmed) continue;
  11540. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11541. try {
  11542. const evt = JSON.parse(line);
  11543. handleLivePingEvent(evt);
  11544. } catch (parseErr) {
  11545. console.warn('Ping SSE parse error:', parseErr, line);
  11546. }
  11547. }
  11548. }
  11549. } catch (err) {
  11550. if (err.name === 'AbortError') {
  11551. // User aborted normally
  11552. } else {
  11553. showToast('Ping Error', err.message, 'error');
  11554. }
  11555. } finally {
  11556. pingAbortController = null;
  11557. resetPingButton();
  11558. }
  11559. }
  11560. function handleLivePingEvent(evt) {
  11561. const sentEl = document.getElementById('tools-ping-stat-sent');
  11562. const recvEl = document.getElementById('tools-ping-stat-recv');
  11563. const lossEl = document.getElementById('tools-ping-stat-loss');
  11564. const avgEl = document.getElementById('tools-ping-stat-avg');
  11565. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11566. const badge = document.getElementById('tools-ping-status-badge');
  11567. const tbody = document.getElementById('tools-ping-tbody');
  11568. const rawEl = document.getElementById('tools-ping-raw');
  11569. if (evt.raw && rawEl) {
  11570. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11571. rawEl.scrollTop = rawEl.scrollHeight;
  11572. }
  11573. if (evt.type === 'reply') {
  11574. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11575. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11576. if (lossEl && evt.packet_loss_pct !== undefined) {
  11577. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11578. lossEl.className = evt.packet_loss_pct === 0
  11579. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11580. : (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');
  11581. }
  11582. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11583. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11584. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11585. }
  11586. if (badge) {
  11587. if (evt.packet_loss_pct === 0) {
  11588. 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';
  11589. badge.innerText = '100% OK';
  11590. } else {
  11591. 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';
  11592. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11593. }
  11594. }
  11595. if (tbody) {
  11596. const tr = document.createElement('tr');
  11597. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11598. tr.innerHTML = `
  11599. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11600. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11601. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11602. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11603. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11604. <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>
  11605. `;
  11606. tbody.appendChild(tr);
  11607. }
  11608. } else if (evt.type === 'timeout') {
  11609. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11610. if (lossEl && evt.packet_loss_pct !== undefined) {
  11611. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11612. 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';
  11613. }
  11614. if (badge) {
  11615. 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';
  11616. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11617. }
  11618. if (tbody) {
  11619. const tr = document.createElement('tr');
  11620. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11621. tr.innerHTML = `
  11622. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11623. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11624. <td class="py-2 px-3 text-slate-600">--</td>
  11625. <td class="py-2 px-3 text-slate-600">--</td>
  11626. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11627. <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>
  11628. `;
  11629. tbody.appendChild(tr);
  11630. }
  11631. } else if (evt.type === 'unreach') {
  11632. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11633. if (lossEl && evt.packet_loss_pct !== undefined) {
  11634. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11635. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11636. }
  11637. if (badge) {
  11638. 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';
  11639. badge.innerText = 'UNREACHABLE';
  11640. }
  11641. if (tbody) {
  11642. const tr = document.createElement('tr');
  11643. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11644. tr.innerHTML = `
  11645. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11646. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11647. <td class="py-2 px-3 text-slate-600">--</td>
  11648. <td class="py-2 px-3 text-slate-600">--</td>
  11649. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11650. <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>
  11651. `;
  11652. tbody.appendChild(tr);
  11653. }
  11654. } else if (evt.type === 'stats') {
  11655. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11656. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11657. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11658. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11659. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11660. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11661. }
  11662. } else if (evt.type === 'done') {
  11663. 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');
  11664. }
  11665. }
  11666. async function executeTraceroute(e) {
  11667. if (e) e.preventDefault();
  11668. if (tracerouteAbortController) {
  11669. tracerouteAbortController.abort();
  11670. tracerouteAbortController = null;
  11671. resetTracerouteButton();
  11672. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11673. return;
  11674. }
  11675. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11676. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11677. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11678. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11679. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11680. if (!target) {
  11681. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11682. return;
  11683. }
  11684. clearTracerouteTable();
  11685. const resCard = document.getElementById('tools-tr-results');
  11686. if (resCard) resCard.classList.remove('hidden');
  11687. tracerouteAbortController = new AbortController();
  11688. setTracerouteRunningButton();
  11689. try {
  11690. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11691. method: 'POST',
  11692. headers: { 'Content-Type': 'application/json' },
  11693. body: JSON.stringify({
  11694. target,
  11695. max_hops: maxHops,
  11696. protocol,
  11697. interface: iface,
  11698. resolve
  11699. }),
  11700. signal: tracerouteAbortController.signal
  11701. });
  11702. if (!res.ok) {
  11703. const errText = await res.text();
  11704. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11705. resetTracerouteButton();
  11706. tracerouteAbortController = null;
  11707. return;
  11708. }
  11709. const reader = res.body.getReader();
  11710. const decoder = new TextDecoder('utf-8');
  11711. let buffer = '';
  11712. while (true) {
  11713. const { done, value } = await reader.read();
  11714. if (done) break;
  11715. buffer += decoder.decode(value, { stream: true });
  11716. const blocks = buffer.split('\n\n');
  11717. buffer = blocks.pop() || '';
  11718. for (const block of blocks) {
  11719. const trimmed = block.trim();
  11720. if (!trimmed) continue;
  11721. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11722. try {
  11723. const evt = JSON.parse(line);
  11724. handleLiveTracerouteEvent(evt);
  11725. } catch (parseErr) {
  11726. console.warn('Traceroute SSE parse error:', parseErr, line);
  11727. }
  11728. }
  11729. }
  11730. } catch (err) {
  11731. if (err.name === 'AbortError') {
  11732. // User aborted normally
  11733. } else {
  11734. showToast('Traceroute Error', err.message, 'error');
  11735. }
  11736. } finally {
  11737. tracerouteAbortController = null;
  11738. resetTracerouteButton();
  11739. }
  11740. }
  11741. function handleLiveTracerouteEvent(evt) {
  11742. const statHops = document.getElementById('tools-tr-hops-count');
  11743. const tbody = document.getElementById('tools-tr-tbody');
  11744. const rawEl = document.getElementById('tools-tr-raw');
  11745. if (evt.raw && rawEl) {
  11746. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11747. rawEl.scrollTop = rawEl.scrollHeight;
  11748. }
  11749. if (evt.hops_count !== undefined && statHops) {
  11750. statHops.innerText = `${evt.hops_count} Hops`;
  11751. }
  11752. if (evt.type === 'hop' && evt.hop && tbody) {
  11753. const h = evt.hop;
  11754. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11755. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11756. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11757. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11758. const tr = document.createElement('tr');
  11759. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11760. tr.innerHTML = `
  11761. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11762. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11763. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11764. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11765. <td class="py-2.5 px-3 text-right">
  11766. ${isTimeout
  11767. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11768. : '<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>'}
  11769. </td>
  11770. `;
  11771. tbody.appendChild(tr);
  11772. } else if (evt.type === 'done') {
  11773. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11774. }
  11775. }
  11776. async function executeMTR(e) {
  11777. if (e) e.preventDefault();
  11778. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11779. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11780. if (!target) {
  11781. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11782. return;
  11783. }
  11784. const btn = document.getElementById('tools-mtr-btn');
  11785. const spinner = document.getElementById('tools-mtr-spinner');
  11786. if (btn) btn.disabled = true;
  11787. if (spinner) spinner.classList.remove('hidden');
  11788. try {
  11789. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11790. method: 'POST',
  11791. headers: { 'Content-Type': 'application/json' },
  11792. body: JSON.stringify({ target, count: cycles })
  11793. });
  11794. const data = await res.json();
  11795. if (!res.ok) {
  11796. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11797. return;
  11798. }
  11799. const resCard = document.getElementById('tools-mtr-results');
  11800. if (resCard) resCard.classList.remove('hidden');
  11801. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11802. const statHops = document.getElementById('tools-mtr-hops-count');
  11803. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11804. const tbody = document.getElementById('tools-mtr-tbody');
  11805. if (tbody) {
  11806. if (hopsCount > 0) {
  11807. tbody.innerHTML = data.hops.map(h => {
  11808. 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');
  11809. return `
  11810. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11811. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11812. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11813. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11814. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11815. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11816. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11817. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11818. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11819. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11820. </tr>
  11821. `;
  11822. }).join('');
  11823. } else {
  11824. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11825. }
  11826. }
  11827. const rawEl = document.getElementById('tools-mtr-raw');
  11828. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11829. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11830. } catch (err) {
  11831. showToast('MTR Error', err.message, 'error');
  11832. } finally {
  11833. if (btn) btn.disabled = false;
  11834. if (spinner) spinner.classList.add('hidden');
  11835. }
  11836. }
  11837. async function executeDNS(e) {
  11838. if (e) e.preventDefault();
  11839. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11840. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11841. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11842. if (!domain) {
  11843. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11844. return;
  11845. }
  11846. const btn = document.getElementById('tools-dns-btn');
  11847. const spinner = document.getElementById('tools-dns-spinner');
  11848. if (btn) btn.disabled = true;
  11849. if (spinner) spinner.classList.remove('hidden');
  11850. try {
  11851. const res = await fetch(`${API_BASE}/tools/dns`, {
  11852. method: 'POST',
  11853. headers: { 'Content-Type': 'application/json' },
  11854. body: JSON.stringify({ domain, type, server })
  11855. });
  11856. const data = await res.json();
  11857. if (!res.ok) {
  11858. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11859. return;
  11860. }
  11861. const resCard = document.getElementById('tools-dns-results');
  11862. if (resCard) resCard.classList.remove('hidden');
  11863. const metaEl = document.getElementById('tools-dns-meta');
  11864. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11865. const tbody = document.getElementById('tools-dns-tbody');
  11866. if (tbody) {
  11867. if (Array.isArray(data.records) && data.records.length > 0) {
  11868. tbody.innerHTML = data.records.map(r => `
  11869. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11870. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11871. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11872. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11873. <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>
  11874. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11875. </tr>
  11876. `).join('');
  11877. } else {
  11878. 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>`;
  11879. }
  11880. }
  11881. const rawEl = document.getElementById('tools-dns-raw');
  11882. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11883. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11884. } catch (err) {
  11885. showToast('DNS Error', err.message, 'error');
  11886. } finally {
  11887. if (btn) btn.disabled = false;
  11888. if (spinner) spinner.classList.add('hidden');
  11889. }
  11890. }
  11891. async function executePortProbe(e) {
  11892. if (e) e.preventDefault();
  11893. const target = document.getElementById('tools-port-target')?.value?.trim();
  11894. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11895. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11896. if (!target || !port) {
  11897. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11898. return;
  11899. }
  11900. const btn = document.getElementById('tools-port-btn');
  11901. const spinner = document.getElementById('tools-port-spinner');
  11902. if (btn) btn.disabled = true;
  11903. if (spinner) spinner.classList.remove('hidden');
  11904. try {
  11905. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11906. method: 'POST',
  11907. headers: { 'Content-Type': 'application/json' },
  11908. body: JSON.stringify({ target, port, timeout })
  11909. });
  11910. const data = await res.json();
  11911. if (!res.ok) {
  11912. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11913. return;
  11914. }
  11915. const resCard = document.getElementById('tools-port-results');
  11916. if (resCard) resCard.classList.remove('hidden');
  11917. const banner = document.getElementById('tools-port-banner');
  11918. const icon = document.getElementById('tools-port-icon');
  11919. const title = document.getElementById('tools-port-title');
  11920. const sub = document.getElementById('tools-port-sub');
  11921. const latency = document.getElementById('tools-port-latency');
  11922. if (data.open) {
  11923. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11924. if (icon) {
  11925. 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';
  11926. icon.innerText = '✓';
  11927. }
  11928. if (title) {
  11929. title.className = 'text-sm font-bold text-emerald-300';
  11930. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11931. }
  11932. if (sub) {
  11933. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11934. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11935. }
  11936. if (latency) {
  11937. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11938. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11939. }
  11940. } else {
  11941. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11942. if (icon) {
  11943. 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';
  11944. icon.innerText = '✕';
  11945. }
  11946. if (title) {
  11947. title.className = 'text-sm font-bold text-rose-300';
  11948. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11949. }
  11950. if (sub) {
  11951. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11952. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11953. }
  11954. if (latency) {
  11955. latency.className = 'text-base font-bold font-mono text-slate-500';
  11956. latency.innerText = '--';
  11957. }
  11958. }
  11959. const rawEl = document.getElementById('tools-port-raw');
  11960. 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'}`);
  11961. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11962. } catch (err) {
  11963. showToast('Probe Error', err.message, 'error');
  11964. } finally {
  11965. if (btn) btn.disabled = false;
  11966. if (spinner) spinner.classList.add('hidden');
  11967. }
  11968. }
  11969. // ==========================================
  11970. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11971. // ==========================================
  11972. async function loadDHCPClients(showToastMsg = false) {
  11973. try {
  11974. const [clientsRes, sumRes] = await Promise.all([
  11975. fetch(`${API_BASE}/dhcp/clients`),
  11976. fetch(`${API_BASE}/dhcp/clients/summary`)
  11977. ]);
  11978. if (clientsRes.ok) {
  11979. state.dhcpClients = await clientsRes.json();
  11980. }
  11981. if (sumRes.ok) {
  11982. state.dhcpSummary = await sumRes.json();
  11983. }
  11984. renderDHCPClients();
  11985. updateDHCPSummaryCards();
  11986. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11987. if (bDhcp && state.dhcpSummary) {
  11988. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11989. }
  11990. if (showToastMsg) {
  11991. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11992. }
  11993. } catch (err) {
  11994. console.error('Failed to load DHCP clients:', err);
  11995. if (showToastMsg) {
  11996. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11997. }
  11998. }
  11999. }
  12000. function updateDHCPSummaryCards() {
  12001. const sum = state.dhcpSummary || {
  12002. total_clients: (state.dhcpClients || []).length,
  12003. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12004. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12005. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12006. };
  12007. const totalEl = document.getElementById('dhcp-stat-total');
  12008. const boundEl = document.getElementById('dhcp-stat-bound');
  12009. const searchEl = document.getElementById('dhcp-stat-searching');
  12010. const disEl = document.getElementById('dhcp-stat-disabled');
  12011. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12012. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12013. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12014. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12015. }
  12016. function renderDHCPClients() {
  12017. const tbody = document.getElementById('dhcp-clients-tbody');
  12018. const emptyState = document.getElementById('dhcp-clients-empty');
  12019. if (!tbody) return;
  12020. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12021. if (clients.length === 0) {
  12022. tbody.innerHTML = '';
  12023. if (emptyState) emptyState.classList.remove('hidden');
  12024. return;
  12025. }
  12026. if (emptyState) emptyState.classList.add('hidden');
  12027. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12028. if (tbody.dataset.sig === sig) return;
  12029. tbody.dataset.sig = sig;
  12030. tbody.innerHTML = clients.map(c => {
  12031. let statusBadge = '';
  12032. if (!c.enabled) {
  12033. 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>';
  12034. } else if (c.status === 'bound') {
  12035. 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>';
  12036. } else if (c.status === 'searching') {
  12037. 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>';
  12038. } else if (c.status === 'stopped') {
  12039. 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>';
  12040. } else {
  12041. 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>`;
  12042. }
  12043. 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>';
  12044. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12045. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12046. 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>';
  12047. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12048. // Option flags
  12049. const flags = [];
  12050. 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>');
  12051. 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>');
  12052. 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>');
  12053. 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>`);
  12054. return `
  12055. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12056. <td class="py-3 px-4">
  12057. <div class="flex items-center gap-2">
  12058. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12059. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12060. </div>
  12061. </td>
  12062. <td class="py-3 px-4">${statusBadge}</td>
  12063. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12064. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12065. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12066. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12067. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12068. <td class="py-3 px-4">
  12069. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12070. </td>
  12071. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12072. ${c.enabled ? `
  12073. <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>
  12074. <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>
  12075. <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>
  12076. ` : `
  12077. <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>
  12078. `}
  12079. <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>
  12080. <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>
  12081. </td>
  12082. </tr>
  12083. `;
  12084. }).join('');
  12085. }
  12086. function openDHCPClientModal(clientId = null) {
  12087. const modal = document.getElementById('modal-dhcp-client');
  12088. if (!modal) return;
  12089. const title = document.getElementById('modal-dhcp-title');
  12090. const idInput = document.getElementById('modal-dhcp-id');
  12091. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12092. const distInput = document.getElementById('modal-dhcp-distance');
  12093. const commentInput = document.getElementById('modal-dhcp-comment');
  12094. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12095. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12096. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12097. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12098. // Populate interfaces
  12099. if (ifaceSelect) {
  12100. let opts = '<option value="">Select interface...</option>';
  12101. const allIfaces = state.interfaces || [];
  12102. const allVlans = state.vlans || [];
  12103. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12104. // Group 1: Physical & Bridge Interfaces
  12105. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12106. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12107. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12108. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12109. });
  12110. opts += '</optgroup>';
  12111. // Group 2: VLAN Interfaces
  12112. if (allVlans.length > 0) {
  12113. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12114. allVlans.forEach(v => {
  12115. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12116. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12117. });
  12118. opts += '</optgroup>';
  12119. }
  12120. ifaceSelect.innerHTML = opts;
  12121. }
  12122. if (clientId) {
  12123. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12124. if (client) {
  12125. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12126. if (idInput) idInput.value = client.id;
  12127. if (ifaceSelect) {
  12128. ifaceSelect.value = client.interface;
  12129. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12130. }
  12131. if (distInput) distInput.value = client.default_route_distance || 1;
  12132. if (commentInput) commentInput.value = client.comment || '';
  12133. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12134. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12135. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12136. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12137. }
  12138. } else {
  12139. if (title) title.innerText = 'Add DHCP Client';
  12140. if (idInput) idInput.value = '';
  12141. if (ifaceSelect) {
  12142. ifaceSelect.value = '';
  12143. ifaceSelect.disabled = false;
  12144. }
  12145. if (distInput) distInput.value = 1;
  12146. if (commentInput) commentInput.value = '';
  12147. if (defRouteCheck) defRouteCheck.checked = true;
  12148. if (peerDnsCheck) peerDnsCheck.checked = true;
  12149. if (peerNtpCheck) peerNtpCheck.checked = true;
  12150. if (enabledCheck) enabledCheck.checked = true;
  12151. }
  12152. modal.classList.remove('hidden');
  12153. }
  12154. function openDHCPClientModalForIface(ifaceName) {
  12155. openDHCPClientModal();
  12156. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12157. if (ifaceSelect && ifaceName) {
  12158. ifaceSelect.value = ifaceName;
  12159. }
  12160. }
  12161. function closeDHCPClientModal() {
  12162. const modal = document.getElementById('modal-dhcp-client');
  12163. if (modal) modal.classList.add('hidden');
  12164. }
  12165. async function submitSaveDHCPClient(e) {
  12166. if (e) e.preventDefault();
  12167. const id = document.getElementById('modal-dhcp-id')?.value;
  12168. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12169. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12170. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12171. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12172. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12173. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12174. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12175. if (!id && !iface) {
  12176. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12177. return;
  12178. }
  12179. try {
  12180. let res;
  12181. if (id) {
  12182. // PUT update
  12183. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12184. method: 'PUT',
  12185. headers: { 'Content-Type': 'application/json' },
  12186. body: JSON.stringify({
  12187. enabled,
  12188. add_default_route: defRoute,
  12189. default_route_distance: distance,
  12190. use_peer_dns: peerDns,
  12191. use_peer_ntp: peerNtp,
  12192. comment
  12193. })
  12194. });
  12195. } else {
  12196. // POST create
  12197. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12198. method: 'POST',
  12199. headers: { 'Content-Type': 'application/json' },
  12200. body: JSON.stringify({
  12201. interface: iface,
  12202. enabled,
  12203. add_default_route: defRoute,
  12204. default_route_distance: distance,
  12205. use_peer_dns: peerDns,
  12206. use_peer_ntp: peerNtp,
  12207. comment
  12208. })
  12209. });
  12210. }
  12211. const data = await res.json();
  12212. if (!res.ok) {
  12213. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12214. return;
  12215. }
  12216. closeDHCPClientModal();
  12217. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12218. await loadDHCPClients();
  12219. fetchData(); // refresh interfaces list with new lease/status
  12220. } catch (err) {
  12221. showToast('Error', err.message, 'error');
  12222. }
  12223. }
  12224. async function toggleDHCPClientState(id, enabled) {
  12225. try {
  12226. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12227. method: 'POST',
  12228. headers: { 'Content-Type': 'application/json' },
  12229. body: JSON.stringify({ enabled })
  12230. });
  12231. const data = await res.json();
  12232. if (!res.ok) {
  12233. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12234. return;
  12235. }
  12236. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12237. await loadDHCPClients();
  12238. fetchData();
  12239. } catch (err) {
  12240. showToast('Error', err.message, 'error');
  12241. }
  12242. }
  12243. async function renewDHCPClient(id) {
  12244. try {
  12245. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12246. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12247. method: 'POST'
  12248. });
  12249. const data = await res.json();
  12250. if (!res.ok) {
  12251. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12252. return;
  12253. }
  12254. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12255. setTimeout(() => {
  12256. loadDHCPClients();
  12257. fetchData();
  12258. }, 1500);
  12259. } catch (err) {
  12260. showToast('Error', err.message, 'error');
  12261. }
  12262. }
  12263. async function releaseDHCPClient(id) {
  12264. try {
  12265. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12266. method: 'POST'
  12267. });
  12268. const data = await res.json();
  12269. if (!res.ok) {
  12270. showToast('Error', data.error || 'Failed to release lease', 'error');
  12271. return;
  12272. }
  12273. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12274. await loadDHCPClients();
  12275. fetchData();
  12276. } catch (err) {
  12277. showToast('Error', err.message, 'error');
  12278. }
  12279. }
  12280. async function deleteDHCPClient(id, ifaceName) {
  12281. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12282. return;
  12283. }
  12284. try {
  12285. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12286. method: 'DELETE'
  12287. });
  12288. const data = await res.json();
  12289. if (!res.ok) {
  12290. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12291. return;
  12292. }
  12293. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12294. await loadDHCPClients();
  12295. fetchData();
  12296. } catch (err) {
  12297. showToast('Error', err.message, 'error');
  12298. }
  12299. }
  12300. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12301. async function loadDHCPServer(populate = true) {
  12302. try {
  12303. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12304. fetch(`${API_BASE}/dhcp-server/summary`),
  12305. fetch(`${API_BASE}/dhcp-server/servers`),
  12306. fetch(`${API_BASE}/dhcp-server/networks`),
  12307. fetch(`${API_BASE}/dhcp-server/leases`),
  12308. fetch(`${API_BASE}/dhcp-server/options`)
  12309. ]);
  12310. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12311. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12312. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12313. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12314. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12315. const sum = state.dhcpServerSummary || {};
  12316. const srvs = state.dhcpServers || [];
  12317. const nets = state.dhcpNetworks || [];
  12318. const leases = state.dhcpLeases || [];
  12319. const opts = state.dhcpOptions || [];
  12320. // KPI Cards
  12321. const statActive = document.getElementById('dhcp-server-stat-active');
  12322. if (statActive) {
  12323. const activeCount = srvs.filter(s => s.running).length;
  12324. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12325. }
  12326. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12327. if (statLeases) {
  12328. statLeases.innerText = leases.length;
  12329. }
  12330. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12331. if (statLeasesSub) {
  12332. const dyn = leases.filter(l => l.dynamic).length;
  12333. const st = leases.filter(l => !l.dynamic).length;
  12334. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12335. }
  12336. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12337. if (statNetworks) {
  12338. statNetworks.innerText = nets.length;
  12339. }
  12340. // Subtab Badges
  12341. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12342. if (bSrv) bSrv.innerText = srvs.length;
  12343. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12344. if (bNet) bNet.innerText = nets.length;
  12345. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12346. if (bLease) bLease.innerText = leases.length;
  12347. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12348. if (bOpt) bOpt.innerText = opts.length;
  12349. // Sidebar Badge
  12350. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12351. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12352. renderCurrentDHCPServerTab();
  12353. } catch (err) {
  12354. console.error('Failed to load DHCP Server:', err);
  12355. }
  12356. }
  12357. function switchDHCPServerTab(tab) {
  12358. state.dhcpServerTab = tab;
  12359. const tabs = ['servers', 'networks', 'leases', 'options'];
  12360. tabs.forEach(t => {
  12361. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12362. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12363. if (panel) {
  12364. if (t === tab) panel.classList.remove('hidden');
  12365. else panel.classList.add('hidden');
  12366. }
  12367. if (btn) {
  12368. if (t === tab) {
  12369. 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';
  12370. } else {
  12371. 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';
  12372. }
  12373. }
  12374. });
  12375. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12376. if (addBtn) {
  12377. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12378. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12379. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12380. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12381. }
  12382. renderCurrentDHCPServerTab();
  12383. }
  12384. function handleDHCPServerPrimaryAdd() {
  12385. const tab = state.dhcpServerTab || 'servers';
  12386. if (tab === 'servers') openAddDHCPServerModal();
  12387. else if (tab === 'networks') openAddDHCPNetworkModal();
  12388. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12389. else if (tab === 'options') openAddDHCPOptionModal();
  12390. }
  12391. function renderCurrentDHCPServerTab() {
  12392. const tab = state.dhcpServerTab || 'servers';
  12393. if (tab === 'servers') renderDHCPServers();
  12394. else if (tab === 'networks') renderDHCPNetworks();
  12395. else if (tab === 'leases') renderDHCPLeases();
  12396. else if (tab === 'options') renderDHCPOptions();
  12397. }
  12398. function renderDHCPServers() {
  12399. const tbody = document.getElementById('dhcp-server-tbody');
  12400. const empty = document.getElementById('dhcp-server-empty');
  12401. if (!tbody) return;
  12402. const servers = state.dhcpServers || [];
  12403. if (servers.length === 0) {
  12404. tbody.innerHTML = '';
  12405. empty?.classList.remove('hidden');
  12406. return;
  12407. }
  12408. empty?.classList.add('hidden');
  12409. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12410. if (tbody.dataset.sig === sig) return;
  12411. tbody.dataset.sig = sig;
  12412. tbody.innerHTML = '';
  12413. servers.forEach(s => {
  12414. const tr = document.createElement('tr');
  12415. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12416. tr.innerHTML = `
  12417. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12418. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12419. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12420. <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>
  12421. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12422. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12423. <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>
  12424. <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>
  12425. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12426. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12427. <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>
  12428. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12429. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12430. </td>
  12431. `;
  12432. tbody.appendChild(tr);
  12433. });
  12434. }
  12435. function renderDHCPNetworks() {
  12436. const tbody = document.getElementById('dhcp-networks-tbody');
  12437. const empty = document.getElementById('dhcp-networks-empty');
  12438. if (!tbody) return;
  12439. tbody.innerHTML = '';
  12440. const networks = state.dhcpNetworks || [];
  12441. if (networks.length === 0) {
  12442. empty?.classList.remove('hidden');
  12443. return;
  12444. }
  12445. empty?.classList.add('hidden');
  12446. networks.forEach(n => {
  12447. const tr = document.createElement('tr');
  12448. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12449. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12450. const optionsChips = (n.dhcp_options || []).map(optId => {
  12451. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12452. if (!opt) return '';
  12453. 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>`;
  12454. }).filter(Boolean).join('');
  12455. tr.innerHTML = `
  12456. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12457. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12458. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12459. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12460. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12461. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12463. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12464. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12465. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12466. </td>
  12467. `;
  12468. tbody.appendChild(tr);
  12469. });
  12470. }
  12471. function renderDHCPLeases() {
  12472. const tbody = document.getElementById('dhcp-leases-tbody');
  12473. const empty = document.getElementById('dhcp-leases-empty');
  12474. if (!tbody) return;
  12475. tbody.innerHTML = '';
  12476. const leases = state.dhcpLeases || [];
  12477. if (leases.length === 0) {
  12478. empty?.classList.remove('hidden');
  12479. return;
  12480. }
  12481. empty?.classList.add('hidden');
  12482. leases.forEach(l => {
  12483. const tr = document.createElement('tr');
  12484. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12485. 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>';
  12486. const statusBadge = l.status === 'bound'
  12487. ? '<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>'
  12488. : l.status === 'static'
  12489. ? '<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>'
  12490. : '<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>';
  12491. const makeStaticBtn = l.dynamic
  12492. ? `<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>`
  12493. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12494. tr.innerHTML = `
  12495. <td class="py-2.5 px-3 text-center">${flag}</td>
  12496. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12497. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12498. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12499. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12500. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12501. <td class="py-2.5 px-3">${statusBadge}</td>
  12502. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12503. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12504. ${makeStaticBtn}
  12505. </td>
  12506. `;
  12507. tbody.appendChild(tr);
  12508. });
  12509. }
  12510. function renderDHCPOptions() {
  12511. const tbody = document.getElementById('dhcp-options-tbody');
  12512. const empty = document.getElementById('dhcp-options-empty');
  12513. if (!tbody) return;
  12514. tbody.innerHTML = '';
  12515. const options = state.dhcpOptions || [];
  12516. if (options.length === 0) {
  12517. empty?.classList.remove('hidden');
  12518. return;
  12519. }
  12520. empty?.classList.add('hidden');
  12521. options.forEach(o => {
  12522. const tr = document.createElement('tr');
  12523. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12524. tr.innerHTML = `
  12525. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12526. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12527. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12528. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12529. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12530. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12531. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12532. </td>
  12533. `;
  12534. tbody.appendChild(tr);
  12535. });
  12536. }
  12537. // ==================== MODALS & ACTIONS: SERVER ====================
  12538. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12539. const sel = document.getElementById(elemId);
  12540. if (!sel) return;
  12541. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12542. const networks = state.dhcpNetworks || [];
  12543. networks.forEach(n => {
  12544. const opt = document.createElement('option');
  12545. opt.value = n.address;
  12546. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12547. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12548. opt.selected = true;
  12549. }
  12550. sel.appendChild(opt);
  12551. });
  12552. }
  12553. function onDHCPServerNetworkChange() {
  12554. const netSel = document.getElementById('dhcp-server-modal-network');
  12555. if (!netSel) return;
  12556. const netVal = netSel.value;
  12557. if (!netVal) return;
  12558. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12559. if (!poolInput) return;
  12560. // Auto-calculate suggested address pool based on subnet CIDR
  12561. const parts = netVal.split('/');
  12562. const ip = parts[0];
  12563. const cidr = parseInt(parts[1] || '24', 10);
  12564. if (cidr === 24) {
  12565. const octets = ip.split('.');
  12566. if (octets.length === 4) {
  12567. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12568. poolInput.value = `${base}.10-${base}.254`;
  12569. }
  12570. }
  12571. }
  12572. function openAddDHCPServerModal() {
  12573. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12574. document.getElementById('dhcp-server-modal-id').value = '';
  12575. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12576. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12577. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12578. document.getElementById('dhcp-server-modal-comment').value = '';
  12579. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12580. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12581. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12582. const networks = state.dhcpNetworks || [];
  12583. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12584. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12585. if (defaultNet) {
  12586. onDHCPServerNetworkChange();
  12587. }
  12588. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12589. }
  12590. function openEditDHCPServerModal(id) {
  12591. const s = (state.dhcpServers || []).find(item => item.id === id);
  12592. if (!s) return;
  12593. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12594. document.getElementById('dhcp-server-modal-id').value = s.id;
  12595. document.getElementById('dhcp-server-modal-name').value = s.name;
  12596. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12597. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12598. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12599. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12600. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12601. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12602. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12603. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12604. }
  12605. function closeDHCPServerModal() {
  12606. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12607. }
  12608. async function submitSaveDHCPServer(e) {
  12609. e.preventDefault();
  12610. const id = document.getElementById('dhcp-server-modal-id').value;
  12611. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12612. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12613. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12614. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12615. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12616. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12617. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12618. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12619. try {
  12620. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12621. method: 'POST',
  12622. headers: { 'Content-Type': 'application/json' },
  12623. body: JSON.stringify({
  12624. id,
  12625. name,
  12626. interface: iface,
  12627. network,
  12628. address_pool: pool,
  12629. lease_time: leaseTime,
  12630. authoritative,
  12631. disabled,
  12632. comment
  12633. })
  12634. });
  12635. if (res.ok) {
  12636. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12637. closeDHCPServerModal();
  12638. loadDHCPServer(false);
  12639. fetchData(false);
  12640. } else {
  12641. const err = await res.text();
  12642. showToast('Error', err, 'error');
  12643. }
  12644. } catch (err) {
  12645. showToast('Error', err.message, 'error');
  12646. }
  12647. }
  12648. async function toggleDHCPServerState(id, disabled) {
  12649. try {
  12650. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12651. method: 'POST',
  12652. headers: { 'Content-Type': 'application/json' },
  12653. body: JSON.stringify({ disabled })
  12654. });
  12655. if (res.ok) {
  12656. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12657. loadDHCPServer(false);
  12658. fetchData(false);
  12659. }
  12660. } catch (err) {
  12661. showToast('Error', err.message, 'error');
  12662. }
  12663. }
  12664. async function deleteDHCPServer(id, name) {
  12665. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12666. try {
  12667. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12668. if (res.ok) {
  12669. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12670. loadDHCPServer(false);
  12671. fetchData(false);
  12672. }
  12673. } catch (err) {
  12674. showToast('Error', err.message, 'error');
  12675. }
  12676. }
  12677. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12678. function openAddDHCPNetworkModal() {
  12679. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12680. document.getElementById('dhcp-network-modal-id').value = '';
  12681. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12682. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12683. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12684. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12685. document.getElementById('dhcp-network-modal-netmask').value = '';
  12686. document.getElementById('dhcp-network-modal-comment').value = '';
  12687. renderDHCPNetworkOptionsCheckboxes([]);
  12688. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12689. }
  12690. function openEditDHCPNetworkModal(id) {
  12691. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12692. if (!n) return;
  12693. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12694. document.getElementById('dhcp-network-modal-id').value = n.id;
  12695. document.getElementById('dhcp-network-modal-address').value = n.address;
  12696. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12697. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12698. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12699. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12700. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12701. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12702. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12703. }
  12704. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12705. const container = document.getElementById('dhcp-network-modal-options-list');
  12706. if (!container) return;
  12707. container.innerHTML = '';
  12708. const opts = state.dhcpOptions || [];
  12709. if (opts.length === 0) {
  12710. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12711. return;
  12712. }
  12713. opts.forEach(o => {
  12714. const isChecked = selectedIds.includes(o.id);
  12715. const label = document.createElement('label');
  12716. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12717. label.innerHTML = `
  12718. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12719. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12720. `;
  12721. container.appendChild(label);
  12722. });
  12723. }
  12724. function closeDHCPNetworkModal() {
  12725. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12726. }
  12727. async function submitSaveDHCPNetwork(e) {
  12728. e.preventDefault();
  12729. const id = document.getElementById('dhcp-network-modal-id').value;
  12730. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12731. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12732. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12733. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12734. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12735. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12736. const selectedOpts = [];
  12737. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12738. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12739. try {
  12740. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12741. method: 'POST',
  12742. headers: { 'Content-Type': 'application/json' },
  12743. body: JSON.stringify({
  12744. id,
  12745. address,
  12746. gateway,
  12747. netmask,
  12748. dns_servers: dnsServers,
  12749. domain,
  12750. dhcp_options: selectedOpts,
  12751. comment
  12752. })
  12753. });
  12754. if (res.ok) {
  12755. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12756. closeDHCPNetworkModal();
  12757. loadDHCPServer(false);
  12758. fetchData(false);
  12759. } else {
  12760. const err = await res.text();
  12761. showToast('Error', err, 'error');
  12762. }
  12763. } catch (err) {
  12764. showToast('Error', err.message, 'error');
  12765. }
  12766. }
  12767. async function deleteDHCPNetwork(id, addr) {
  12768. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12769. try {
  12770. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12771. if (res.ok) {
  12772. showToast('Deleted', `Network ${addr} removed`, 'success');
  12773. loadDHCPServer(false);
  12774. fetchData(false);
  12775. }
  12776. } catch (err) {
  12777. showToast('Error', err.message, 'error');
  12778. }
  12779. }
  12780. // ==================== MODALS & ACTIONS: LEASES ====================
  12781. function openAddDHCPStaticLeaseModal() {
  12782. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12783. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12784. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12785. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12786. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12787. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12788. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12789. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12790. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12791. }
  12792. function closeDHCPStaticLeaseModal() {
  12793. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12794. }
  12795. async function submitSaveDHCPStaticLease(e) {
  12796. e.preventDefault();
  12797. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12798. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12799. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12800. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12801. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12802. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12803. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12804. try {
  12805. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12806. method: 'POST',
  12807. headers: { 'Content-Type': 'application/json' },
  12808. body: JSON.stringify({
  12809. id,
  12810. mac_address: mac,
  12811. address: ip,
  12812. hostname,
  12813. server,
  12814. comment,
  12815. disabled
  12816. })
  12817. });
  12818. if (res.ok) {
  12819. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12820. closeDHCPStaticLeaseModal();
  12821. loadDHCPServer(false);
  12822. fetchData(false);
  12823. } else {
  12824. const err = await res.text();
  12825. showToast('Error', err, 'error');
  12826. }
  12827. } catch (err) {
  12828. showToast('Error', err.message, 'error');
  12829. }
  12830. }
  12831. async function deleteDHCPStaticLease(id) {
  12832. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12833. try {
  12834. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12835. if (res.ok) {
  12836. showToast('Deleted', 'Static lease removed', 'success');
  12837. loadDHCPServer(false);
  12838. fetchData(false);
  12839. }
  12840. } catch (err) {
  12841. showToast('Error', err.message, 'error');
  12842. }
  12843. }
  12844. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12845. try {
  12846. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12847. method: 'POST',
  12848. headers: { 'Content-Type': 'application/json' },
  12849. body: JSON.stringify({
  12850. mac_address: mac,
  12851. address: ip,
  12852. hostname,
  12853. comment: comment || 'Converted to static'
  12854. })
  12855. });
  12856. if (res.ok) {
  12857. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12858. loadDHCPServer(false);
  12859. fetchData(false);
  12860. } else {
  12861. const err = await res.text();
  12862. showToast('Error', err, 'error');
  12863. }
  12864. } catch (err) {
  12865. showToast('Error', err.message, 'error');
  12866. }
  12867. }
  12868. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12869. function openAddDHCPOptionModal() {
  12870. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12871. document.getElementById('dhcp-option-modal-id').value = '';
  12872. document.getElementById('dhcp-option-modal-name').value = '';
  12873. document.getElementById('dhcp-option-modal-code').value = '';
  12874. document.getElementById('dhcp-option-modal-value').value = '';
  12875. document.getElementById('dhcp-option-modal-comment').value = '';
  12876. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12877. }
  12878. function openEditDHCPOptionModal(id) {
  12879. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12880. if (!o) return;
  12881. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12882. document.getElementById('dhcp-option-modal-id').value = o.id;
  12883. document.getElementById('dhcp-option-modal-name').value = o.name;
  12884. document.getElementById('dhcp-option-modal-code').value = o.code;
  12885. document.getElementById('dhcp-option-modal-value').value = o.value;
  12886. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12887. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12888. }
  12889. function closeDHCPOptionModal() {
  12890. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12891. }
  12892. async function submitSaveDHCPOption(e) {
  12893. e.preventDefault();
  12894. const id = document.getElementById('dhcp-option-modal-id').value;
  12895. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12896. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12897. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12898. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12899. try {
  12900. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12901. method: 'POST',
  12902. headers: { 'Content-Type': 'application/json' },
  12903. body: JSON.stringify({ id, name, code, value, comment })
  12904. });
  12905. if (res.ok) {
  12906. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12907. closeDHCPOptionModal();
  12908. loadDHCPServer(false);
  12909. fetchData(false);
  12910. } else {
  12911. const err = await res.text();
  12912. showToast('Error', err, 'error');
  12913. }
  12914. } catch (err) {
  12915. showToast('Error', err.message, 'error');
  12916. }
  12917. }
  12918. async function deleteDHCPOption(id, name) {
  12919. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12920. try {
  12921. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12922. if (res.ok) {
  12923. showToast('Deleted', `Option ${name} removed`, 'success');
  12924. loadDHCPServer(false);
  12925. fetchData(false);
  12926. }
  12927. } catch (err) {
  12928. showToast('Error', err.message, 'error');
  12929. }
  12930. }
  12931. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12932. function openDHCPServerSetupModal() {
  12933. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12934. onDHCPWizardIfaceChange();
  12935. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12936. }
  12937. function closeDHCPServerSetupModal() {
  12938. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12939. }
  12940. function onDHCPWizardIfaceChange() {
  12941. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12942. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12943. let ip = '192.168.88.1';
  12944. let prefix = '24';
  12945. if (iface && iface.ip_address) {
  12946. const parts = iface.ip_address.split('/');
  12947. ip = parts[0];
  12948. if (parts.length > 1) prefix = parts[1];
  12949. }
  12950. // Calculate subnet base (e.g. 192.168.88.0/24)
  12951. const ipParts = ip.split('.');
  12952. if (ipParts.length === 4) {
  12953. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12954. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12955. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12956. document.getElementById('dhcp-wizard-gateway').value = ip;
  12957. document.getElementById('dhcp-wizard-pool').value = pool;
  12958. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12959. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12960. }
  12961. }
  12962. async function submitDHCPServerSetupWizard(e) {
  12963. e.preventDefault();
  12964. const iface = document.getElementById('dhcp-wizard-iface').value;
  12965. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12966. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12967. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12968. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12969. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12970. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12971. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12972. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12973. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12974. try {
  12975. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12976. method: 'POST',
  12977. headers: { 'Content-Type': 'application/json' },
  12978. body: JSON.stringify({
  12979. interface: iface,
  12980. address_space: space,
  12981. gateway: gw,
  12982. address_pool: pool,
  12983. dns_servers: dnsServers,
  12984. lease_time: leaseTime,
  12985. ntp_servers: ntpServers,
  12986. next_server: tftp
  12987. })
  12988. });
  12989. if (res.ok) {
  12990. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12991. closeDHCPServerSetupModal();
  12992. loadDHCPServer(false);
  12993. fetchData(false);
  12994. } else {
  12995. const err = await res.text();
  12996. showToast('Error', err, 'error');
  12997. }
  12998. } catch (err) {
  12999. showToast('Error', err.message, 'error');
  13000. }
  13001. }
  13002. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13003. const sel = document.getElementById(elemId);
  13004. if (!sel) return;
  13005. sel.innerHTML = '<option value="">Select interface...</option>';
  13006. const ifaces = state.interfaces || [];
  13007. ifaces.forEach(i => {
  13008. if (i.name === 'lo') return;
  13009. const opt = document.createElement('option');
  13010. opt.value = i.name;
  13011. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13012. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13013. if (i.name === selectedVal) opt.selected = true;
  13014. sel.appendChild(opt);
  13015. });
  13016. }
  13017. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13018. function initTableSorting() {
  13019. document.querySelectorAll('table').forEach(setupSortableTable);
  13020. }
  13021. function setupSortableTable(table) {
  13022. const thead = table.querySelector('thead');
  13023. const tbody = table.querySelector('tbody');
  13024. if (!thead || !tbody) return;
  13025. const headerRows = thead.querySelectorAll('tr');
  13026. if (headerRows.length === 0) return;
  13027. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13028. ths.forEach((th, colIdx) => {
  13029. if (th._sortBound) return;
  13030. th._sortBound = true;
  13031. const rawText = th.innerText.trim().toLowerCase();
  13032. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13033. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13034. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13035. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13036. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13037. return;
  13038. }
  13039. th.classList.add('table-sortable', 'group');
  13040. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13041. let icon = th.querySelector('.table-sort-icon');
  13042. if (!icon) {
  13043. icon = document.createElement('span');
  13044. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13045. icon.innerHTML = '⇅';
  13046. th.appendChild(icon);
  13047. }
  13048. th.addEventListener('click', (e) => {
  13049. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13050. handleHeaderClick(table, th, colIdx);
  13051. });
  13052. });
  13053. if (!tbody._sortObserved) {
  13054. tbody._sortObserved = true;
  13055. let sortDebounceTimer = null;
  13056. const observer = new MutationObserver((mutations) => {
  13057. if (tbody._isSorting) return;
  13058. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13059. if (!hasChildChanges) return;
  13060. clearTimeout(sortDebounceTimer);
  13061. sortDebounceTimer = setTimeout(() => {
  13062. if (tbody._isSorting) return;
  13063. if (table._activeSort && table._activeSort.dir !== 'none') {
  13064. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13065. } else {
  13066. tagOriginalRowOrder(tbody);
  13067. }
  13068. }, 50);
  13069. });
  13070. tbody._sortObserver = observer;
  13071. observer.observe(tbody, { childList: true });
  13072. }
  13073. tagOriginalRowOrder(tbody);
  13074. }
  13075. function tagOriginalRowOrder(tbody) {
  13076. let idx = 0;
  13077. Array.from(tbody.children).forEach(tr => {
  13078. if (!tr.querySelector('td[colspan]')) {
  13079. if (!tr.hasAttribute('data-orig-idx')) {
  13080. tr.setAttribute('data-orig-idx', idx++);
  13081. }
  13082. }
  13083. });
  13084. }
  13085. function handleHeaderClick(table, th, colIdx) {
  13086. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13087. let newDir = 'asc';
  13088. if (currentSort.colIdx === colIdx) {
  13089. if (currentSort.dir === 'asc') newDir = 'desc';
  13090. else if (currentSort.dir === 'desc') newDir = 'none';
  13091. else newDir = 'asc';
  13092. } else {
  13093. newDir = 'asc';
  13094. }
  13095. table._activeSort = { colIdx, dir: newDir };
  13096. updateHeaderIcons(table, colIdx, newDir);
  13097. applyTableSort(table, colIdx, newDir, true);
  13098. }
  13099. function updateHeaderIcons(table, activeColIdx, dir) {
  13100. const thead = table.querySelector('thead');
  13101. if (!thead) return;
  13102. const ths = thead.querySelectorAll('th');
  13103. ths.forEach((th, idx) => {
  13104. const icon = th.querySelector('.table-sort-icon');
  13105. if (!icon) return;
  13106. if (idx === activeColIdx && dir !== 'none') {
  13107. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13108. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13109. th.classList.add('table-sorted-active');
  13110. } else {
  13111. icon.innerHTML = '⇅';
  13112. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13113. th.classList.remove('table-sorted-active');
  13114. }
  13115. });
  13116. }
  13117. function applyTableSort(table, colIdx, dir, userInitiated) {
  13118. const tbody = table.querySelector('tbody');
  13119. if (!tbody || tbody.children.length <= 1) return;
  13120. tbody._isSorting = true;
  13121. tagOriginalRowOrder(tbody);
  13122. // Group parent rows and any attached drawer/sub-rows
  13123. const groups = [];
  13124. let currentGroup = null;
  13125. Array.from(tbody.children).forEach(tr => {
  13126. if (tr.querySelector('td[colspan]')) {
  13127. if (currentGroup) {
  13128. currentGroup.subRows.push(tr);
  13129. } else {
  13130. groups.push({ mainRow: tr, subRows: [] });
  13131. }
  13132. } else {
  13133. currentGroup = { mainRow: tr, subRows: [] };
  13134. groups.push(currentGroup);
  13135. }
  13136. });
  13137. if (dir === 'none') {
  13138. groups.sort((a, b) => {
  13139. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13140. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13141. return idxA - idxB;
  13142. });
  13143. } else {
  13144. groups.sort((a, b) => {
  13145. const cellA = a.mainRow.children[colIdx];
  13146. const cellB = b.mainRow.children[colIdx];
  13147. const res = compareTableCells(cellA, cellB);
  13148. return dir === 'asc' ? res : -res;
  13149. });
  13150. }
  13151. // Check if rows are already in correct order to avoid modifying DOM
  13152. let alreadyOrdered = true;
  13153. let childIdx = 0;
  13154. for (const g of groups) {
  13155. if (tbody.children[childIdx] !== g.mainRow) {
  13156. alreadyOrdered = false;
  13157. break;
  13158. }
  13159. childIdx++;
  13160. for (const sub of g.subRows) {
  13161. if (tbody.children[childIdx] !== sub) {
  13162. alreadyOrdered = false;
  13163. break;
  13164. }
  13165. childIdx++;
  13166. }
  13167. }
  13168. if (alreadyOrdered) {
  13169. tbody._isSorting = false;
  13170. return;
  13171. }
  13172. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13173. if (tbody._sortObserver) {
  13174. tbody._sortObserver.disconnect();
  13175. }
  13176. // Re-append rows in sorted order
  13177. groups.forEach(g => {
  13178. tbody.appendChild(g.mainRow);
  13179. g.subRows.forEach(sub => tbody.appendChild(sub));
  13180. });
  13181. // Drain any queued mutations and re-connect observer
  13182. if (tbody._sortObserver) {
  13183. tbody._sortObserver.takeRecords();
  13184. tbody._sortObserver.observe(tbody, { childList: true });
  13185. }
  13186. tbody._isSorting = false;
  13187. }
  13188. function getCellRawText(cell) {
  13189. if (!cell) return '';
  13190. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13191. const input = cell.querySelector('input, select');
  13192. if (input) {
  13193. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13194. return input.value;
  13195. }
  13196. return cell.innerText.trim();
  13197. }
  13198. function parseTrafficToNumber(str) {
  13199. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13200. if (!m) return null;
  13201. const num = parseFloat(m[1].replace(/,/g, ''));
  13202. if (isNaN(num)) return null;
  13203. const unit = m[2].toUpperCase();
  13204. let mult = 1;
  13205. if (unit.startsWith('K')) mult = 1024;
  13206. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13207. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13208. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13209. return num * mult;
  13210. }
  13211. function parseIpToNumber(str) {
  13212. const clean = str.replace(/^[!~]/, '').trim();
  13213. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13214. if (!m) return null;
  13215. const o1 = parseInt(m[1], 10);
  13216. const o2 = parseInt(m[2], 10);
  13217. const o3 = parseInt(m[3], 10);
  13218. const o4 = parseInt(m[4], 10);
  13219. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13220. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13221. }
  13222. function parseCompoundPackets(str) {
  13223. const m = str.match(/^([\d,]+)p/);
  13224. if (!m) return null;
  13225. return parseInt(m[1].replace(/,/g, ''), 10);
  13226. }
  13227. function compareTableCells(cellA, cellB) {
  13228. const a = getCellRawText(cellA);
  13229. const b = getCellRawText(cellB);
  13230. if (a === '' && b !== '') return 1;
  13231. if (b === '' && a !== '') return -1;
  13232. if (a === b) return 0;
  13233. // 1. IP Addresses / CIDR
  13234. const ipA = parseIpToNumber(a);
  13235. const ipB = parseIpToNumber(b);
  13236. if (ipA !== null && ipB !== null) return ipA - ipB;
  13237. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13238. const pktA = parseCompoundPackets(a);
  13239. const pktB = parseCompoundPackets(b);
  13240. if (pktA !== null && pktB !== null) return pktA - pktB;
  13241. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13242. const trafA = parseTrafficToNumber(a);
  13243. const trafB = parseTrafficToNumber(b);
  13244. if (trafA !== null && trafB !== null) return trafA - trafB;
  13245. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13246. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13247. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13248. const numA = Number(cleanNumA);
  13249. const numB = Number(cleanNumB);
  13250. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13251. return numA - numB;
  13252. }
  13253. // 5. Natural case-insensitive string compare
  13254. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13255. }
  13256. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13257. async function loadVRRP(showToastNotification = false) {
  13258. try {
  13259. const [instRes, sumRes] = await Promise.all([
  13260. fetch(`${API_BASE}/vrrp/instances`),
  13261. fetch(`${API_BASE}/vrrp/summary`)
  13262. ]);
  13263. if (instRes.ok) {
  13264. state.vrrpInstances = await instRes.json();
  13265. renderVRRP();
  13266. }
  13267. if (sumRes.ok) {
  13268. state.vrrpSummary = await sumRes.json();
  13269. renderVRRPSummary();
  13270. }
  13271. if (showToastNotification) {
  13272. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13273. }
  13274. } catch (err) {
  13275. console.error('Failed to load VRRP:', err);
  13276. }
  13277. }
  13278. function renderVRRPSummary() {
  13279. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13280. const elTotal = document.getElementById('vrrp-stat-total');
  13281. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13282. const elMaster = document.getElementById('vrrp-stat-master');
  13283. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13284. const elBackup = document.getElementById('vrrp-stat-backup');
  13285. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13286. const bCount = document.getElementById('badge-vrrp-count');
  13287. if (bCount) bCount.innerText = s.total_instances || 0;
  13288. const dot = document.getElementById('badge-vrrp-dot');
  13289. if (dot) {
  13290. if (s.master_instances > 0) {
  13291. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13292. } else if (s.backup_instances > 0) {
  13293. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13294. } else {
  13295. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13296. }
  13297. }
  13298. }
  13299. function renderVRRP() {
  13300. const tbody = document.getElementById('vrrp-table-tbody');
  13301. const empty = document.getElementById('vrrp-table-empty');
  13302. if (!tbody) return;
  13303. tbody.innerHTML = '';
  13304. const instances = state.vrrpInstances || [];
  13305. if (instances.length === 0) {
  13306. empty?.classList.remove('hidden');
  13307. return;
  13308. }
  13309. empty?.classList.add('hidden');
  13310. instances.forEach(inst => {
  13311. const tr = document.createElement('tr');
  13312. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13313. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13314. 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>`;
  13315. if (inst.disabled) {
  13316. 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>`;
  13317. } else if (inst.state === 'MASTER') {
  13318. 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>`;
  13319. } else if (inst.state === 'BACKUP') {
  13320. 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>`;
  13321. } else if (inst.state === 'FAULT') {
  13322. 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>`;
  13323. }
  13324. // Render State Badge
  13325. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13326. if (!inst.disabled) {
  13327. if (inst.state === 'MASTER') {
  13328. 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>`;
  13329. } else if (inst.state === 'BACKUP') {
  13330. 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>`;
  13331. } else if (inst.state === 'FAULT') {
  13332. 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>`;
  13333. }
  13334. }
  13335. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13336. tr.innerHTML = `
  13337. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13338. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13339. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13340. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13341. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13342. <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>
  13343. <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>
  13344. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13345. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13346. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13347. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13348. <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>
  13349. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13350. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13351. </td>
  13352. `;
  13353. tbody.appendChild(tr);
  13354. });
  13355. }
  13356. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13357. const sel = document.getElementById(elemId);
  13358. if (!sel) return;
  13359. sel.innerHTML = '<option value="">Select interface...</option>';
  13360. const ifaces = state.interfaces || [];
  13361. ifaces.forEach(i => {
  13362. const opt = document.createElement('option');
  13363. opt.value = i.name;
  13364. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13365. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13366. sel.appendChild(opt);
  13367. });
  13368. }
  13369. function openAddVRRPModal() {
  13370. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13371. document.getElementById('modal-vrrp-id').value = '';
  13372. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13373. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13374. document.getElementById('modal-vrrp-priority').value = 100;
  13375. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13376. document.getElementById('modal-vrrp-version').value = '3';
  13377. document.getElementById('modal-vrrp-interval').value = 1;
  13378. document.getElementById('modal-vrrp-authtype').value = 'none';
  13379. document.getElementById('modal-vrrp-authpass').value = '';
  13380. document.getElementById('modal-vrrp-comment').value = '';
  13381. document.getElementById('modal-vrrp-preempt').checked = true;
  13382. document.getElementById('modal-vrrp-disabled').checked = false;
  13383. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13384. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13385. }
  13386. function openEditVRRPModal(id) {
  13387. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13388. if (!inst) return;
  13389. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13390. document.getElementById('modal-vrrp-id').value = inst.id;
  13391. document.getElementById('modal-vrrp-name').value = inst.name;
  13392. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13393. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13394. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13395. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13396. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13397. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13398. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13399. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13400. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13401. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13402. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13403. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13404. }
  13405. function closeVRRPModal() {
  13406. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13407. }
  13408. async function submitSaveVRRP(e) {
  13409. e.preventDefault();
  13410. const id = document.getElementById('modal-vrrp-id').value;
  13411. const name = document.getElementById('modal-vrrp-name').value.trim();
  13412. const iface = document.getElementById('modal-vrrp-iface').value;
  13413. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13414. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13415. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13416. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13417. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13418. const authType = document.getElementById('modal-vrrp-authtype').value;
  13419. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13420. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13421. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13422. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13423. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13424. try {
  13425. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13426. method: 'POST',
  13427. headers: { 'Content-Type': 'application/json' },
  13428. body: JSON.stringify({
  13429. id,
  13430. name,
  13431. interface: iface,
  13432. vrid,
  13433. priority,
  13434. virtual_ips: vips,
  13435. version,
  13436. interval,
  13437. auth_type: authType,
  13438. auth_password: authPass,
  13439. comment,
  13440. preempt,
  13441. disabled
  13442. })
  13443. });
  13444. if (res.ok) {
  13445. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13446. closeVRRPModal();
  13447. loadVRRP(false);
  13448. fetchData(false);
  13449. } else {
  13450. const err = await res.text();
  13451. showToast('Error', err, 'error');
  13452. }
  13453. } catch (err) {
  13454. showToast('Error', err.message, 'error');
  13455. }
  13456. }
  13457. async function deleteVRRP(id, name) {
  13458. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13459. try {
  13460. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13461. if (res.ok) {
  13462. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13463. loadVRRP(false);
  13464. fetchData(false);
  13465. } else {
  13466. const err = await res.text();
  13467. showToast('Error', err, 'error');
  13468. }
  13469. } catch (err) {
  13470. showToast('Error', err.message, 'error');
  13471. }
  13472. }
  13473. async function toggleVRRPState(id, disabled) {
  13474. try {
  13475. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13476. method: 'POST',
  13477. headers: { 'Content-Type': 'application/json' },
  13478. body: JSON.stringify({ disabled })
  13479. });
  13480. if (res.ok) {
  13481. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13482. loadVRRP(false);
  13483. fetchData(false);
  13484. } else {
  13485. const err = await res.text();
  13486. showToast('Error', err, 'error');
  13487. }
  13488. } catch (err) {
  13489. showToast('Error', err.message, 'error');
  13490. }
  13491. }
  13492. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13493. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13494. let docSortDebounce = null;
  13495. const docTableObserver = new MutationObserver((mutations) => {
  13496. let needsInit = false;
  13497. for (const m of mutations) {
  13498. for (const node of m.addedNodes) {
  13499. if (node.nodeType === 1) {
  13500. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13501. needsInit = true;
  13502. break;
  13503. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13504. needsInit = true;
  13505. break;
  13506. }
  13507. }
  13508. }
  13509. if (needsInit) break;
  13510. }
  13511. if (needsInit) {
  13512. clearTimeout(docSortDebounce);
  13513. docSortDebounce = setTimeout(initTableSorting, 100);
  13514. }
  13515. });
  13516. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13517. }
  13518. // =========================================================================
  13519. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13520. // =========================================================================
  13521. const bwtestState = {
  13522. running: false,
  13523. pollTimer: null,
  13524. eventSource: null,
  13525. chartPoints: [],
  13526. maxChartPoints: 60,
  13527. serverConfig: null,
  13528. peakTx: 0,
  13529. peakRx: 0,
  13530. targetDuration: 10,
  13531. lastSampleElapsed: -1,
  13532. sessionID: null
  13533. };
  13534. async function loadBwTestView() {
  13535. resizeBwTestCanvas();
  13536. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13537. }
  13538. async function fetchBwTestServerStatus() {
  13539. try {
  13540. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13541. if (!res.ok) return;
  13542. const s = await res.json();
  13543. bwtestState.serverConfig = s;
  13544. // Update indicator and badges
  13545. const indicator = document.getElementById('bwtest-server-indicator');
  13546. const badge = document.getElementById('bwtest-server-badge');
  13547. const sideBadge = document.getElementById('badge-bwtest-server');
  13548. if (s.enabled && s.running) {
  13549. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13550. if (badge) {
  13551. badge.innerText = `Port ${s.port} (Active)`;
  13552. badge.className = 'text-emerald-400 font-bold';
  13553. }
  13554. if (sideBadge) {
  13555. sideBadge.innerText = s.port;
  13556. 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';
  13557. }
  13558. } else {
  13559. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13560. if (badge) {
  13561. badge.innerText = `Disabled`;
  13562. badge.className = 'text-slate-500 font-bold';
  13563. }
  13564. if (sideBadge) {
  13565. sideBadge.innerText = 'Off';
  13566. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13567. }
  13568. }
  13569. // Modal fields
  13570. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13571. const serverModal = document.getElementById('modal-bwtest-server');
  13572. const editing = serverModal && !serverModal.classList.contains('hidden');
  13573. if (toggle && !editing) toggle.checked = !!s.enabled;
  13574. const portInp = document.getElementById('bwtest-server-port-input');
  13575. if (portInp && !editing) portInp.value = s.port || 2000;
  13576. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13577. if (actSess) actSess.innerText = s.active_sessions || 0;
  13578. const totServ = document.getElementById('bwtest-modal-total-served');
  13579. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13580. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13581. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13582. } catch (err) {
  13583. console.error('Failed to fetch BwTest server status:', err);
  13584. }
  13585. }
  13586. function openBwTestServerModal() {
  13587. const cfg = bwtestState.serverConfig;
  13588. if (cfg) {
  13589. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13590. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13591. }
  13592. fetchBwTestServerStatus();
  13593. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13594. }
  13595. function closeBwTestServerModal() {
  13596. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13597. }
  13598. async function submitBwTestServerSettings(e) {
  13599. e.preventDefault();
  13600. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13601. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13602. try {
  13603. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13604. method: 'POST',
  13605. headers: { 'Content-Type': 'application/json' },
  13606. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13607. });
  13608. if (!res.ok) {
  13609. const err = await res.json();
  13610. throw new Error(err.error || 'Failed to update server configuration');
  13611. }
  13612. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13613. closeBwTestServerModal();
  13614. fetchBwTestServerStatus();
  13615. } catch (err) {
  13616. showToast('Server Configuration Error', err.message, 'error');
  13617. }
  13618. }
  13619. function setBwTestTarget(target) {
  13620. const inp = document.getElementById('bwtest-input-target');
  13621. if (inp) inp.value = target;
  13622. }
  13623. function setBwTestProtocol(proto) {
  13624. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13625. if (hiddenInp) hiddenInp.value = proto;
  13626. const btnUdp = document.getElementById('bwtest-proto-udp');
  13627. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13628. const badge = document.getElementById('bwtest-proto-badge');
  13629. const pktField = document.getElementById('bwtest-field-pktsize');
  13630. 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';
  13631. 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';
  13632. 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';
  13633. if (proto === 'udp') {
  13634. if (btnUdp) {
  13635. btnUdp.className = activeUdpCls;
  13636. const dot = btnUdp.querySelector('span');
  13637. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13638. }
  13639. if (btnTcp) {
  13640. btnTcp.className = inactiveCls;
  13641. const dot = btnTcp.querySelector('span');
  13642. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13643. }
  13644. if (badge) {
  13645. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13646. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13647. }
  13648. if (pktField) pktField.classList.remove('opacity-40');
  13649. } else {
  13650. if (btnUdp) {
  13651. btnUdp.className = inactiveCls;
  13652. const dot = btnUdp.querySelector('span');
  13653. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13654. }
  13655. if (btnTcp) {
  13656. btnTcp.className = activeTcpCls;
  13657. const dot = btnTcp.querySelector('span');
  13658. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13659. }
  13660. if (badge) {
  13661. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13662. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13663. }
  13664. if (pktField) pktField.classList.add('opacity-40');
  13665. }
  13666. }
  13667. function setBwTestDirection(dir) {
  13668. const hiddenInp = document.getElementById('bwtest-input-direction');
  13669. if (hiddenInp) hiddenInp.value = dir;
  13670. const btnBoth = document.getElementById('bwtest-dir-both');
  13671. const btnTx = document.getElementById('bwtest-dir-tx');
  13672. const btnRx = document.getElementById('bwtest-dir-rx');
  13673. 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';
  13674. 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';
  13675. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13676. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13677. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13678. }
  13679. function setBwTestLimit(bps) {
  13680. const sel = document.getElementById('bwtest-input-limit');
  13681. if (sel) sel.value = String(bps);
  13682. }
  13683. async function checkActiveBwTest() {
  13684. try {
  13685. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13686. if (!res.ok) return;
  13687. const st = await res.json();
  13688. if (st.running) {
  13689. setBwTestRunningUI(true);
  13690. processBwTestStatus(st);
  13691. startBwTestTelemetry();
  13692. }
  13693. } catch (err) {
  13694. console.error('Failed to check active BwTest:', err);
  13695. }
  13696. }
  13697. async function startBwTest(e) {
  13698. if (e && e.preventDefault) e.preventDefault();
  13699. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13700. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13701. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13702. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13703. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13704. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13705. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13706. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13707. bwtestState.targetDuration = duration;
  13708. bwtestState.chartPoints = [];
  13709. bwtestState.peakTx = 0;
  13710. bwtestState.peakRx = 0;
  13711. bwtestState.lastSampleElapsed = -1;
  13712. bwtestState.sessionID = null;
  13713. // Clear UI elements
  13714. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13715. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13716. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13717. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13718. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13719. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13720. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13721. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13722. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13723. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13724. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13725. const tbody = document.getElementById('bwtest-samples-tbody');
  13726. if (tbody) tbody.innerHTML = '';
  13727. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13728. setBwTestRunningUI(true);
  13729. try {
  13730. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13731. method: 'POST',
  13732. headers: { 'Content-Type': 'application/json' },
  13733. body: JSON.stringify({
  13734. target,
  13735. port,
  13736. direction,
  13737. protocol,
  13738. bandwidth_limit,
  13739. packet_size,
  13740. streams,
  13741. duration
  13742. })
  13743. });
  13744. if (!res.ok) {
  13745. const err = await res.json();
  13746. throw new Error(err.error || 'Failed to start bandwidth test');
  13747. }
  13748. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13749. startBwTestTelemetry();
  13750. } catch (err) {
  13751. setBwTestRunningUI(false);
  13752. showToast('Start Failed', err.message, 'error');
  13753. }
  13754. }
  13755. function setBwTestRunningUI(running) {
  13756. bwtestState.running = running;
  13757. const startBtn = document.getElementById('bwtest-btn-start');
  13758. const stopBtn = document.getElementById('bwtest-btn-stop');
  13759. const badge = document.getElementById('bwtest-run-status-badge');
  13760. const ph = document.getElementById('bwtest-chart-placeholder');
  13761. if (running) {
  13762. if (startBtn) {
  13763. startBtn.disabled = true;
  13764. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13765. }
  13766. if (stopBtn) {
  13767. stopBtn.disabled = false;
  13768. stopBtn.classList.remove('opacity-40');
  13769. }
  13770. if (badge) {
  13771. badge.innerText = 'TESTING...';
  13772. 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';
  13773. }
  13774. if (ph) ph.style.display = 'none';
  13775. } else {
  13776. if (startBtn) {
  13777. startBtn.disabled = false;
  13778. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13779. }
  13780. if (stopBtn) {
  13781. stopBtn.disabled = true;
  13782. stopBtn.classList.add('opacity-40');
  13783. }
  13784. if (badge) {
  13785. badge.innerText = 'IDLE';
  13786. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13787. }
  13788. }
  13789. }
  13790. async function stopBwTest() {
  13791. try {
  13792. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13793. if (!res.ok) throw new Error(await responseError(res));
  13794. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13795. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13796. } catch (err) {
  13797. showToast('Stop Failed', err.message, 'error');
  13798. }
  13799. }
  13800. async function responseError(res) {
  13801. const text = await res.text();
  13802. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13803. catch { return text || `HTTP ${res.status}`; }
  13804. }
  13805. function processBwTestStatus(st) {
  13806. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13807. bwtestState.sessionID = st.session_id;
  13808. bwtestState.lastSampleElapsed = -1;
  13809. }
  13810. for (const sample of st.recent_samples || []) {
  13811. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13812. handleBwTestSample(sample);
  13813. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13814. }
  13815. }
  13816. if (!st.running) {
  13817. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13818. bwtestState.pollTimer = null;
  13819. setBwTestRunningUI(false);
  13820. handleBwTestFinish(st.summary, st.error);
  13821. }
  13822. }
  13823. function startBwTestTelemetry() {
  13824. if (!state.currentUser) return;
  13825. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13826. let busy = false;
  13827. const poll = async () => {
  13828. if (busy || !state.currentUser || document.hidden) return;
  13829. busy = true;
  13830. try {
  13831. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13832. if (!res.ok) throw new Error(await responseError(res));
  13833. processBwTestStatus(await res.json());
  13834. } catch (err) {
  13835. console.error('BwTest polling error:', err);
  13836. } finally { busy = false; }
  13837. };
  13838. bwtestState.pollTimer = setInterval(poll, 400);
  13839. poll();
  13840. }
  13841. function handleBwTestSample(s) {
  13842. if (!s) return;
  13843. const payloadHint = document.getElementById('bwtest-effective-payload');
  13844. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13845. const txMbps = s.tx_mbps || 0;
  13846. const rxMbps = s.rx_mbps || 0;
  13847. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13848. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13849. // KPI updates
  13850. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13851. if (elTx) {
  13852. elTx.innerText = txMbps.toFixed(2);
  13853. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13854. }
  13855. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13856. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13857. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13858. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13859. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13860. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13861. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13862. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13863. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13864. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13865. const elLoss = document.getElementById('bwtest-stat-loss');
  13866. if (elLoss) {
  13867. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13868. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13869. }
  13870. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13871. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13872. const elJitter = document.getElementById('bwtest-stat-jitter');
  13873. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13874. const elTime = document.getElementById('bwtest-stat-time');
  13875. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13876. const elData = document.getElementById('bwtest-stat-data');
  13877. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13878. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13879. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13880. // Append point to chart buffer
  13881. bwtestState.chartPoints.push({
  13882. elapsed: s.elapsed_sec || 0,
  13883. tx: txMbps,
  13884. rx: rxMbps
  13885. });
  13886. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13887. bwtestState.chartPoints.shift();
  13888. }
  13889. drawBwTestChart();
  13890. // Add row to breakdown table
  13891. const tbody = document.getElementById('bwtest-samples-tbody');
  13892. if (tbody) {
  13893. const tr = document.createElement('tr');
  13894. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13895. tr.innerHTML = `
  13896. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13897. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13898. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13899. <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>
  13900. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13901. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13902. `;
  13903. tbody.insertBefore(tr, tbody.firstChild);
  13904. const countEl = document.getElementById('bwtest-sample-count');
  13905. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13906. }
  13907. }
  13908. function handleBwTestFinish(summary, error) {
  13909. const badge = document.getElementById('bwtest-run-status-badge');
  13910. if (error) {
  13911. showToast('Benchmark Error', error, 'error');
  13912. if (badge) {
  13913. badge.innerText = 'ERROR';
  13914. 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';
  13915. }
  13916. } else if (summary) {
  13917. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13918. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13919. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13920. if (badge) {
  13921. badge.innerText = 'COMPLETED';
  13922. 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';
  13923. }
  13924. }
  13925. loadBwTestHistory();
  13926. fetchBwTestServerStatus();
  13927. }
  13928. function resizeBwTestCanvas() {
  13929. const canvas = document.getElementById('bwtest-chart');
  13930. if (!canvas || !canvas.parentElement) return;
  13931. const rect = canvas.parentElement.getBoundingClientRect();
  13932. const dpr = window.devicePixelRatio || 1;
  13933. canvas.width = rect.width * dpr;
  13934. canvas.height = rect.height * dpr;
  13935. const ctx = canvas.getContext('2d');
  13936. ctx.scale(dpr, dpr);
  13937. drawBwTestChart();
  13938. }
  13939. window.addEventListener('resize', () => {
  13940. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13941. });
  13942. function drawBwTestChart() {
  13943. const canvas = document.getElementById('bwtest-chart');
  13944. if (!canvas) return;
  13945. const ctx = canvas.getContext('2d');
  13946. const dpr = window.devicePixelRatio || 1;
  13947. const width = canvas.width / dpr;
  13948. const height = canvas.height / dpr;
  13949. ctx.clearRect(0, 0, width, height);
  13950. const points = bwtestState.chartPoints;
  13951. if (!points || points.length === 0) return;
  13952. // Determine scale ceiling
  13953. let maxRate = 10;
  13954. for (const p of points) {
  13955. if (p.tx > maxRate) maxRate = p.tx;
  13956. if (p.rx > maxRate) maxRate = p.rx;
  13957. }
  13958. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13959. const paddingLeft = 55;
  13960. const paddingBottom = 24;
  13961. const paddingTop = 12;
  13962. const paddingRight = 16;
  13963. const chartW = width - paddingLeft - paddingRight;
  13964. const chartH = height - paddingTop - paddingBottom;
  13965. // Grid Lines and Y-Axis labels
  13966. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13967. ctx.lineWidth = 1;
  13968. ctx.fillStyle = '#94a3b8';
  13969. ctx.font = '10px monospace';
  13970. ctx.textAlign = 'right';
  13971. const gridSteps = 4;
  13972. for (let i = 0; i <= gridSteps; i++) {
  13973. const val = (maxRate / gridSteps) * i;
  13974. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13975. ctx.beginPath();
  13976. ctx.moveTo(paddingLeft, y);
  13977. ctx.lineTo(width - paddingRight, y);
  13978. ctx.stroke();
  13979. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13980. }
  13981. // Draw TX Line (Cyan #22d3ee)
  13982. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13983. // Draw RX Line (Purple #a855f7)
  13984. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13985. }
  13986. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13987. if (points.length < 2) return;
  13988. const stepX = w / Math.max(points.length - 1, 1);
  13989. // Gradient area fill
  13990. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13991. grad.addColorStop(0, fillColor);
  13992. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13993. ctx.beginPath();
  13994. points.forEach((p, idx) => {
  13995. const x = left + idx * stepX;
  13996. const val = valFn(p);
  13997. const y = top + h - (val / maxVal) * h;
  13998. if (idx === 0) {
  13999. ctx.moveTo(x, y);
  14000. } else {
  14001. ctx.lineTo(x, y);
  14002. }
  14003. });
  14004. // Complete path for fill
  14005. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14006. ctx.lineTo(left, top + h);
  14007. ctx.closePath();
  14008. ctx.fillStyle = grad;
  14009. ctx.fill();
  14010. // Draw line stroke
  14011. ctx.beginPath();
  14012. ctx.lineWidth = 2.5;
  14013. ctx.strokeStyle = strokeColor;
  14014. points.forEach((p, idx) => {
  14015. const x = left + idx * stepX;
  14016. const val = valFn(p);
  14017. const y = top + h - (val / maxVal) * h;
  14018. if (idx === 0) {
  14019. ctx.moveTo(x, y);
  14020. } else {
  14021. ctx.lineTo(x, y);
  14022. }
  14023. });
  14024. ctx.stroke();
  14025. // Draw end point halo
  14026. const lastP = points[points.length - 1];
  14027. const lastX = left + (points.length - 1) * stepX;
  14028. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14029. ctx.fillStyle = strokeColor;
  14030. ctx.beginPath();
  14031. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14032. ctx.fill();
  14033. }
  14034. async function loadBwTestHistory() {
  14035. try {
  14036. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14037. if (!res.ok) return;
  14038. const list = await res.json();
  14039. renderBwTestHistory(Array.isArray(list) ? list : []);
  14040. } catch (err) {
  14041. console.error('Failed to load BwTest history:', err);
  14042. }
  14043. }
  14044. function renderBwTestHistory(list) {
  14045. const tbody = document.getElementById('bwtest-history-tbody');
  14046. if (!tbody) return;
  14047. if (list.length === 0) {
  14048. 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>`;
  14049. return;
  14050. }
  14051. tbody.innerHTML = '';
  14052. list.forEach(item => {
  14053. const s = item.summary || {};
  14054. const tr = document.createElement('tr');
  14055. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14056. const dirBadge = item.direction === 'both'
  14057. ? `<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>`
  14058. : item.direction === 'tx'
  14059. ? `<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>`
  14060. : `<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>`;
  14061. const protoBadge = item.protocol === 'tcp'
  14062. ? `<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>`
  14063. : `<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>`;
  14064. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14065. tr.innerHTML = `
  14066. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14067. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14068. <td class="py-2.5 px-4">${protoBadge}</td>
  14069. <td class="py-2.5 px-4">${dirBadge}</td>
  14070. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14071. <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>
  14072. <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>
  14073. <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>
  14074. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14075. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14076. `;
  14077. tbody.appendChild(tr);
  14078. });
  14079. }
  14080. // ======================== SETTINGS & ROUTER DNS ========================
  14081. state.settingsSubTab = 'dns';
  14082. state.dnsSettings = null;
  14083. state.dnsStaticRecords = [];
  14084. state.dnsStatus = null;
  14085. function switchSettingsSubTab(sub) {
  14086. state.settingsSubTab = sub;
  14087. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14088. const btnSys = document.getElementById('btn-settings-subtab-system');
  14089. const tabDns = document.getElementById('settings-subtab-dns');
  14090. const tabSys = document.getElementById('settings-subtab-system');
  14091. if (sub === 'dns') {
  14092. if (btnDns) {
  14093. 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';
  14094. }
  14095. if (btnSys) {
  14096. 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';
  14097. }
  14098. tabDns?.classList.remove('hidden');
  14099. tabSys?.classList.add('hidden');
  14100. loadDNSSettings();
  14101. } else {
  14102. if (btnSys) {
  14103. 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';
  14104. }
  14105. if (btnDns) {
  14106. 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';
  14107. }
  14108. tabSys?.classList.remove('hidden');
  14109. tabDns?.classList.add('hidden');
  14110. loadSystemSettings();
  14111. }
  14112. }
  14113. async function loadSettingsData(showLoading = false) {
  14114. if (state.settingsSubTab === 'system') {
  14115. await loadSystemSettings();
  14116. } else {
  14117. await loadDNSSettings();
  14118. }
  14119. }
  14120. async function loadDNSSettings() {
  14121. try {
  14122. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14123. fetch(`${API_BASE}/dns/settings`),
  14124. fetch(`${API_BASE}/dns/static`),
  14125. fetch(`${API_BASE}/dns/status`)
  14126. ]);
  14127. if (settingsRes.ok) {
  14128. state.dnsSettings = await settingsRes.json();
  14129. populateDNSSettingsForm(state.dnsSettings);
  14130. }
  14131. if (staticRes.ok) {
  14132. state.dnsStaticRecords = await staticRes.json();
  14133. renderStaticDNSList();
  14134. }
  14135. if (statusRes.ok) {
  14136. state.dnsStatus = await statusRes.json();
  14137. updateDNSStatusView(state.dnsStatus);
  14138. }
  14139. } catch (err) {
  14140. console.error('Failed to load DNS settings:', err);
  14141. }
  14142. }
  14143. function populateDNSSettingsForm(s) {
  14144. if (!s) return;
  14145. const dnsForm = document.getElementById('form-dns-settings');
  14146. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14147. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14148. if (dynamicEl) {
  14149. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14150. 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(' ');
  14151. } else {
  14152. dynamicEl.innerText = 'None';
  14153. }
  14154. }
  14155. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14156. if (isEditing) return;
  14157. const serversInput = document.getElementById('dns-servers-input');
  14158. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14159. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14160. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14161. const domainInput = document.getElementById('dns-domain-input');
  14162. if (domainInput) domainInput.value = s.domain || '';
  14163. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14164. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14165. }
  14166. function updateDNSStatusView(st) {
  14167. if (!st) return;
  14168. const preview = document.getElementById('dns-resolv-preview');
  14169. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14170. const pillText = document.getElementById('dns-live-status-text');
  14171. const pill = document.getElementById('dns-live-status-pill');
  14172. if (pill && pillText) {
  14173. if (st.service_running) {
  14174. 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';
  14175. pillText.innerText = 'DNS Service Active';
  14176. } else {
  14177. 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';
  14178. pillText.innerText = 'DNS Service Inactive';
  14179. }
  14180. }
  14181. }
  14182. function appendDNSPreset(preset) {
  14183. const input = document.getElementById('dns-servers-input');
  14184. if (!input) return;
  14185. const dnsForm = document.getElementById('form-dns-settings');
  14186. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14187. const current = input.value.trim();
  14188. if (!current) {
  14189. input.value = preset;
  14190. } else {
  14191. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14192. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14193. toAdd.forEach(ip => {
  14194. if (!existing.includes(ip)) existing.push(ip);
  14195. });
  14196. input.value = existing.join(', ');
  14197. }
  14198. }
  14199. async function saveDNSSettings(e) {
  14200. e.preventDefault();
  14201. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14202. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14203. if (servers.length === 0) {
  14204. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14205. return;
  14206. }
  14207. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14208. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14209. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14210. try {
  14211. const res = await fetch(`${API_BASE}/dns/settings`, {
  14212. method: 'POST',
  14213. headers: { 'Content-Type': 'application/json' },
  14214. body: JSON.stringify({
  14215. servers: servers,
  14216. cache_size: cacheSize,
  14217. domain: domain,
  14218. allow_remote_requests: allowRemote
  14219. })
  14220. });
  14221. const data = await res.json();
  14222. if (res.ok) {
  14223. const dnsForm = document.getElementById('form-dns-settings');
  14224. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14225. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14226. loadDNSSettings();
  14227. } else {
  14228. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14229. }
  14230. } catch (err) {
  14231. showToast('Error', err.message, 'error');
  14232. }
  14233. }
  14234. async function flushDNSCache() {
  14235. try {
  14236. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14237. if (res.ok) {
  14238. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14239. loadDNSSettings();
  14240. } else {
  14241. const err = await res.json();
  14242. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14243. }
  14244. } catch (err) {
  14245. showToast('Error', err.message, 'error');
  14246. }
  14247. }
  14248. function renderStaticDNSList() {
  14249. const tbody = document.getElementById('dns-static-tbody');
  14250. const empty = document.getElementById('dns-static-empty');
  14251. const badge = document.getElementById('dns-static-count-badge');
  14252. if (!tbody) return;
  14253. tbody.innerHTML = '';
  14254. const records = state.dnsStaticRecords || [];
  14255. if (badge) badge.innerText = `${records.length} Records`;
  14256. if (records.length === 0) {
  14257. empty?.classList.remove('hidden');
  14258. return;
  14259. }
  14260. empty?.classList.add('hidden');
  14261. records.forEach(rec => {
  14262. const tr = document.createElement('tr');
  14263. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14264. tr.innerHTML = `
  14265. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14266. <td class="py-2.5 px-4">
  14267. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14268. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14269. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14270. }">
  14271. ${rec.type || 'A'}
  14272. </span>
  14273. </td>
  14274. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14275. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14276. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14277. <td class="py-2.5 px-4">
  14278. <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'}">
  14279. ${rec.disabled ? 'Disabled' : 'Active'}
  14280. </span>
  14281. </td>
  14282. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14283. <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>
  14284. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14285. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14286. </td>
  14287. `;
  14288. tbody.appendChild(tr);
  14289. });
  14290. }
  14291. function openStaticDNSModal(id = null) {
  14292. const modal = document.getElementById('modal-static-dns');
  14293. const title = document.getElementById('modal-static-dns-title');
  14294. const form = document.getElementById('form-static-dns');
  14295. if (!modal || !form) return;
  14296. form.reset();
  14297. document.getElementById('modal-static-dns-id').value = '';
  14298. if (id) {
  14299. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14300. if (rec) {
  14301. if (title) title.innerText = 'Edit Static DNS Record';
  14302. document.getElementById('modal-static-dns-id').value = rec.id;
  14303. document.getElementById('modal-static-dns-name').value = rec.name;
  14304. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14305. document.getElementById('modal-static-dns-addr').value = rec.address;
  14306. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14307. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14308. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14309. }
  14310. } else {
  14311. if (title) title.innerText = 'Add Static DNS Record';
  14312. }
  14313. modal.classList.remove('hidden');
  14314. }
  14315. function closeStaticDNSModal() {
  14316. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14317. }
  14318. async function submitSaveStaticDNS(e) {
  14319. e.preventDefault();
  14320. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14321. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14322. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14323. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14324. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14325. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14326. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14327. if (!name || !address) {
  14328. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14329. return;
  14330. }
  14331. try {
  14332. const res = await fetch(`${API_BASE}/dns/static`, {
  14333. method: 'POST',
  14334. headers: { 'Content-Type': 'application/json' },
  14335. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14336. });
  14337. const data = await res.json();
  14338. if (res.ok) {
  14339. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14340. closeStaticDNSModal();
  14341. loadDNSSettings();
  14342. } else {
  14343. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14344. }
  14345. } catch (err) {
  14346. showToast('Error', err.message, 'error');
  14347. }
  14348. }
  14349. async function deleteStaticDNS(id) {
  14350. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14351. try {
  14352. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14353. if (res.ok) {
  14354. showToast('Deleted', 'Static DNS record deleted', 'success');
  14355. loadDNSSettings();
  14356. }
  14357. } catch (err) {
  14358. showToast('Error', err.message, 'error');
  14359. }
  14360. }
  14361. async function toggleStaticDNS(id, disabled) {
  14362. try {
  14363. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14364. method: 'POST',
  14365. headers: { 'Content-Type': 'application/json' },
  14366. body: JSON.stringify({ disabled })
  14367. });
  14368. if (res.ok) {
  14369. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14370. loadDNSSettings();
  14371. }
  14372. } catch (err) {
  14373. showToast('Error', err.message, 'error');
  14374. }
  14375. }
  14376. async function loadSystemSettings() {
  14377. try {
  14378. const sysForm = document.getElementById('form-system-settings');
  14379. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14380. const res = await fetch(`${API_BASE}/system/settings`);
  14381. if (res.ok) {
  14382. const data = await res.json();
  14383. if (!isEditing) {
  14384. const hostInput = document.getElementById('system-hostname-input');
  14385. if (hostInput) hostInput.value = data.hostname || '';
  14386. const tzInput = document.getElementById('system-timezone-input');
  14387. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14388. }
  14389. }
  14390. } catch (err) {
  14391. console.error('Failed to load system settings:', err);
  14392. }
  14393. }
  14394. async function saveSystemSettings(e) {
  14395. e.preventDefault();
  14396. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14397. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14398. try {
  14399. const res = await fetch(`${API_BASE}/system/settings`, {
  14400. method: 'POST',
  14401. headers: { 'Content-Type': 'application/json' },
  14402. body: JSON.stringify({ hostname, timezone })
  14403. });
  14404. const data = await res.json();
  14405. if (res.ok) {
  14406. const sysForm = document.getElementById('form-system-settings');
  14407. if (sysForm) sysForm.dataset.dirty = 'false';
  14408. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14409. const sideH = document.getElementById('side-hostname');
  14410. if (sideH) sideH.innerText = data.hostname;
  14411. } else {
  14412. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14413. }
  14414. } catch (err) {
  14415. showToast('Error', err.message, 'error');
  14416. }
  14417. }
  14418. // =============================================================================
  14419. // AUTHENTICATION & USER MANAGER
  14420. // =============================================================================
  14421. async function checkAuthStatus() {
  14422. try {
  14423. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14424. headers: {
  14425. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14426. }
  14427. });
  14428. if (res.ok) {
  14429. const user = await res.json();
  14430. state.currentUser = user;
  14431. updateUserProfileHeader(user);
  14432. hideLoginScreen();
  14433. state.isPolling = true;
  14434. fetchData();
  14435. initLiveTrafficStream();
  14436. return true;
  14437. } else {
  14438. showLoginScreen(false);
  14439. return false;
  14440. }
  14441. } catch (err) {
  14442. showLoginScreen(false);
  14443. return false;
  14444. }
  14445. }
  14446. function showLoginScreen(isExpired = false) {
  14447. const el = document.getElementById('login-screen');
  14448. if (el) el.classList.remove('hidden');
  14449. const errEl = document.getElementById('login-error');
  14450. const errTxt = document.getElementById('login-error-text');
  14451. if (isExpired && errEl && errTxt) {
  14452. errTxt.innerText = 'Session expired. Please sign in again.';
  14453. errEl.classList.remove('hidden');
  14454. } else if (errEl) {
  14455. errEl.classList.add('hidden');
  14456. }
  14457. const pwInput = document.getElementById('login-password');
  14458. if (pwInput) pwInput.value = '';
  14459. const userInput = document.getElementById('login-username');
  14460. if (userInput && !userInput.value) userInput.focus();
  14461. else if (pwInput) pwInput.focus();
  14462. }
  14463. function hideLoginScreen() {
  14464. const el = document.getElementById('login-screen');
  14465. if (el) el.classList.add('hidden');
  14466. const errEl = document.getElementById('login-error');
  14467. if (errEl) errEl.classList.add('hidden');
  14468. }
  14469. async function handleLoginSubmit(event) {
  14470. event.preventDefault();
  14471. const username = (document.getElementById('login-username')?.value || '').trim();
  14472. const password = document.getElementById('login-password')?.value || '';
  14473. const errEl = document.getElementById('login-error');
  14474. const errTxt = document.getElementById('login-error-text');
  14475. const btn = document.getElementById('login-submit-btn');
  14476. const btnText = document.getElementById('login-btn-text');
  14477. const spinner = document.getElementById('login-btn-spinner');
  14478. if (!username || !password) {
  14479. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14480. if (errEl) errEl.classList.remove('hidden');
  14481. return;
  14482. }
  14483. if (errEl) errEl.classList.add('hidden');
  14484. if (btn) btn.disabled = true;
  14485. if (btnText) btnText.innerText = 'Authenticating...';
  14486. if (spinner) spinner.classList.remove('hidden');
  14487. try {
  14488. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14489. method: 'POST',
  14490. headers: { 'Content-Type': 'application/json' },
  14491. body: JSON.stringify({ username, password })
  14492. });
  14493. const data = await res.json();
  14494. if (res.ok && data.success) {
  14495. localStorage.setItem('debtik_token', data.token);
  14496. state.currentUser = data.user;
  14497. updateUserProfileHeader(data.user);
  14498. hideLoginScreen();
  14499. state.isPolling = true;
  14500. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14501. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14502. navigate(hash);
  14503. fetchData();
  14504. initLiveTrafficStream();
  14505. // Ensure background telemetry polling is active
  14506. if (!window._telemetryInterval) {
  14507. window._telemetryInterval = setInterval(() => {
  14508. if (state.isPolling && state.currentUser && !document.hidden) {
  14509. fetchData(false);
  14510. }
  14511. }, 5000);
  14512. }
  14513. } else {
  14514. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14515. if (errEl) errEl.classList.remove('hidden');
  14516. }
  14517. } catch (err) {
  14518. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14519. if (errEl) errEl.classList.remove('hidden');
  14520. } finally {
  14521. if (btn) btn.disabled = false;
  14522. if (btnText) btnText.innerText = 'Sign In to Controller';
  14523. if (spinner) spinner.classList.add('hidden');
  14524. }
  14525. }
  14526. async function handleLogoutClick() {
  14527. try {
  14528. await originalFetch(`${API_BASE}/auth/logout`, {
  14529. method: 'POST',
  14530. headers: {
  14531. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14532. }
  14533. });
  14534. } catch (e) {}
  14535. stopSessionPolling();
  14536. localStorage.removeItem('debtik_token');
  14537. state.currentUser = null;
  14538. state.isPolling = false;
  14539. if (window._telemetryInterval) {
  14540. clearInterval(window._telemetryInterval);
  14541. window._telemetryInterval = null;
  14542. }
  14543. if (trafficEventSource) {
  14544. trafficEventSource.close();
  14545. trafficEventSource = null;
  14546. }
  14547. if (trafficPollFallback) {
  14548. clearInterval(trafficPollFallback);
  14549. trafficPollFallback = null;
  14550. }
  14551. showLoginScreen(false);
  14552. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14553. }
  14554. function togglePasswordVisibility(id) {
  14555. const input = document.getElementById(id);
  14556. if (!input) return;
  14557. input.type = input.type === 'password' ? 'text' : 'password';
  14558. }
  14559. function toggleUserMenu() {
  14560. const menu = document.getElementById('user-menu-dropdown');
  14561. if (menu) menu.classList.toggle('hidden');
  14562. }
  14563. function closeUserMenu() {
  14564. const menu = document.getElementById('user-menu-dropdown');
  14565. if (menu) menu.classList.add('hidden');
  14566. }
  14567. // Close user menu on outside click
  14568. document.addEventListener('click', (e) => {
  14569. const menu = document.getElementById('user-menu-dropdown');
  14570. if (!menu || menu.classList.contains('hidden')) return;
  14571. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14572. menu.classList.add('hidden');
  14573. }
  14574. });
  14575. function updateUserProfileHeader(user) {
  14576. if (!user) return;
  14577. const navName = document.getElementById('nav-user-name');
  14578. if (navName) navName.innerText = user.username;
  14579. const dropName = document.getElementById('dropdown-user-name');
  14580. if (dropName) dropName.innerText = user.username;
  14581. const navRole = document.getElementById('nav-user-role');
  14582. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14583. const navAvatar = document.getElementById('nav-user-avatar');
  14584. if (navAvatar) {
  14585. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14586. navAvatar.innerText = initials;
  14587. }
  14588. const statCurUser = document.getElementById('stat-current-user');
  14589. if (statCurUser) statCurUser.innerText = user.username;
  14590. const statCurRole = document.getElementById('stat-current-role');
  14591. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14592. // Role permissions UI visibility: hide user management for non-admins
  14593. const isFullAdmin = user.role === 'full';
  14594. const navUsers = document.getElementById('nav-users');
  14595. if (navUsers) {
  14596. if (isFullAdmin) navUsers.classList.remove('hidden');
  14597. else navUsers.classList.add('hidden');
  14598. }
  14599. const dropdownUsers = document.getElementById('dropdown-item-users');
  14600. if (dropdownUsers) {
  14601. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14602. else dropdownUsers.classList.add('hidden');
  14603. }
  14604. }
  14605. // ================= User Management CRUD =================
  14606. async function loadUsers(isManual = false) {
  14607. try {
  14608. const res = await fetch(`${API_BASE}/users`);
  14609. if (res.status === 403) {
  14610. const tbody = document.getElementById('users-table-tbody');
  14611. if (tbody) {
  14612. tbody.innerHTML = `
  14613. <tr>
  14614. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14615. <div class="inline-flex items-center gap-2">
  14616. <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>
  14617. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14618. </div>
  14619. </td>
  14620. </tr>
  14621. `;
  14622. }
  14623. return;
  14624. }
  14625. if (res.ok) {
  14626. state.users = await res.json();
  14627. renderUsersTable();
  14628. const totalUsers = document.getElementById('stat-total-users');
  14629. if (totalUsers) totalUsers.innerText = state.users.length;
  14630. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14631. const adminUsers = document.getElementById('stat-admin-users');
  14632. if (adminUsers) adminUsers.innerText = adminCount;
  14633. const badgeCount = document.getElementById('badge-users-count');
  14634. if (badgeCount) badgeCount.innerText = state.users.length;
  14635. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14636. }
  14637. } catch (err) {
  14638. console.error('Failed to load users:', err);
  14639. }
  14640. }
  14641. function renderUsersTable() {
  14642. const tbody = document.getElementById('users-table-tbody');
  14643. const emptyState = document.getElementById('users-empty-state');
  14644. if (!tbody) return;
  14645. tbody.innerHTML = '';
  14646. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14647. const filtered = (state.users || []).filter(u => {
  14648. if (!query) return true;
  14649. return u.username.toLowerCase().includes(query) ||
  14650. (u.role || '').toLowerCase().includes(query) ||
  14651. (u.comment || '').toLowerCase().includes(query);
  14652. });
  14653. if (filtered.length === 0) {
  14654. if (emptyState) emptyState.classList.remove('hidden');
  14655. return;
  14656. }
  14657. if (emptyState) emptyState.classList.add('hidden');
  14658. const currentAuthUser = state.currentUser?.username || '';
  14659. filtered.forEach(u => {
  14660. const isSelf = u.username === currentAuthUser;
  14661. const isFull = u.role === 'full';
  14662. const isWrite = u.role === 'write';
  14663. 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>`;
  14664. if (isFull) {
  14665. 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>`;
  14666. } else if (isWrite) {
  14667. 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>`;
  14668. }
  14669. const statusBadge = u.disabled
  14670. ? `<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>`
  14671. : `<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>`;
  14672. let lastLoginText = 'Never';
  14673. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14674. const dt = new Date(u.last_login_at);
  14675. lastLoginText = dt.toLocaleString();
  14676. }
  14677. const initials = u.username.slice(0, 2).toUpperCase();
  14678. const tr = document.createElement('tr');
  14679. tr.className = 'hover:bg-slate-800/40 transition group';
  14680. tr.innerHTML = `
  14681. <td class="py-3 px-4">
  14682. <div class="flex items-center gap-3">
  14683. <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">
  14684. ${initials}
  14685. </div>
  14686. <div>
  14687. <div class="font-bold text-white text-xs flex items-center gap-2">
  14688. <span>${escapeHtml(u.username)}</span>
  14689. ${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>' : ''}
  14690. </div>
  14691. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14692. </div>
  14693. </div>
  14694. </td>
  14695. <td class="py-3 px-4 font-sans">
  14696. ${roleBadge}
  14697. </td>
  14698. <td class="py-3 px-4 font-sans">
  14699. ${statusBadge}
  14700. </td>
  14701. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14702. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14703. </td>
  14704. <td class="py-3 px-4 text-slate-400 text-xs">
  14705. ${lastLoginText}
  14706. </td>
  14707. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14708. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14709. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14710. <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>
  14711. </button>
  14712. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14713. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14714. <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>
  14715. </button>
  14716. ${!isSelf ? `
  14717. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14718. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14719. <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>
  14720. </button>
  14721. ` : ''}
  14722. </td>
  14723. `;
  14724. tbody.appendChild(tr);
  14725. });
  14726. }
  14727. function openAddUserModal() {
  14728. document.getElementById('user-add-username').value = '';
  14729. document.getElementById('user-add-password').value = '';
  14730. document.getElementById('user-add-confirm').value = '';
  14731. document.getElementById('user-add-role').value = 'full';
  14732. document.getElementById('user-add-comment').value = '';
  14733. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14734. document.getElementById('user-add-username')?.focus();
  14735. }
  14736. function closeAddUserModal() {
  14737. document.getElementById('modal-add-user')?.classList.add('hidden');
  14738. }
  14739. async function submitAddUser(event) {
  14740. event.preventDefault();
  14741. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14742. const password = document.getElementById('user-add-password')?.value || '';
  14743. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14744. const role = document.getElementById('user-add-role')?.value || 'full';
  14745. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14746. if (password !== confirm) {
  14747. showToast('Validation Error', 'Passwords do not match', 'warning');
  14748. return;
  14749. }
  14750. if (password.length < 4) {
  14751. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14752. return;
  14753. }
  14754. try {
  14755. const res = await fetch(`${API_BASE}/users`, {
  14756. method: 'POST',
  14757. headers: { 'Content-Type': 'application/json' },
  14758. body: JSON.stringify({ username, password, role, comment })
  14759. });
  14760. const data = await res.json();
  14761. if (res.ok) {
  14762. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14763. closeAddUserModal();
  14764. loadUsers(false);
  14765. } else {
  14766. showToast('Error', data.message || 'Failed to create user', 'error');
  14767. }
  14768. } catch (err) {
  14769. showToast('Error', err.message, 'error');
  14770. }
  14771. }
  14772. function openEditUserModal(username) {
  14773. const user = (state.users || []).find(u => u.username === username);
  14774. if (!user) return;
  14775. document.getElementById('user-edit-username').value = user.username;
  14776. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14777. document.getElementById('user-edit-role').value = user.role || 'read';
  14778. document.getElementById('user-edit-comment').value = user.comment || '';
  14779. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14780. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14781. }
  14782. function closeEditUserModal() {
  14783. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14784. }
  14785. async function submitEditUser(event) {
  14786. event.preventDefault();
  14787. const username = document.getElementById('user-edit-username')?.value;
  14788. const role = document.getElementById('user-edit-role')?.value || 'read';
  14789. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14790. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14791. try {
  14792. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14793. method: 'PUT',
  14794. headers: { 'Content-Type': 'application/json' },
  14795. body: JSON.stringify({ role, comment, disabled })
  14796. });
  14797. const data = await res.json();
  14798. if (res.ok) {
  14799. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14800. closeEditUserModal();
  14801. loadUsers(false);
  14802. // If updated own role/disabled status, refresh self profile
  14803. if (username === state.currentUser?.username) {
  14804. checkAuthStatus();
  14805. }
  14806. } else {
  14807. showToast('Error', data.message || 'Failed to update user', 'error');
  14808. }
  14809. } catch (err) {
  14810. showToast('Error', err.message, 'error');
  14811. }
  14812. }
  14813. function openAdminResetPasswordModal(username) {
  14814. document.getElementById('admin-reset-username').value = username;
  14815. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14816. document.getElementById('admin-reset-new-pw').value = '';
  14817. document.getElementById('admin-reset-confirm-pw').value = '';
  14818. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14819. document.getElementById('admin-reset-new-pw')?.focus();
  14820. }
  14821. function closeAdminResetPasswordModal() {
  14822. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14823. }
  14824. async function submitAdminResetPassword(event) {
  14825. event.preventDefault();
  14826. const username = document.getElementById('admin-reset-username')?.value;
  14827. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14828. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14829. if (newPassword !== confirm) {
  14830. showToast('Validation Error', 'Passwords do not match', 'warning');
  14831. return;
  14832. }
  14833. if (newPassword.length < 4) {
  14834. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14835. return;
  14836. }
  14837. try {
  14838. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14839. method: 'POST',
  14840. headers: { 'Content-Type': 'application/json' },
  14841. body: JSON.stringify({ new_password: newPassword })
  14842. });
  14843. const data = await res.json();
  14844. if (res.ok) {
  14845. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14846. closeAdminResetPasswordModal();
  14847. } else {
  14848. showToast('Error', data.message || 'Failed to reset password', 'error');
  14849. }
  14850. } catch (err) {
  14851. showToast('Error', err.message, 'error');
  14852. }
  14853. }
  14854. async function deleteUser(username) {
  14855. if (username === state.currentUser?.username) {
  14856. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14857. return;
  14858. }
  14859. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14860. return;
  14861. }
  14862. try {
  14863. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14864. method: 'DELETE'
  14865. });
  14866. const data = await res.json();
  14867. if (res.ok) {
  14868. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14869. loadUsers(false);
  14870. } else {
  14871. showToast('Error', data.message || 'Failed to delete user', 'error');
  14872. }
  14873. } catch (err) {
  14874. showToast('Error', err.message, 'error');
  14875. }
  14876. }
  14877. function openSelfPasswordModal() {
  14878. document.getElementById('self-current-password').value = '';
  14879. document.getElementById('self-new-password').value = '';
  14880. document.getElementById('self-confirm-password').value = '';
  14881. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14882. document.getElementById('self-current-password')?.focus();
  14883. }
  14884. function closeSelfPasswordModal() {
  14885. document.getElementById('modal-self-password')?.classList.add('hidden');
  14886. }
  14887. async function submitSelfPassword(event) {
  14888. event.preventDefault();
  14889. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14890. const newPassword = document.getElementById('self-new-password')?.value || '';
  14891. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14892. if (newPassword !== confirm) {
  14893. showToast('Validation Error', 'New passwords do not match', 'warning');
  14894. return;
  14895. }
  14896. if (newPassword.length < 4) {
  14897. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14898. return;
  14899. }
  14900. try {
  14901. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14902. method: 'POST',
  14903. headers: { 'Content-Type': 'application/json' },
  14904. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14905. });
  14906. const data = await res.json();
  14907. if (res.ok) {
  14908. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14909. closeSelfPasswordModal();
  14910. } else {
  14911. showToast('Error', data.message || 'Failed to change password', 'error');
  14912. }
  14913. } catch (err) {
  14914. showToast('Error', err.message, 'error');
  14915. }
  14916. }
  14917. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14918. state.services = [];
  14919. async function loadServices(manual = false) {
  14920. try {
  14921. const res = await fetch(`${API_BASE}/system/services`);
  14922. if (!res.ok) throw new Error('Failed to load services');
  14923. const data = await res.json();
  14924. state.services = data || [];
  14925. renderServicesTable();
  14926. updateCertificatesBadges();
  14927. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14928. } catch (err) {
  14929. if (manual) showToast('Error', err.message, 'error');
  14930. }
  14931. }
  14932. function renderServicesTable() {
  14933. const tbody = document.getElementById('services-table-body');
  14934. if (!tbody) return;
  14935. if (!state.services || state.services.length === 0) {
  14936. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14937. return;
  14938. }
  14939. tbody.innerHTML = state.services.map(s => {
  14940. const isOff = s.disabled;
  14941. const statusBadge = isOff
  14942. ? '<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>'
  14943. : '<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>';
  14944. const toggleBtn = isOff
  14945. ? `<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>`
  14946. : `<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>`;
  14947. let certBadge = '';
  14948. if (s.name === 'www-ssl') {
  14949. if (s.certificate) {
  14950. 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>`;
  14951. } else {
  14952. 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>`;
  14953. }
  14954. }
  14955. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14956. return `
  14957. <tr class="hover:bg-slate-800/40 transition">
  14958. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14959. <td class="py-3 px-4">
  14960. <div class="flex items-center gap-2">
  14961. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14962. <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">
  14963. <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>
  14964. </button>
  14965. </div>
  14966. </td>
  14967. <td class="py-3 px-4">${statusBadge}</td>
  14968. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14969. <td class="py-3 px-4 text-right">
  14970. <div class="flex items-center justify-end gap-2">
  14971. <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">
  14972. <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>
  14973. <span>Edit</span>
  14974. </button>
  14975. ${toggleBtn}
  14976. </div>
  14977. </td>
  14978. </tr>
  14979. `;
  14980. }).join('');
  14981. }
  14982. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14983. document.getElementById('modal-service-name').value = serviceName;
  14984. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14985. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14986. document.getElementById('modal-service-port').value = currentPort;
  14987. const hintEl = document.getElementById('modal-service-port-hint');
  14988. const warnEl = document.getElementById('modal-service-warning');
  14989. const certGroup = document.getElementById('modal-service-cert-group');
  14990. const certSelect = document.getElementById('modal-service-cert-select');
  14991. if (serviceName === 'www') {
  14992. hintEl.textContent = 'Default HTTP web port: 80';
  14993. warnEl.classList.remove('hidden');
  14994. certGroup.classList.add('hidden');
  14995. } else if (serviceName === 'www-ssl') {
  14996. hintEl.textContent = 'Default HTTPS web port: 443';
  14997. warnEl.classList.remove('hidden');
  14998. certGroup.classList.remove('hidden');
  14999. const populateCertOptions = (certs) => {
  15000. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15001. (certs || []).forEach(c => {
  15002. const opt = document.createElement('option');
  15003. opt.value = c.name;
  15004. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15005. if (c.name === currentCert) opt.selected = true;
  15006. certSelect.appendChild(opt);
  15007. });
  15008. };
  15009. if (state.certificates && state.certificates.length > 0) {
  15010. populateCertOptions(state.certificates);
  15011. } else {
  15012. loadCertificates(false).then(() => {
  15013. populateCertOptions(state.certificates);
  15014. });
  15015. }
  15016. } else if (serviceName === 'telnet') {
  15017. hintEl.textContent = 'Default Telnet console port: 8282';
  15018. warnEl.classList.add('hidden');
  15019. certGroup.classList.add('hidden');
  15020. } else if (serviceName === 'ssh') {
  15021. hintEl.textContent = 'Default SSH port: 2222';
  15022. warnEl.classList.add('hidden');
  15023. certGroup.classList.add('hidden');
  15024. } else {
  15025. hintEl.textContent = '';
  15026. warnEl.classList.add('hidden');
  15027. certGroup.classList.add('hidden');
  15028. }
  15029. const modal = document.getElementById('modal-service-edit');
  15030. modal.classList.remove('hidden');
  15031. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15032. }
  15033. function closeEditServiceModal() {
  15034. const modal = document.getElementById('modal-service-edit');
  15035. if (modal) modal.classList.add('hidden');
  15036. }
  15037. async function submitSaveServicePort(event) {
  15038. event.preventDefault();
  15039. const name = document.getElementById('modal-service-name').value;
  15040. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15041. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15042. if (isNaN(port) || port < 1 || port > 65535) {
  15043. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15044. return;
  15045. }
  15046. const certSelect = document.getElementById('modal-service-cert-select');
  15047. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15048. try {
  15049. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15050. method: 'POST',
  15051. headers: { 'Content-Type': 'application/json' },
  15052. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15053. });
  15054. if (!res.ok) {
  15055. const errData = await res.json();
  15056. throw new Error(errData.message || 'Failed to update service settings');
  15057. }
  15058. closeEditServiceModal();
  15059. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15060. await loadServices();
  15061. } catch (err) {
  15062. showToast('Error', err.message, 'error');
  15063. }
  15064. }
  15065. async function toggleServiceState(serviceName, newDisabled) {
  15066. if (serviceName === 'www' && newDisabled) {
  15067. 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?")) {
  15068. return;
  15069. }
  15070. }
  15071. if (serviceName === 'www-ssl' && !newDisabled) {
  15072. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15073. if (!sslSvc || !sslSvc.certificate) {
  15074. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15075. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15076. return;
  15077. }
  15078. }
  15079. try {
  15080. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15081. method: 'POST',
  15082. headers: { 'Content-Type': 'application/json' },
  15083. body: JSON.stringify({ disabled: newDisabled })
  15084. });
  15085. if (!res.ok) {
  15086. const errData = await res.json();
  15087. throw new Error(errData.message || 'Failed to update service');
  15088. }
  15089. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15090. await loadServices();
  15091. } catch (err) {
  15092. showToast('Error', err.message, 'error');
  15093. }
  15094. }
  15095. // ==================== SYSTEM LOGS (/log) ====================
  15096. state.logs = [];
  15097. let logsTimer = null;
  15098. async function loadLogs(manual = false) {
  15099. const limitEl = document.getElementById('logs-limit-select');
  15100. const limit = limitEl ? limitEl.value : '100';
  15101. try {
  15102. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15103. if (!res.ok) throw new Error('Failed to load logs');
  15104. const data = await res.json();
  15105. state.logs = data.logs || [];
  15106. renderLogsTable();
  15107. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15108. } catch (err) {
  15109. if (manual) showToast('Error', err.message, 'error');
  15110. }
  15111. // Setup auto-refresh if enabled and on logs tab
  15112. if (!logsTimer && state.currentUser) {
  15113. logsTimer = setInterval(() => {
  15114. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15115. const auto = document.getElementById('logs-auto-refresh');
  15116. if (auto && auto.checked) {
  15117. loadLogs(false);
  15118. }
  15119. }
  15120. }, 3000);
  15121. }
  15122. }
  15123. function renderLogsTable() {
  15124. const tbody = document.getElementById('logs-table-body');
  15125. if (!tbody) return;
  15126. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15127. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15128. const filtered = state.logs.filter(entry => {
  15129. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15130. return false;
  15131. }
  15132. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15133. return false;
  15134. }
  15135. return true;
  15136. });
  15137. if (filtered.length === 0) {
  15138. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15139. return;
  15140. }
  15141. tbody.innerHTML = filtered.map(l => {
  15142. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15143. const topLower = l.topics.toLowerCase();
  15144. if (topLower.includes('auth')) {
  15145. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15146. } else if (topLower.includes('dhcp')) {
  15147. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15148. } else if (topLower.includes('route')) {
  15149. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15150. } else if (topLower.includes('firewall')) {
  15151. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15152. } else if (topLower.includes('error')) {
  15153. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15154. } else if (topLower.includes('system')) {
  15155. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15156. }
  15157. const d = new Date(l.time);
  15158. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15159. return `
  15160. <tr class="hover:bg-slate-800/40 transition">
  15161. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15162. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15163. <td class="py-2 px-3 whitespace-nowrap">
  15164. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15165. </td>
  15166. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15167. </tr>
  15168. `;
  15169. }).join('');
  15170. }
  15171. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15172. state.certificates = [];
  15173. async function loadCertificates(manual = false) {
  15174. try {
  15175. const res = await fetch(`${API_BASE}/certificates`);
  15176. if (!res.ok) throw new Error('Failed to load certificates');
  15177. state.certificates = await res.json() || [];
  15178. updateCertificatesBadges();
  15179. renderCertificatesTable();
  15180. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15181. } catch (err) {
  15182. if (manual) showToast('Error', err.message, 'error');
  15183. }
  15184. }
  15185. function updateCertificatesBadges() {
  15186. const total = (state.certificates || []).length;
  15187. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15188. const bCount = document.getElementById('badge-certs-count');
  15189. if (bCount) bCount.innerText = total;
  15190. const kpiTotal = document.getElementById('kpi-certs-total');
  15191. if (kpiTotal) kpiTotal.innerText = total;
  15192. const kpiCA = document.getElementById('kpi-certs-ca');
  15193. if (kpiCA) kpiCA.innerText = caCount;
  15194. const kpiHttps = document.getElementById('kpi-https-status');
  15195. if (kpiHttps) {
  15196. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15197. if (sslSvc) {
  15198. if (!sslSvc.disabled) {
  15199. 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>`;
  15200. } else {
  15201. 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>`;
  15202. }
  15203. }
  15204. }
  15205. }
  15206. function renderCertificatesTable() {
  15207. const tbody = document.getElementById('certs-table-body');
  15208. if (!tbody) return;
  15209. if (!state.certificates || state.certificates.length === 0) {
  15210. 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>';
  15211. return;
  15212. }
  15213. tbody.innerHTML = state.certificates.map(c => {
  15214. let typeBadge = '';
  15215. if (c.is_ca) {
  15216. 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>';
  15217. } else if (c.type === 'acme') {
  15218. 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>';
  15219. } else if (c.issuer && c.issuer !== c.common_name) {
  15220. 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>';
  15221. } else {
  15222. 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>';
  15223. }
  15224. const sansHtml = (c.sans && c.sans.length > 0)
  15225. ? 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('')
  15226. : '<span class="text-slate-500">-</span>';
  15227. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15228. let validStr = '-';
  15229. let validBadge = '';
  15230. if (validTo && !isNaN(validTo.getTime())) {
  15231. const now = new Date();
  15232. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15233. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15234. if (daysLeft < 0) {
  15235. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15236. } else if (daysLeft < 30) {
  15237. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15238. } else {
  15239. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15240. }
  15241. }
  15242. return `
  15243. <tr class="hover:bg-slate-800/40 transition">
  15244. <td class="py-3 px-4">${typeBadge}</td>
  15245. <td class="py-3 px-4">
  15246. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15247. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15248. </td>
  15249. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15250. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15251. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15252. <span>${validStr}</span> ${validBadge}
  15253. ${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>` : ''}
  15254. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15255. </td>
  15256. <td class="py-3 px-4 text-right whitespace-nowrap">
  15257. <div class="flex items-center justify-end gap-1.5">
  15258. <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">
  15259. <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>
  15260. <span>View</span>
  15261. </button>
  15262. <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">
  15263. <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>
  15264. </button>
  15265. </div>
  15266. </td>
  15267. </tr>
  15268. `;
  15269. }).join('');
  15270. }
  15271. // Create CA
  15272. function openCreateCAModal() {
  15273. document.getElementById('form-create-ca').reset();
  15274. document.getElementById('ca-days').value = '3650';
  15275. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15276. document.getElementById('ca-country').value = 'GR';
  15277. document.getElementById('ca-key-type').value = 'RSA-2048';
  15278. document.getElementById('modal-create-ca').classList.remove('hidden');
  15279. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15280. }
  15281. function closeCreateCAModal() {
  15282. document.getElementById('modal-create-ca').classList.add('hidden');
  15283. }
  15284. async function submitCreateCA(event) {
  15285. event.preventDefault();
  15286. const payload = {
  15287. name: document.getElementById('ca-name').value.trim(),
  15288. common_name: document.getElementById('ca-cn').value.trim(),
  15289. organization: document.getElementById('ca-org').value.trim(),
  15290. country: document.getElementById('ca-country').value.trim(),
  15291. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15292. key_type: document.getElementById('ca-key-type').value
  15293. };
  15294. try {
  15295. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15296. method: 'POST',
  15297. headers: { 'Content-Type': 'application/json' },
  15298. body: JSON.stringify(payload)
  15299. });
  15300. if (!res.ok) {
  15301. const errData = await res.json();
  15302. throw new Error(errData.message || 'Failed to create CA');
  15303. }
  15304. closeCreateCAModal();
  15305. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15306. await loadCertificates();
  15307. } catch (err) {
  15308. showToast('Error', err.message, 'error');
  15309. }
  15310. }
  15311. // Create Cert
  15312. function openCreateCertModal() {
  15313. document.getElementById('form-create-cert').reset();
  15314. document.getElementById('cert-days').value = '730';
  15315. document.getElementById('cert-key-type').value = 'RSA-2048';
  15316. const caSelect = document.getElementById('cert-ca-select');
  15317. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15318. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15319. const opt = document.createElement('option');
  15320. opt.value = ca.name;
  15321. opt.textContent = `${ca.name} (${ca.common_name})`;
  15322. caSelect.appendChild(opt);
  15323. });
  15324. document.getElementById('modal-create-cert').classList.remove('hidden');
  15325. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15326. }
  15327. function closeCreateCertModal() {
  15328. document.getElementById('modal-create-cert').classList.add('hidden');
  15329. }
  15330. async function submitCreateCert(event) {
  15331. event.preventDefault();
  15332. const rawSans = document.getElementById('cert-sans').value;
  15333. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15334. const caName = document.getElementById('cert-ca-select').value;
  15335. const payload = {
  15336. name: document.getElementById('cert-name').value.trim(),
  15337. common_name: document.getElementById('cert-cn').value.trim(),
  15338. ca_name: caName,
  15339. sans: sansList,
  15340. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15341. key_type: document.getElementById('cert-key-type').value,
  15342. is_server: true
  15343. };
  15344. try {
  15345. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15346. method: 'POST',
  15347. headers: { 'Content-Type': 'application/json' },
  15348. body: JSON.stringify(payload)
  15349. });
  15350. if (!res.ok) {
  15351. const errData = await res.json();
  15352. throw new Error(errData.message || 'Failed to issue certificate');
  15353. }
  15354. closeCreateCertModal();
  15355. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15356. await loadCertificates();
  15357. } catch (err) {
  15358. showToast('Error', err.message, 'error');
  15359. }
  15360. }
  15361. // Let's Encrypt
  15362. function openLetsEncryptModal() {
  15363. document.getElementById('form-letsencrypt').reset();
  15364. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15365. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15366. }
  15367. function closeLetsEncryptModal() {
  15368. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15369. }
  15370. async function submitLetsEncrypt(event) {
  15371. event.preventDefault();
  15372. const domain = document.getElementById('le-domain').value.trim();
  15373. const email = document.getElementById('le-email').value.trim();
  15374. let name = document.getElementById('le-name').value.trim();
  15375. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15376. const staging = document.getElementById('le-staging').checked;
  15377. const btn = document.getElementById('btn-submit-letsencrypt');
  15378. const origBtnHtml = btn.innerHTML;
  15379. btn.disabled = true;
  15380. 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>`;
  15381. try {
  15382. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15383. method: 'POST',
  15384. headers: { 'Content-Type': 'application/json' },
  15385. body: JSON.stringify({
  15386. name: name,
  15387. domain: domain,
  15388. email: email,
  15389. staging: staging
  15390. })
  15391. });
  15392. if (!res.ok) {
  15393. const errData = await res.json();
  15394. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15395. }
  15396. closeLetsEncryptModal();
  15397. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15398. await loadCertificates();
  15399. } catch (err) {
  15400. showToast('Let\'s Encrypt Error', err.message, 'error');
  15401. } finally {
  15402. btn.disabled = false;
  15403. btn.innerHTML = origBtnHtml;
  15404. }
  15405. }
  15406. // Import Cert
  15407. function openImportCertModal() {
  15408. document.getElementById('form-import-cert').reset();
  15409. document.getElementById('modal-import-cert').classList.remove('hidden');
  15410. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15411. }
  15412. function closeImportCertModal() {
  15413. document.getElementById('modal-import-cert').classList.add('hidden');
  15414. }
  15415. async function submitImportCert(event) {
  15416. event.preventDefault();
  15417. const payload = {
  15418. name: document.getElementById('import-cert-name').value.trim(),
  15419. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15420. key_pem: document.getElementById('import-key-pem').value.trim()
  15421. };
  15422. try {
  15423. const res = await fetch(`${API_BASE}/certificates/import`, {
  15424. method: 'POST',
  15425. headers: { 'Content-Type': 'application/json' },
  15426. body: JSON.stringify(payload)
  15427. });
  15428. if (!res.ok) {
  15429. const errData = await res.json();
  15430. throw new Error(errData.message || 'Failed to import certificate');
  15431. }
  15432. closeImportCertModal();
  15433. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15434. await loadCertificates();
  15435. } catch (err) {
  15436. showToast('Error', err.message, 'error');
  15437. }
  15438. }
  15439. // View / Export Modal
  15440. async function openViewCertModal(name) {
  15441. const c = (state.certificates || []).find(x => x.name === name);
  15442. if (!c) return;
  15443. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15444. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15445. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15446. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15447. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15448. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15449. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15450. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15451. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15452. document.getElementById('modal-view-cert').classList.remove('hidden');
  15453. try {
  15454. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15455. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15456. const data = await res.json();
  15457. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15458. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15459. } catch (err) {
  15460. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15461. document.getElementById('view-key-pem-text').value = '';
  15462. }
  15463. }
  15464. function closeViewCertModal() {
  15465. document.getElementById('modal-view-cert').classList.add('hidden');
  15466. }
  15467. function copyCertPEM() {
  15468. const text = document.getElementById('view-cert-pem-text').value;
  15469. if (!text) return;
  15470. navigator.clipboard.writeText(text).then(() => {
  15471. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15472. }).catch(() => {
  15473. showToast('Error', 'Failed to copy to clipboard', 'error');
  15474. });
  15475. }
  15476. function copyKeyPEM() {
  15477. const text = document.getElementById('view-key-pem-text').value;
  15478. if (!text) return;
  15479. navigator.clipboard.writeText(text).then(() => {
  15480. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15481. }).catch(() => {
  15482. showToast('Error', 'Failed to copy to clipboard', 'error');
  15483. });
  15484. }
  15485. async function deleteCertificate(name) {
  15486. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15487. return;
  15488. }
  15489. try {
  15490. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15491. method: 'DELETE'
  15492. });
  15493. if (!res.ok) {
  15494. const errData = await res.json();
  15495. throw new Error(errData.message || 'Failed to delete certificate');
  15496. }
  15497. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15498. await loadCertificates();
  15499. } catch (err) {
  15500. showToast('Error', err.message, 'error');
  15501. }
  15502. }
  15503. // Refresh immediately when returning to a backgrounded controller tab.
  15504. document.addEventListener('visibilitychange', () => {
  15505. if (!state.currentUser) return;
  15506. if (document.hidden) {
  15507. if (trafficEventSource) trafficEventSource.close();
  15508. trafficEventSource = null;
  15509. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15510. trafficPollFallback = null;
  15511. } else {
  15512. fetchData(false);
  15513. initLiveTrafficStream();
  15514. if (state.activeTab === 'bwtest') loadBwTestView();
  15515. }
  15516. });
  15517. async function loadUpdateStatus(populate = true) {
  15518. try {
  15519. const res = await fetch(`${API_BASE}/update/status`);
  15520. if (!res.ok) throw new Error(await responseError(res));
  15521. const data = await res.json();
  15522. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15523. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15524. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15525. document.getElementById('update-state').textContent = data.state || 'idle';
  15526. document.getElementById('update-log').textContent = data.log || '';
  15527. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15528. }
  15529. async function saveUpdateConfig() {
  15530. try {
  15531. const repository = document.getElementById('update-repository').value.trim();
  15532. const branch = 'master';
  15533. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15534. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15535. if (!res.ok) throw new Error(await responseError(res));
  15536. document.getElementById('update-install-button').disabled = true;
  15537. document.getElementById('update-available').textContent = '—';
  15538. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15539. await loadUpdateStatus(false);
  15540. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15541. }
  15542. async function checkUpdate() {
  15543. try {
  15544. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15545. if (!res.ok) throw new Error(await responseError(res));
  15546. const data = await res.json();
  15547. document.getElementById('update-available').textContent = data.available_version;
  15548. document.getElementById('update-install-button').disabled = !data.update_available;
  15549. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15550. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15551. }
  15552. async function startUpdate(action) {
  15553. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15554. try {
  15555. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15556. if (!res.ok) throw new Error(await responseError(res));
  15557. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15558. await loadUpdateStatus(false);
  15559. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15560. }
  15561. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  15562. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  15563. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  15564. function safeFirewallRow(row) {
  15565. const result = {...row};
  15566. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  15567. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  15568. return result;
  15569. }
  15570. function setFirewallDays(prefix, days) {
  15571. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  15572. 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); }
  15573. }
  15574. function getFirewallDays(prefix) {
  15575. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  15576. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  15577. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  15578. return selected.join(',');
  15579. }
  15580. async function resetFirewallRuleCounter(kind, resetDisplay) {
  15581. const id = document.getElementById(kind+'-modal-id')?.value;
  15582. if (!id) { resetDisplay(); return; }
  15583. try {
  15584. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  15585. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  15586. resetDisplay(); await loadFirewall(false);
  15587. } catch(error) { showToast('Error', error.message, 'error'); }
  15588. }
  15589. function reviewLegacyFirewallSettings(kind, id) {
  15590. if (!id) return true;
  15591. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  15592. const rule = (rows || []).find(r => r.id === id);
  15593. if (!rule) return true;
  15594. 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'];
  15595. const present = unsupported.filter(key => rule[key]);
  15596. if (!present.length) return true;
  15597. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  15598. }
  15599. function refreshFirewallRejectTypes() {
  15600. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  15601. const old=select.value;
  15602. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  15603. 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'];
  15604. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  15605. if(types.includes(old))select.value=old;
  15606. }
  15607. function setFirewallActionSelection(kind, value) {
  15608. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  15609. if(!Array.from(select.options).some(option=>option.value===value)) {
  15610. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  15611. }
  15612. select.value=value;
  15613. }