app.js 823 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446
  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. vxlanTunnels: [],
  109. vxlanVteps: [],
  110. pppSecrets: [],
  111. pppProfiles: [],
  112. pppActiveSessions: [],
  113. pppoeServer: null,
  114. pptpServer: null,
  115. l2tpServer: null,
  116. ipsecServer: null,
  117. ifaceFilter: 'all',
  118. currentModalIface: null,
  119. isPolling: false,
  120. expandedParents: new Set(['eth0']),
  121. pppoeData: null,
  122. wgData: null,
  123. ipsecData: null,
  124. l2tpData: null,
  125. pptpData: null,
  126. fwSummary: null,
  127. filterRules: [],
  128. natRules: [],
  129. mangleRules: [],
  130. addressLists: [],
  131. connections: [],
  132. policyRules: [],
  133. routingTables: [],
  134. routingFilters: [],
  135. filterChainSelected: 'all',
  136. activeToolsSubTab: 'ping',
  137. dhcpClients: [],
  138. dhcpSummary: null,
  139. dhcpServerTab: 'servers',
  140. dhcpServers: [],
  141. dhcpNetworks: [],
  142. dhcpLeases: [],
  143. dhcpOptions: [],
  144. dhcpServerSummary: null,
  145. sdwanGroups: [],
  146. sdwanTelemetry: null
  147. };
  148. const API_BASE = '/api';
  149. function escapeHtml(str) {
  150. if (str === null || str === undefined) return '';
  151. return String(str)
  152. .replace(/&/g, '&')
  153. .replace(/</g, '&lt;')
  154. .replace(/>/g, '&gt;')
  155. .replace(/"/g, '&quot;')
  156. .replace(/'/g, '&#039;');
  157. }
  158. function formatBytes(bytes) {
  159. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  160. const k = 1024;
  161. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  162. const i = Math.floor(Math.log(bytes) / Math.log(k));
  163. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  164. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  165. }
  166. // Initialize on page load
  167. document.addEventListener('DOMContentLoaded', async () => {
  168. initTableSorting();
  169. // Verify authentication before bootstrapping telemetry and views
  170. const isAuthenticated = await checkAuthStatus();
  171. if (isAuthenticated) {
  172. const hash = window.location.hash.replace('#', '') || 'dashboard';
  173. navigate(hash);
  174. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  175. if (!window._telemetryInterval) {
  176. window._telemetryInterval = setInterval(() => {
  177. if (state.isPolling && state.currentUser && !document.hidden) {
  178. fetchData(false);
  179. }
  180. }, 5000);
  181. }
  182. }
  183. });
  184. let trafficEventSource = null;
  185. let trafficPollFallback = null;
  186. function initLiveTrafficStream() {
  187. if (trafficEventSource) {
  188. try { trafficEventSource.close(); } catch(e) {}
  189. trafficEventSource = null;
  190. }
  191. if (trafficPollFallback) {
  192. clearInterval(trafficPollFallback);
  193. trafficPollFallback = null;
  194. }
  195. if (window.EventSource) {
  196. try {
  197. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  198. trafficEventSource.onmessage = (event) => {
  199. try {
  200. const data = JSON.parse(event.data);
  201. updateLiveInterfaceTraffic(data);
  202. } catch (e) {
  203. console.error('Error parsing live traffic event:', e);
  204. }
  205. };
  206. trafficEventSource.onerror = () => {
  207. // Fallback polling if SSE disconnects
  208. if (!trafficPollFallback) {
  209. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  210. }
  211. };
  212. trafficEventSource.onopen = () => {
  213. if (trafficPollFallback) {
  214. clearInterval(trafficPollFallback);
  215. trafficPollFallback = null;
  216. }
  217. };
  218. return;
  219. } catch (e) {
  220. console.warn('EventSource failed, using 1s polling fallback:', e);
  221. }
  222. }
  223. // Fallback if EventSource is unavailable
  224. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  225. }
  226. async function pollLiveTrafficSnapshot() {
  227. try {
  228. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  229. if (res.ok) {
  230. const data = await res.json();
  231. updateLiveInterfaceTraffic(data);
  232. }
  233. } catch (e) {}
  234. }
  235. function updateLiveInterfaceTraffic(data) {
  236. if (!data || !data.interfaces) return;
  237. state.latestTraffic = data;
  238. // 1. Update Top & Dashboard Total Bandwidth Indicators
  239. const rxHuman = data.total_rx_human || '0 B/s';
  240. const txHuman = data.total_tx_human || '0 B/s';
  241. const statRx = document.getElementById('stat-traffic-rx');
  242. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  243. const statTx = document.getElementById('stat-traffic-tx');
  244. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  245. // 2. Update state.interfaces rates in-memory
  246. if (Array.isArray(state.interfaces)) {
  247. state.interfaces.forEach(i => {
  248. const live = data.interfaces[i.name];
  249. if (live) {
  250. i.rate = {
  251. rx_bytes_sec: live.rx_bytes_sec,
  252. tx_bytes_sec: live.tx_bytes_sec,
  253. rx_human: live.rx_human,
  254. tx_human: live.tx_human
  255. };
  256. i.stats = {
  257. rx_bytes: live.rx_bytes,
  258. tx_bytes: live.tx_bytes,
  259. rx_packets: live.rx_packets,
  260. tx_packets: live.tx_packets,
  261. rx_errors: live.rx_errors,
  262. tx_errors: live.tx_errors,
  263. rx_dropped: live.rx_dropped,
  264. tx_dropped: live.tx_dropped
  265. };
  266. }
  267. });
  268. }
  269. // 3. Update all live UI rate spans in-place (ZERO flicker)
  270. Object.keys(data.interfaces).forEach(name => {
  271. const live = data.interfaces[name];
  272. // Dashboard Port Matrix Card
  273. const cardRate = document.getElementById(`port-card-rate-${name}`);
  274. if (cardRate && cardRate.innerText !== live.rx_human) {
  275. cardRate.innerText = live.rx_human;
  276. }
  277. // Dashboard Quick Interfaces Table
  278. const quickRx = document.getElementById(`quick-rx-${name}`);
  279. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  280. const quickTx = document.getElementById(`quick-tx-${name}`);
  281. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  282. // Main Interfaces Tree Table
  283. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  284. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  285. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  286. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  287. // VLAN Sub-interfaces Table
  288. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  289. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  290. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  291. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  292. // VLAN Page Table
  293. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  294. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  295. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  296. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  297. });
  298. }
  299. // Navigation Handler
  300. function navigate(tabName) {
  301. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  302. navigate('bgp');
  303. return;
  304. }
  305. if (tabName === 'vlans') {
  306. navigate('interfaces');
  307. return;
  308. }
  309. if (tabName === 'persistence') {
  310. navigate('dashboard');
  311. return;
  312. }
  313. stopFwStatPolling();
  314. stopNATStatPolling();
  315. stopMangleStatPolling();
  316. state.activeTab = tabName;
  317. window.location.hash = tabName;
  318. // Update nav links styling
  319. document.querySelectorAll('.nav-link').forEach(link => {
  320. 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';
  321. });
  322. const activeNav = document.getElementById(`nav-${tabName}`);
  323. if (activeNav) {
  324. 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';
  325. }
  326. // Update page headers
  327. const titles = {
  328. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  329. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  330. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  331. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  332. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  333. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  334. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  335. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  336. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  337. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  338. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  339. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  340. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  341. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  342. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  343. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  344. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  345. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  346. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  347. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  348. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  349. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  350. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  351. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  352. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  353. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  354. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  355. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  356. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  357. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  358. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  359. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  360. };
  361. const header = titles[tabName] || titles.dashboard;
  362. const pTitle = document.getElementById('page-title');
  363. if (pTitle) pTitle.innerText = header.title;
  364. const pSub = document.getElementById('page-subtitle');
  365. if (pSub) pSub.innerText = header.sub;
  366. // Toggle sections dynamically for all section elements
  367. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  368. if (el.id === `section-${tabName}`) {
  369. el.classList.remove('hidden');
  370. } else {
  371. el.classList.add('hidden');
  372. }
  373. });
  374. if (tabName === 'interfaces') {
  375. loadRoles();
  376. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  377. else switchIfaceSubTab('tree');
  378. }
  379. if (tabName === 'bridge') loadBridge();
  380. if (tabName === 'firewall') loadFirewall();
  381. if (tabName === 'routes') loadRoutes();
  382. if (tabName === 'sdwan') loadSDWAN();
  383. if (tabName === 'bgp') {
  384. loadDynamicRouting();
  385. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  386. }
  387. if (tabName === 'ospf') {
  388. loadDynamicRouting();
  389. switchOspfTab(state.activeOspfTab || 'instances');
  390. }
  391. if (tabName === 'routing-filters') loadDynamicRouting();
  392. if (tabName === 'dynamic-routing') loadDynamicRouting();
  393. if (tabName === 'ppp') loadPPP();
  394. if (tabName === 'eoip') loadEoIP();
  395. if (tabName === 'vxlan') loadVXLAN();
  396. if (tabName === 'aerotun') loadAeroTUN();
  397. if (tabName === 'pppoe') loadPPPoE();
  398. if (tabName === 'wireguard') loadWireGuard();
  399. if (tabName === 'ipsec') loadIPSec();
  400. if (tabName === 'l2tp') loadL2TP();
  401. if (tabName === 'pptp') loadPPTP();
  402. if (tabName === 'tools') loadToolsView();
  403. if (tabName === 'dhcp-client') loadDHCPClients();
  404. if (tabName === 'dhcp-server') loadDHCPServer();
  405. if (tabName === 'vrrp') loadVRRP();
  406. if (tabName === 'bwtest') loadBwTestView();
  407. if (tabName === 'settings') loadSettingsData();
  408. if (tabName === 'users') loadUsers();
  409. if (tabName === 'certificates') loadCertificates();
  410. if (tabName === 'reverse_proxy') loadReverseProxy();
  411. if (tabName === 'services') loadServices();
  412. if (tabName === 'updates') loadUpdateStatus();
  413. if (tabName === 'logs') loadLogs();
  414. setTimeout(initTableSorting, 50);
  415. }
  416. // Fetch all core system, network and VPN telemetry
  417. function fetchData(isManual = false) {
  418. if (coreRefreshPromise) return coreRefreshPromise;
  419. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  420. return coreRefreshPromise;
  421. }
  422. async function refreshCoreData(isManual = false) {
  423. const spinner = document.getElementById('refresh-spinner');
  424. if (isManual && spinner) spinner.classList.add('animate-spin');
  425. try {
  426. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  427. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  428. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  429. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  430. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  431. summaryFetch('/vlans'),
  432. summaryFetch('/vpn/status'),
  433. summaryFetch('/firewall/summary'),
  434. summaryFetch('/routing/dynamic/summary'),
  435. summaryFetch('/bridge/summary'),
  436. summaryFetch('/dhcp/clients/summary'),
  437. summaryFetch('/dhcp/clients'),
  438. summaryFetch('/vrrp/summary').catch(() => null),
  439. summaryFetch('/roles').catch(() => null)
  440. ]);
  441. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  442. if (rolesRes && rolesRes.ok) {
  443. state.roles = await rolesRes.json();
  444. const countEl = document.getElementById('badge-roles-count');
  445. if (countEl) countEl.innerText = (state.roles || []).length;
  446. }
  447. if (vrrpSumRes && vrrpSumRes.ok) {
  448. state.vrrpSummary = await vrrpSumRes.json();
  449. renderVRRPSummary();
  450. }
  451. if (dhcpSumRes && dhcpSumRes.ok) {
  452. state.dhcpSummary = await dhcpSumRes.json();
  453. const bDhcp = document.getElementById('badge-dhcp-client-count');
  454. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  455. }
  456. if (dhcpClientsRes && dhcpClientsRes.ok) {
  457. state.dhcpClients = await dhcpClientsRes.json();
  458. }
  459. if (brSummaryRes.ok) {
  460. state.bridgeSummary = await brSummaryRes.json();
  461. const bBridge = document.getElementById('badge-bridge-count');
  462. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  463. const sBr = document.getElementById('bridge-stat-bridges');
  464. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  465. const sPorts = document.getElementById('bridge-stat-ports');
  466. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  467. const sHosts = document.getElementById('bridge-stat-hosts');
  468. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  469. }
  470. if (statusRes.ok) state.systemStatus = await statusRes.json();
  471. if (ifacesRes.ok) {
  472. const ifacesData = await ifacesRes.json();
  473. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  474. state.interfaces = rawIfaces.filter(i => {
  475. if (!i.name) return false;
  476. if (i.name.startsWith('ep_')) return false;
  477. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  478. });
  479. try { populateToolsInterfaces(); } catch (e) {}
  480. }
  481. if (vlansRes.ok) {
  482. const vlansData = await vlansRes.json();
  483. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  484. }
  485. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  486. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  487. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  488. updateSystemMetrics();
  489. updateBadges();
  490. if (state.activeTab === 'dashboard') renderDashboard();
  491. if (state.activeTab === 'interfaces') {
  492. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  493. else renderInterfacesList();
  494. }
  495. if (state.activeTab === 'vlans') renderVlansList();
  496. if (state.activeTab === 'firewall') await loadFirewall(false);
  497. if (state.activeTab === 'routes') await loadRoutes(false);
  498. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
  499. if (state.activeTab === 'ppp') await loadPPP(false);
  500. if (state.activeTab === 'eoip') await loadEoIP(false);
  501. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  502. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  503. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  504. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  505. if (state.activeTab === 'ipsec') await loadIPSec(false);
  506. if (state.activeTab === 'l2tp') await loadL2TP(false);
  507. if (state.activeTab === 'pptp') await loadPPTP(false);
  508. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  509. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  510. if (state.activeTab === 'vrrp') await loadVRRP(false);
  511. if (state.activeTab === 'settings') await loadSettingsData(false);
  512. if (state.activeTab === 'users') await loadUsers(false);
  513. if (state.activeTab === 'certificates') await loadCertificates(false);
  514. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  515. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  516. if (state.activeTab === 'services') await loadServices(false);
  517. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  518. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  519. } catch (err) {
  520. console.error('Failed to fetch router state:', err);
  521. } finally {
  522. if (isManual && spinner) {
  523. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  524. }
  525. }
  526. }
  527. // Update Top KPI and Sidebar Telemetry
  528. function updateSystemMetrics() {
  529. const s = state.systemStatus;
  530. const v = state.vpnStatus;
  531. if (!s) return;
  532. // Sidebar Host & Uptime
  533. const sideHost = document.getElementById('side-hostname');
  534. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  535. const sideUp = document.getElementById('side-uptime');
  536. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  537. const sideGw = document.getElementById('side-gateway-ip');
  538. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  539. // Compute CPU Metrics
  540. let cpuPct = 0;
  541. if (s.cpu_pct !== undefined) {
  542. cpuPct = s.cpu_pct;
  543. } else if (s.cpu_load && s.cpu_load.length > 0) {
  544. const cores = s.cpu_cores || 1;
  545. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  546. }
  547. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  548. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  549. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  550. // Sidebar CPU
  551. const sideCpuVal = document.getElementById('side-cpu-val');
  552. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  553. const sideCpuBar = document.getElementById('side-cpu-bar');
  554. if (sideCpuBar) {
  555. sideCpuBar.style.width = cpuWidth;
  556. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  557. }
  558. // Dashboard CPU Card
  559. const dashCpuVal = document.getElementById('dash-cpu-val');
  560. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  561. const dashCpuBar = document.getElementById('dash-cpu-bar');
  562. if (dashCpuBar) {
  563. dashCpuBar.style.width = cpuWidth;
  564. if (cpuPct > 85) {
  565. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  566. } else if (cpuPct > 65) {
  567. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  568. } else {
  569. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  570. }
  571. }
  572. const dashCpuCores = document.getElementById('dash-cpu-cores');
  573. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  574. const dashCpuLoad = document.getElementById('dash-cpu-load');
  575. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  576. const dashCpuStatus = document.getElementById('dash-cpu-status');
  577. if (dashCpuStatus) {
  578. if (cpuPct > 85) {
  579. dashCpuStatus.innerText = 'High';
  580. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  581. } else if (cpuPct > 65) {
  582. dashCpuStatus.innerText = 'Heavy';
  583. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  584. } else {
  585. dashCpuStatus.innerText = 'Normal';
  586. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  587. }
  588. }
  589. // Compute RAM Metrics
  590. const memPct = Math.round(s.mem_usage_pct || 0);
  591. const memPctStr = `${memPct}%`;
  592. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  593. const usedMB = s.mem_used_mb || 0;
  594. const totalMB = s.mem_total_mb || 0;
  595. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  596. function fmtMemMB(mb) {
  597. if (mb >= 1024) {
  598. return `${(mb / 1024).toFixed(1)} GB`;
  599. }
  600. return `${mb} MB`;
  601. }
  602. // Sidebar RAM
  603. const sideRamVal = document.getElementById('side-ram-val');
  604. if (sideRamVal) sideRamVal.innerText = memPctStr;
  605. const sideRamBar = document.getElementById('side-ram-bar');
  606. if (sideRamBar) sideRamBar.style.width = memWidth;
  607. // Dashboard RAM Card
  608. const dashRamVal = document.getElementById('dash-ram-val');
  609. if (dashRamVal) dashRamVal.innerText = memPctStr;
  610. const dashRamBar = document.getElementById('dash-ram-bar');
  611. if (dashRamBar) {
  612. dashRamBar.style.width = memWidth;
  613. if (memPct > 85) {
  614. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  615. } else if (memPct > 70) {
  616. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  617. } else {
  618. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  619. }
  620. }
  621. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  622. if (dashRamUsedTotal) {
  623. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  624. }
  625. const dashRamFree = document.getElementById('dash-ram-free');
  626. if (dashRamFree) {
  627. dashRamFree.innerText = fmtMemMB(freeMB);
  628. }
  629. const dashRamStatus = document.getElementById('dash-ram-status');
  630. if (dashRamStatus) {
  631. if (memPct > 85) {
  632. dashRamStatus.innerText = 'High';
  633. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  634. } else {
  635. dashRamStatus.innerText = 'Active';
  636. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  637. }
  638. }
  639. // Legacy Dashboard Stats (Safe checks)
  640. const elIfacesUp = document.getElementById('stat-ifaces-up');
  641. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  642. const elIfacesTot = document.getElementById('stat-ifaces-total');
  643. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  644. const elIfacesDown = document.getElementById('stat-ifaces-down');
  645. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  646. const elVlans = document.getElementById('stat-vlans-count');
  647. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  648. // VPN Status Indicators
  649. if (v) {
  650. const totalActive = v.total_active_tunnels || 0;
  651. const statVpnActive = document.getElementById('stat-vpn-active');
  652. if (statVpnActive) statVpnActive.innerText = totalActive;
  653. const tunnelsDot = document.getElementById('tunnels-dot');
  654. const tunnelsLabel = document.getElementById('tunnels-label');
  655. if (tunnelsDot && tunnelsLabel) {
  656. if (totalActive > 0) {
  657. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  658. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  659. } else {
  660. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  661. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  662. }
  663. }
  664. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  665. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  666. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  667. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  668. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  669. }
  670. // Total Live Bandwidth Rate
  671. let totalRx = 0;
  672. let totalTx = 0;
  673. (state.interfaces || []).forEach(i => {
  674. if (i.rate) {
  675. totalRx += i.rate.rx_bytes_sec || 0;
  676. totalTx += i.rate.tx_bytes_sec || 0;
  677. }
  678. });
  679. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  680. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  681. }
  682. function setDotBadge(id, active) {
  683. const el = document.getElementById(id);
  684. if (!el) return;
  685. if (active) {
  686. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  687. } else {
  688. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  689. }
  690. }
  691. function updateBadges() {
  692. const bIfaces = document.getElementById('badge-ifaces-count');
  693. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  694. const bVlans = document.getElementById('badge-vlans-count');
  695. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  696. if (state.fwSummary) {
  697. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  698. const badgeFw = document.getElementById('badge-firewall-count');
  699. if (badgeFw) badgeFw.innerText = totalFwRules;
  700. }
  701. if (state.vpnStatus) {
  702. const v = state.vpnStatus;
  703. const bEoIP = document.getElementById('badge-eoip-count');
  704. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  705. const bVXLAN = document.getElementById('badge-vxlan-count');
  706. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  707. const bAero = document.getElementById('badge-aerotun-count');
  708. if (bAero) bAero.innerText = v.total_aerotun || 0;
  709. const bPPPSess = document.getElementById('badge-ppp-sessions');
  710. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  711. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  712. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  713. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  714. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  715. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  716. }
  717. if (state.dynSummary) {
  718. const d = state.dynSummary;
  719. setDotBadge('badge-bgp-dot', d.bgp_running);
  720. setDotBadge('badge-ospf-dot', d.ospf_running);
  721. const bBgp = document.getElementById('badge-bgp-count');
  722. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  723. const bOspf = document.getElementById('badge-ospf-count');
  724. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  725. const bFilters = document.getElementById('badge-filters-count');
  726. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  727. }
  728. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  729. if (bDhcpServer) {
  730. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  731. }
  732. }
  733. // Render Dashboard View
  734. function renderDashboard() {
  735. const matrix = document.getElementById('port-matrix');
  736. if (!matrix) return;
  737. const ifaces = state.interfaces || [];
  738. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  739. if (matrix.dataset.sig === sig) {
  740. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  741. }
  742. matrix.dataset.sig = sig;
  743. matrix.innerHTML = '';
  744. (state.interfaces || []).forEach(iface => {
  745. const isUp = iface.state === 'UP';
  746. const isVlan = iface.is_vlan;
  747. const portCard = document.createElement('div');
  748. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  749. isUp
  750. ? (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')
  751. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  752. }`;
  753. portCard.onclick = () => openIfaceModal(iface.name);
  754. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  755. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  756. portCard.innerHTML = `
  757. <div class="flex items-center justify-between mb-2">
  758. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  759. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  760. </div>
  761. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  762. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  763. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  764. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  765. </div>
  766. `;
  767. matrix.appendChild(portCard);
  768. });
  769. const ifaceTbody = document.getElementById('quick-interfaces-table');
  770. if (ifaceTbody) {
  771. ifaceTbody.innerHTML = '';
  772. (state.interfaces || []).forEach(i => {
  773. const isUp = i.state === 'UP';
  774. const tr = document.createElement('tr');
  775. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  776. tr.onclick = () => openIfaceModal(i.name);
  777. const rxStr = i.rate?.rx_human || '0 B/s';
  778. const txStr = i.rate?.tx_human || '0 B/s';
  779. tr.innerHTML = `
  780. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  781. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  782. <span>${i.name}</span>
  783. </td>
  784. <td class="py-2.5 text-slate-300 font-sans">
  785. ${getRoleBadge(i.role || 'LAN')}
  786. </td>
  787. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  788. <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>
  789. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  790. <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>
  791. </td>
  792. <td class="py-2.5 text-right font-sans font-semibold">
  793. <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>
  794. </td>
  795. `;
  796. ifaceTbody.appendChild(tr);
  797. });
  798. }
  799. const vlanTbody = document.getElementById('quick-vlans-table');
  800. if (vlanTbody) {
  801. vlanTbody.innerHTML = '';
  802. }
  803. }
  804. // Expand / Collapse Handlers
  805. function toggleExpand(parentName) {
  806. if (state.expandedParents.has(parentName)) {
  807. state.expandedParents.delete(parentName);
  808. } else {
  809. state.expandedParents.add(parentName);
  810. }
  811. renderInterfacesList();
  812. }
  813. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  814. function supportsVLAN(iface) {
  815. if (!iface) return false;
  816. if (iface.is_vlan) return false;
  817. const name = (iface.name || '').toLowerCase();
  818. const type = (iface.type || '').toLowerCase();
  819. const role = (iface.role || '').toLowerCase();
  820. // Exclude loopback
  821. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  822. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  823. if (type === 'wireguard' || name.startsWith('wg')) return false;
  824. // Exclude PPP / PPPoE
  825. if (type === 'ppp' || name.startsWith('ppp')) return false;
  826. // Exclude other Layer 3 tunnels and dummy devices
  827. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  828. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  829. return false;
  830. }
  831. // If name already contains a dot, it's already a sub-interface
  832. if (name.includes('.')) return false;
  833. return true;
  834. }
  835. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  836. function supportsDHCPClient(iface) {
  837. if (!iface) return false;
  838. const name = (iface.name || '').toLowerCase();
  839. const type = (iface.type || '').toLowerCase();
  840. const role = (iface.role || '').toLowerCase();
  841. // Exclude loopback
  842. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  843. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  844. if (type === 'wireguard' || name.startsWith('wg')) return false;
  845. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  846. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  847. // Exclude other Layer 3 tunnels and dummy devices
  848. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  849. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  850. return false;
  851. }
  852. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  853. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  854. if (isBridgePort) return false;
  855. return true;
  856. }
  857. // Expand / Collapse Handlers
  858. function toggleExpand(parentName) {
  859. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  860. if (childVlans.length === 0) {
  861. // Cannot expand an interface with no VLANs
  862. state.expandedParents.delete(parentName);
  863. return;
  864. }
  865. if (state.expandedParents.has(parentName)) {
  866. state.expandedParents.delete(parentName);
  867. } else {
  868. state.expandedParents.add(parentName);
  869. }
  870. renderInterfacesList();
  871. }
  872. function expandAllIfaces(expand) {
  873. if (expand) {
  874. (state.interfaces || []).forEach(i => {
  875. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  876. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  877. });
  878. } else {
  879. state.expandedParents.clear();
  880. }
  881. renderInterfacesList();
  882. }
  883. // =========================================================================
  884. // INTERFACE ROLE TAGS MANAGEMENT
  885. // =========================================================================
  886. const ROLE_COLORS = {
  887. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  888. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  889. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  890. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  891. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  892. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  893. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  894. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  895. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  896. };
  897. function getRoleBadge(roleName) {
  898. const name = roleName || 'LAN';
  899. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  900. const colorKey = (role?.color || 'blue').toLowerCase();
  901. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  902. 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>`;
  903. }
  904. function switchIfaceSubTab(subTab) {
  905. state.activeIfaceSubTab = subTab;
  906. const treeTab = document.getElementById('ifaces-subtab-tree');
  907. const rolesTab = document.getElementById('ifaces-subtab-roles');
  908. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  909. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  910. if (subTab === 'roles') {
  911. treeTab?.classList.add('hidden');
  912. rolesTab?.classList.remove('hidden');
  913. if (btnRoles) {
  914. 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';
  915. }
  916. if (btnTree) {
  917. 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';
  918. }
  919. loadRoles();
  920. } else {
  921. rolesTab?.classList.add('hidden');
  922. treeTab?.classList.remove('hidden');
  923. if (btnTree) {
  924. 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';
  925. }
  926. if (btnRoles) {
  927. 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';
  928. }
  929. renderInterfacesList();
  930. }
  931. }
  932. async function loadRoles() {
  933. try {
  934. const res = await fetch(`${API_BASE}/roles`);
  935. if (res.ok) {
  936. state.roles = await res.json();
  937. const countEl = document.getElementById('badge-roles-count');
  938. if (countEl) countEl.innerText = (state.roles || []).length;
  939. renderRolesTable();
  940. populateRoleSelects();
  941. }
  942. } catch (err) {
  943. console.error('Failed to load role tags:', err);
  944. }
  945. }
  946. function renderRolesTable() {
  947. const tbody = document.getElementById('roles-table-body');
  948. const empty = document.getElementById('roles-empty-state');
  949. if (!tbody) return;
  950. const roles = state.roles || [];
  951. if (roles.length === 0) {
  952. tbody.innerHTML = '';
  953. empty?.classList.remove('hidden');
  954. return;
  955. }
  956. empty?.classList.add('hidden');
  957. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  958. if (tbody.dataset.sig === sig) return;
  959. tbody.dataset.sig = sig;
  960. tbody.innerHTML = roles.map(r => {
  961. const colorKey = (r.color || 'blue').toLowerCase();
  962. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  963. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  964. const ifacesChips = ifaces.length > 0
  965. ? 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('')
  966. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  967. return `
  968. <tr class="hover:bg-slate-800/40 transition">
  969. <td class="py-3 px-4">
  970. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  971. ${escapeHtml(r.name)}
  972. </span>
  973. </td>
  974. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  975. <span>${escapeHtml(r.name)}</span>
  976. ${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>' : ''}
  977. </td>
  978. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  979. <span class="inline-flex items-center gap-1.5">
  980. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  981. <span>${escapeHtml(r.color || 'blue')}</span>
  982. </span>
  983. </td>
  984. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  985. <td class="py-3 px-4 font-sans">
  986. <div class="flex flex-wrap items-center">
  987. ${ifacesChips}
  988. </div>
  989. </td>
  990. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  991. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  992. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  993. Edit
  994. </button>
  995. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  996. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  997. Delete
  998. </button>
  999. </td>
  1000. </tr>
  1001. `;
  1002. }).join('');
  1003. }
  1004. function openRoleModal(id = null) {
  1005. const modal = document.getElementById('role-modal');
  1006. if (!modal) return;
  1007. const idInput = document.getElementById('role-modal-id');
  1008. const nameInput = document.getElementById('role-modal-name');
  1009. const colorSelect = document.getElementById('role-modal-color');
  1010. const descInput = document.getElementById('role-modal-desc');
  1011. const title = document.getElementById('role-modal-title');
  1012. if (id) {
  1013. const role = (state.roles || []).find(r => r.id === id);
  1014. if (role) {
  1015. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1016. if (idInput) idInput.value = role.id;
  1017. if (nameInput) nameInput.value = role.name;
  1018. if (colorSelect) colorSelect.value = role.color || 'blue';
  1019. if (descInput) descInput.value = role.description || '';
  1020. }
  1021. } else {
  1022. if (title) title.innerText = 'Add Role Tag';
  1023. if (idInput) idInput.value = '';
  1024. if (nameInput) nameInput.value = '';
  1025. if (colorSelect) colorSelect.value = 'blue';
  1026. if (descInput) descInput.value = '';
  1027. }
  1028. updateRoleModalPreview();
  1029. modal.classList.remove('hidden');
  1030. }
  1031. function closeRoleModal() {
  1032. const modal = document.getElementById('role-modal');
  1033. if (modal) modal.classList.add('hidden');
  1034. }
  1035. function updateRoleModalPreview() {
  1036. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1037. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1038. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1039. const preview = document.getElementById('role-modal-preview');
  1040. if (preview) {
  1041. preview.innerText = name;
  1042. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1043. }
  1044. }
  1045. async function submitSaveRole(e) {
  1046. e.preventDefault();
  1047. const id = document.getElementById('role-modal-id')?.value;
  1048. const name = document.getElementById('role-modal-name')?.value.trim();
  1049. const color = document.getElementById('role-modal-color')?.value;
  1050. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1051. if (!name) return;
  1052. try {
  1053. const payload = { id, name, color, description: desc };
  1054. const method = id ? 'PUT' : 'POST';
  1055. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1056. const res = await fetch(url, {
  1057. method,
  1058. headers: { 'Content-Type': 'application/json' },
  1059. body: JSON.stringify(payload)
  1060. });
  1061. if (res.ok) {
  1062. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1063. closeRoleModal();
  1064. await loadRoles();
  1065. fetchData(false);
  1066. } else {
  1067. const err = await res.json();
  1068. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1069. }
  1070. } catch (err) {
  1071. showToast('Error', err.message, 'error');
  1072. }
  1073. }
  1074. async function deleteRoleTag(id, name) {
  1075. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1076. try {
  1077. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1078. method: 'DELETE'
  1079. });
  1080. if (res.ok) {
  1081. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1082. await loadRoles();
  1083. fetchData(false);
  1084. } else {
  1085. const err = await res.json();
  1086. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1087. }
  1088. } catch (err) {
  1089. showToast('Error', err.message, 'error');
  1090. }
  1091. }
  1092. function populateRoleSelects(selectedRole = '') {
  1093. const ifaceSelect = document.getElementById('modal-iface-role');
  1094. const vlanSelect = document.getElementById('vlan-role');
  1095. const roles = state.roles || [];
  1096. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1097. if (ifaceSelect) {
  1098. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1099. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1100. ifaceSelect.innerHTML = optionsHtml;
  1101. ifaceSelect.dataset.optionsSig = optionsHtml;
  1102. }
  1103. if (currentVal) ifaceSelect.value = currentVal;
  1104. }
  1105. if (vlanSelect) {
  1106. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1107. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1108. vlanSelect.innerHTML = optionsHtml;
  1109. vlanSelect.dataset.optionsSig = optionsHtml;
  1110. }
  1111. if (currentVal) vlanSelect.value = currentVal;
  1112. }
  1113. }
  1114. // Filter and Render Hierarchical Interfaces List
  1115. function filterIfaces(filter) {
  1116. state.ifaceFilter = filter || 'all';
  1117. renderInterfacesList();
  1118. }
  1119. function renderInterfacesList() {
  1120. const tbody = document.getElementById('interfaces-tree-tbody');
  1121. const emptyState = document.getElementById('interfaces-empty-state');
  1122. const summary = document.getElementById('ifaces-list-summary');
  1123. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1124. const allIfaces = state.interfaces || [];
  1125. const allVlans = state.vlans || [];
  1126. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1127. const filteredParents = parentIfaces.filter(parent => {
  1128. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1129. if (query) {
  1130. const matchName = parent.name.toLowerCase().includes(query);
  1131. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1132. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1133. const matchType = (parent.type || '').toLowerCase().includes(query);
  1134. const matchVlan = childVlans.some(v =>
  1135. v.name.toLowerCase().includes(query) ||
  1136. String(v.vlan_id).includes(query) ||
  1137. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1138. (v.description || '').toLowerCase().includes(query)
  1139. );
  1140. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1141. }
  1142. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1143. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1144. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1145. return true;
  1146. });
  1147. if (summary) {
  1148. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1149. }
  1150. if (filteredParents.length === 0) {
  1151. emptyState?.classList.remove('hidden');
  1152. tbody.innerHTML = '';
  1153. return;
  1154. }
  1155. emptyState?.classList.add('hidden');
  1156. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1157. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1158. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1159. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1160. }).join(';');
  1161. if (tbody.dataset.sig === sig) {
  1162. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1163. }
  1164. tbody.dataset.sig = sig;
  1165. tbody.innerHTML = '';
  1166. filteredParents.forEach(parent => {
  1167. const isUp = parent.state === 'UP';
  1168. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1169. const hasVlans = childVlans.length > 0;
  1170. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1171. const canHaveVlan = supportsVLAN(parent);
  1172. const parentRow = document.createElement('tr');
  1173. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1174. parentRow.innerHTML = `
  1175. <td class="py-3 px-3 text-center">
  1176. ${hasVlans ? `
  1177. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1178. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1179. <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">
  1180. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1181. </svg>
  1182. </button>
  1183. ` : `
  1184. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1185. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1186. </div>
  1187. `}
  1188. </td>
  1189. <td class="py-3 px-4">
  1190. <div class="flex items-center space-x-2.5">
  1191. <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">
  1192. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1193. </div>
  1194. <div>
  1195. <div class="flex items-center gap-2">
  1196. <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'}">
  1197. <span>${parent.name}</span>
  1198. <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>
  1199. </span>
  1200. ${hasVlans ? `
  1201. <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>
  1202. ` : `
  1203. <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>
  1204. `}
  1205. </div>
  1206. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1207. </div>
  1208. </div>
  1209. </td>
  1210. <td class="py-3 px-4 font-sans">
  1211. <div class="flex items-center gap-1.5">
  1212. ${getRoleBadge(parent.role || 'LAN')}
  1213. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1214. </div>
  1215. </td>
  1216. <td class="py-3 px-4">
  1217. ${parent.ipv4 && parent.ipv4.length > 0
  1218. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1219. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1220. }
  1221. ${(() => {
  1222. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1223. if (!c) return '';
  1224. 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');
  1225. 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>`;
  1226. })()}
  1227. </td>
  1228. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1229. <div>${parent.mac || 'N/A'}</div>
  1230. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1231. </td>
  1232. <td class="py-3 px-4 text-[11px]">
  1233. <div class="flex items-center space-x-2">
  1234. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1235. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1236. </div>
  1237. </td>
  1238. <td class="py-3 px-4 font-sans">
  1239. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1240. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1241. 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'
  1242. }" title="Click to toggle link status">
  1243. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1244. <span>${parent.state}</span>
  1245. </button>
  1246. </td>
  1247. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1248. ${(() => {
  1249. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1250. if (c) {
  1251. 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>`;
  1252. }
  1253. if (!supportsDHCPClient(parent)) {
  1254. return '';
  1255. }
  1256. 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>`;
  1257. })()}
  1258. ${canHaveVlan ? `
  1259. <button onclick="openVlanModal('${parent.name}')"
  1260. 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">
  1261. + Add VLAN
  1262. </button>
  1263. ` : ''}
  1264. <button onclick="openIfaceModal('${parent.name}')"
  1265. 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">
  1266. Edit
  1267. </button>
  1268. </td>
  1269. `;
  1270. tbody.appendChild(parentRow);
  1271. if (isExpanded) {
  1272. const drawerRow = document.createElement('tr');
  1273. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1274. const drawerCell = document.createElement('td');
  1275. drawerCell.colSpan = 8;
  1276. drawerCell.className = 'p-0';
  1277. drawerCell.innerHTML = `
  1278. <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">
  1279. <div class="flex items-center justify-between mb-3">
  1280. <div class="flex items-center space-x-3">
  1281. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1282. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1283. </span>
  1284. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1285. ${childVlans.length} Attached
  1286. </span>
  1287. </div>
  1288. <button onclick="openVlanModal('${parent.name}')"
  1289. 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">
  1290. <span>+ Create VLAN on ${parent.name}</span>
  1291. </button>
  1292. </div>
  1293. ${childVlans.length === 0 ? `
  1294. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1295. <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>
  1296. <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">
  1297. <span>+ Create Your First VLAN on ${parent.name}</span>
  1298. </button>
  1299. </div>
  1300. ` : `
  1301. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1302. <table class="w-full text-left text-xs font-mono">
  1303. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1304. <tr>
  1305. <th class="py-2.5 px-4">VLAN ID</th>
  1306. <th class="py-2.5 px-4">Interface Device</th>
  1307. <th class="py-2.5 px-4">Subnet Gateway</th>
  1308. <th class="py-2.5 px-4">Role / Alias</th>
  1309. <th class="py-2.5 px-4">MTU</th>
  1310. <th class="py-2.5 px-4">Throughput</th>
  1311. <th class="py-2.5 px-4">Status</th>
  1312. <th class="py-2.5 px-4 text-right">Actions</th>
  1313. </tr>
  1314. </thead>
  1315. <tbody class="divide-y divide-slate-800/70">
  1316. ${childVlans.map(v => {
  1317. const isVlanUp = v.state === 'UP';
  1318. return `
  1319. <tr class="hover:bg-slate-800/40 transition">
  1320. <td class="py-2.5 px-4">
  1321. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1322. VLAN ${v.vlan_id}
  1323. </span>
  1324. </td>
  1325. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1326. <span class="text-cyan-500">└─</span>
  1327. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1328. <span>${v.name}</span>
  1329. <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>
  1330. </span>
  1331. </td>
  1332. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1333. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1334. ${(() => {
  1335. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1336. if (!c) return '';
  1337. 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';
  1338. 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>`;
  1339. })()}
  1340. </td>
  1341. <td class="py-2.5 px-4 font-sans text-slate-300">
  1342. <div class="flex items-center gap-1.5">
  1343. ${getRoleBadge(v.role || 'LAN')}
  1344. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1345. </div>
  1346. </td>
  1347. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1348. <td class="py-2.5 px-4 text-[11px]">
  1349. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1350. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1351. </td>
  1352. <td class="py-2.5 px-4 font-sans">
  1353. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1354. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1355. 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'
  1356. }">
  1357. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1358. <span>${v.state}</span>
  1359. </button>
  1360. </td>
  1361. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1362. ${(() => {
  1363. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1364. if (c) {
  1365. 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>`;
  1366. }
  1367. if (!supportsDHCPClient(v)) {
  1368. return '';
  1369. }
  1370. 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>`;
  1371. })()}
  1372. <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>
  1373. <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>
  1374. </td>
  1375. </tr>
  1376. `;
  1377. }).join('')}
  1378. </tbody>
  1379. </table>
  1380. </div>
  1381. `}
  1382. </div>
  1383. `;
  1384. drawerRow.appendChild(drawerCell);
  1385. tbody.appendChild(drawerRow);
  1386. }
  1387. });
  1388. }
  1389. // Render VLANs Dedicated View
  1390. function renderVlansList() {
  1391. const tbody = document.getElementById('vlans-table-body');
  1392. if (!tbody) return;
  1393. const emptyState = document.getElementById('vlans-empty-state');
  1394. const countBadge = document.getElementById('vlans-table-count');
  1395. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1396. const allVlans = state.vlans || [];
  1397. if (countBadge) countBadge.innerText = allVlans.length;
  1398. const filtered = allVlans.filter(v => {
  1399. if (!query) return true;
  1400. return v.name.toLowerCase().includes(query) ||
  1401. String(v.vlan_id).includes(query) ||
  1402. (v.description || '').toLowerCase().includes(query) ||
  1403. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1404. });
  1405. if (allVlans.length === 0) {
  1406. emptyState.classList.remove('hidden');
  1407. tbody.innerHTML = '';
  1408. return;
  1409. }
  1410. emptyState.classList.add('hidden');
  1411. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1412. if (tbody.dataset.sig === sig) return;
  1413. tbody.dataset.sig = sig;
  1414. tbody.innerHTML = '';
  1415. filtered.forEach(v => {
  1416. const isUp = v.state === 'UP';
  1417. const tr = document.createElement('tr');
  1418. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1419. tr.innerHTML = `
  1420. <td class="py-3 px-4">
  1421. <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">
  1422. VLAN ${v.vlan_id}
  1423. </span>
  1424. </td>
  1425. <td class="py-3 px-4 font-bold text-white">
  1426. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1427. <span>${v.name}</span>
  1428. <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>
  1429. </span>
  1430. </td>
  1431. <td class="py-3 px-4 text-slate-300">
  1432. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1433. </td>
  1434. <td class="py-3 px-4 text-emerald-400 font-medium">
  1435. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1436. </td>
  1437. <td class="py-3 px-4 text-slate-300 font-sans">
  1438. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1439. </td>
  1440. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1441. <td class="py-3 px-4 font-sans">
  1442. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1443. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1444. 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'
  1445. }">
  1446. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1447. <span>${v.state}</span>
  1448. </button>
  1449. </td>
  1450. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1451. <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>
  1452. <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>
  1453. </td>
  1454. `;
  1455. tbody.appendChild(tr);
  1456. });
  1457. }
  1458. // Toggle interface UP / DOWN
  1459. async function toggleInterfaceState(name, newState) {
  1460. try {
  1461. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1462. method: 'POST',
  1463. headers: { 'Content-Type': 'application/json' },
  1464. body: JSON.stringify({ state: newState })
  1465. });
  1466. const data = await res.json();
  1467. if (res.ok) {
  1468. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1469. fetchData(false);
  1470. } else {
  1471. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1472. }
  1473. } catch (err) {
  1474. showToast('Error', err.message, 'error');
  1475. }
  1476. }
  1477. // ---------------- MikroTik Flag & Utilities ----------------
  1478. function renderMikroTikFlag(running, disabled) {
  1479. if (running) {
  1480. 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>`;
  1481. }
  1482. if (disabled) {
  1483. 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>`;
  1484. }
  1485. 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>`;
  1486. }
  1487. function copyToClipboard(text, label = 'Text') {
  1488. navigator.clipboard.writeText(text).then(() => {
  1489. showToast('Copied', `${label} copied to clipboard`, 'success');
  1490. }).catch(() => {
  1491. prompt('Copy value:', text);
  1492. });
  1493. }
  1494. // ======================== PPP Profiles Shared Helper ========================
  1495. async function fetchPPPProfilesList() {
  1496. try {
  1497. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1498. if (res.ok) {
  1499. state.pppProfiles = await res.json();
  1500. }
  1501. } catch (err) {
  1502. console.error('Failed to load PPP profiles:', err);
  1503. }
  1504. }
  1505. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1506. const sel = document.getElementById(selectId);
  1507. if (!sel) return;
  1508. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1509. { name: 'default', use_encryption: 'no' },
  1510. { name: 'default-encryption', use_encryption: 'required' }
  1511. ];
  1512. sel.innerHTML = '';
  1513. profiles.forEach(p => {
  1514. const opt = document.createElement('option');
  1515. opt.value = p.name;
  1516. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1517. opt.innerText = `${p.name}${encBadge}`;
  1518. sel.appendChild(opt);
  1519. });
  1520. if (selectedVal) {
  1521. sel.value = selectedVal;
  1522. } else {
  1523. sel.value = defaultVal;
  1524. }
  1525. if (!sel.value && sel.options.length > 0) {
  1526. sel.selectedIndex = 0;
  1527. }
  1528. }
  1529. // ======================== PPPoE Multi-Instance ========================
  1530. async function loadPPPoE(populateInputs = true) {
  1531. try {
  1532. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1533. await fetchPPPProfilesList();
  1534. }
  1535. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1536. const list = await res.json();
  1537. state.pppoeList = Array.isArray(list) ? list : [];
  1538. const badge = document.getElementById('pppoe-count-badge');
  1539. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1540. const tbody = document.getElementById('pppoe-table-body');
  1541. const empty = document.getElementById('pppoe-empty');
  1542. if (!tbody) return;
  1543. tbody.innerHTML = '';
  1544. if (state.pppoeList.length === 0) {
  1545. if (empty) empty.classList.remove('hidden');
  1546. } else {
  1547. if (empty) empty.classList.add('hidden');
  1548. state.pppoeList.forEach(inst => {
  1549. const tr = document.createElement('tr');
  1550. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1551. tr.innerHTML = `
  1552. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1553. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1554. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1555. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1556. <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>
  1557. <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>
  1558. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1559. <td class="py-2.5 px-3 text-center">
  1560. <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'}">
  1561. ${inst.default_route ? 'Yes' : 'No'}
  1562. </span>
  1563. </td>
  1564. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1565. ${inst.running ? `
  1566. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1567. ` : `
  1568. <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>
  1569. `}
  1570. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1571. ${inst.disabled ? 'Enable' : 'Disable'}
  1572. </button>
  1573. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1574. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1575. </td>
  1576. `;
  1577. tbody.appendChild(tr);
  1578. });
  1579. }
  1580. } catch (err) {
  1581. console.error('Failed to load PPPoE:', err);
  1582. }
  1583. }
  1584. function openAddPPPoEModal() {
  1585. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1586. document.getElementById('pppoe-modal-edit-orig').value = '';
  1587. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1588. document.getElementById('pppoe-modal-name').readOnly = false;
  1589. document.getElementById('pppoe-modal-user').value = '';
  1590. document.getElementById('pppoe-modal-pass').value = '';
  1591. document.getElementById('pppoe-modal-service').value = '';
  1592. document.getElementById('pppoe-modal-mtu').value = '1492';
  1593. document.getElementById('pppoe-modal-defroute').checked = true;
  1594. document.getElementById('pppoe-modal-reconnect').checked = true;
  1595. document.getElementById('pppoe-modal-disabled').checked = false;
  1596. // Populate profiles
  1597. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1598. // Populate interfaces
  1599. const sel = document.getElementById('pppoe-modal-iface');
  1600. sel.innerHTML = '';
  1601. (state.interfaces || []).forEach(i => {
  1602. if (i.name === 'lo') return;
  1603. const opt = document.createElement('option');
  1604. opt.value = i.name;
  1605. opt.innerText = `${i.name} (${i.role || i.type})`;
  1606. sel.appendChild(opt);
  1607. });
  1608. document.getElementById('pppoe-modal').classList.remove('hidden');
  1609. }
  1610. function openEditPPPoEModal(name) {
  1611. const inst = (state.pppoeList || []).find(i => i.name === name);
  1612. if (!inst) return;
  1613. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1614. document.getElementById('pppoe-modal-edit-orig').value = name;
  1615. document.getElementById('pppoe-modal-name').value = inst.name;
  1616. document.getElementById('pppoe-modal-name').readOnly = true;
  1617. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1618. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1619. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1620. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1621. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1622. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1623. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1624. // Populate profiles
  1625. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1626. const sel = document.getElementById('pppoe-modal-iface');
  1627. sel.innerHTML = '';
  1628. (state.interfaces || []).forEach(i => {
  1629. if (i.name === 'lo') return;
  1630. const opt = document.createElement('option');
  1631. opt.value = i.name;
  1632. opt.innerText = `${i.name} (${i.role || i.type})`;
  1633. if (i.name === inst.interface) opt.selected = true;
  1634. sel.appendChild(opt);
  1635. });
  1636. document.getElementById('pppoe-modal').classList.remove('hidden');
  1637. }
  1638. function closePPPoEModal() {
  1639. document.getElementById('pppoe-modal').classList.add('hidden');
  1640. }
  1641. async function submitSavePPPoE(e) {
  1642. e.preventDefault();
  1643. const name = document.getElementById('pppoe-modal-name').value.trim();
  1644. const iface = document.getElementById('pppoe-modal-iface').value;
  1645. const user = document.getElementById('pppoe-modal-user').value.trim();
  1646. const pass = document.getElementById('pppoe-modal-pass').value;
  1647. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1648. const service = document.getElementById('pppoe-modal-service').value.trim();
  1649. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1650. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1651. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1652. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1653. try {
  1654. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1655. method: 'POST',
  1656. headers: { 'Content-Type': 'application/json' },
  1657. body: JSON.stringify({
  1658. name,
  1659. interface: iface,
  1660. username: user,
  1661. password: pass,
  1662. profile: profile,
  1663. service_name: service,
  1664. mtu,
  1665. default_route: defRoute,
  1666. auto_reconnect: reconnect,
  1667. disabled
  1668. })
  1669. });
  1670. if (res.ok) {
  1671. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1672. closePPPoEModal();
  1673. loadPPPoE(false);
  1674. fetchData(false);
  1675. } else {
  1676. const err = await res.json();
  1677. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1678. }
  1679. } catch (err) {
  1680. showToast('Error', err.message, 'error');
  1681. }
  1682. }
  1683. async function connectPPPoEInstance(name) {
  1684. try {
  1685. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1686. if (res.ok) {
  1687. showToast('Connecting', `Dialing ${name}...`, 'info');
  1688. setTimeout(() => loadPPPoE(false), 2000);
  1689. }
  1690. } catch (err) {
  1691. showToast('Error', err.message, 'error');
  1692. }
  1693. }
  1694. async function disconnectPPPoEInstance(name) {
  1695. try {
  1696. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1697. if (res.ok) {
  1698. showToast('Disconnected', `${name} session terminated`, 'info');
  1699. setTimeout(() => loadPPPoE(false), 1000);
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function togglePPPoEState(name, enable) {
  1706. try {
  1707. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1708. method: 'POST',
  1709. headers: { 'Content-Type': 'application/json' },
  1710. body: JSON.stringify({ enabled: enable })
  1711. });
  1712. if (res.ok) {
  1713. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1714. loadPPPoE(false);
  1715. }
  1716. } catch (err) {
  1717. showToast('Error', err.message, 'error');
  1718. }
  1719. }
  1720. async function deletePPPoEInstance(name) {
  1721. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1722. try {
  1723. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1724. if (res.ok) {
  1725. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1726. loadPPPoE(false);
  1727. fetchData(false);
  1728. }
  1729. } catch (err) {
  1730. showToast('Error', err.message, 'error');
  1731. }
  1732. }
  1733. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1734. state.wgSubTab = 'ifaces';
  1735. function switchWGSubTab(tab) {
  1736. state.wgSubTab = tab;
  1737. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1738. const peersPanel = document.getElementById('wg-subtab-peers');
  1739. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1740. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1741. if (tab === 'ifaces') {
  1742. ifacesPanel?.classList.remove('hidden');
  1743. peersPanel?.classList.add('hidden');
  1744. 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';
  1745. 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';
  1746. } else {
  1747. ifacesPanel?.classList.add('hidden');
  1748. peersPanel?.classList.remove('hidden');
  1749. 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';
  1750. 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';
  1751. renderWGPeers();
  1752. }
  1753. }
  1754. async function loadWireGuard(populateInputs = true) {
  1755. try {
  1756. const [ifacesRes, peersRes] = await Promise.all([
  1757. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1758. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1759. ]);
  1760. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1761. const peers = peersRes.ok ? await peersRes.json() : [];
  1762. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1763. state.wgPeers = Array.isArray(peers) ? peers : [];
  1764. // Badges
  1765. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1766. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1767. const peersCountBadge = document.getElementById('wg-peers-count');
  1768. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1769. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1770. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1771. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1772. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1773. // Render Interfaces
  1774. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1775. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1776. if (ifacesTbody) {
  1777. ifacesTbody.innerHTML = '';
  1778. if (state.wgInterfaces.length === 0) {
  1779. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1780. } else {
  1781. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1782. state.wgInterfaces.forEach(iface => {
  1783. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1784. const tr = document.createElement('tr');
  1785. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1786. tr.innerHTML = `
  1787. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1788. <td class="py-2.5 px-3">
  1789. <div class="flex items-center gap-1.5">
  1790. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1791. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1792. </div>
  1793. </td>
  1794. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1795. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1796. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1797. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1798. ${(iface.public_key || '').substring(0, 10)}... 📋
  1799. </span>
  1800. </td>
  1801. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1802. <td class="py-2.5 px-3 text-center">
  1803. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1804. </td>
  1805. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1806. ${iface.running ? `
  1807. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1808. ` : `
  1809. <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>
  1810. `}
  1811. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1812. ${iface.disabled ? 'Enable' : 'Disable'}
  1813. </button>
  1814. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1815. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1816. </td>
  1817. `;
  1818. ifacesTbody.appendChild(tr);
  1819. });
  1820. }
  1821. }
  1822. // Populate filter dropdown in peers tab
  1823. const filterSel = document.getElementById('wg-peers-filter-iface');
  1824. if (filterSel) {
  1825. const currentVal = filterSel.value;
  1826. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1827. state.wgInterfaces.forEach(i => {
  1828. const opt = document.createElement('option');
  1829. opt.value = i.name;
  1830. opt.innerText = i.name;
  1831. if (i.name === currentVal) opt.selected = true;
  1832. filterSel.appendChild(opt);
  1833. });
  1834. }
  1835. renderWGPeers();
  1836. } catch (err) {
  1837. console.error('Failed to load WireGuard:', err);
  1838. }
  1839. }
  1840. function formatWGPeerEndpoint(address, port) {
  1841. if (!address || address === '(none)') return '--';
  1842. let addr = address.trim();
  1843. let p = port || 0;
  1844. while (addr.includes(':') && !addr.startsWith('[')) {
  1845. const lastColon = addr.lastIndexOf(':');
  1846. const maybePort = addr.substring(lastColon + 1);
  1847. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1848. if (!p) p = parseInt(maybePort, 10);
  1849. addr = addr.substring(0, lastColon);
  1850. } else {
  1851. break;
  1852. }
  1853. }
  1854. return p ? `${addr}:${p}` : addr;
  1855. }
  1856. function renderWGPeers() {
  1857. const filterSel = document.getElementById('wg-peers-filter-iface');
  1858. const selectedIface = filterSel ? filterSel.value : '';
  1859. const tbody = document.getElementById('wg-peers-table-body');
  1860. const empty = document.getElementById('wg-peers-empty');
  1861. if (!tbody) return;
  1862. tbody.innerHTML = '';
  1863. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1864. if (filtered.length === 0) {
  1865. if (empty) empty.classList.remove('hidden');
  1866. } else {
  1867. if (empty) empty.classList.add('hidden');
  1868. filtered.forEach(p => {
  1869. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1870. const tr = document.createElement('tr');
  1871. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1872. tr.innerHTML = `
  1873. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1874. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1875. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1876. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1877. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1878. ${(p.public_key || '').substring(0, 10)}... 📋
  1879. </span>
  1880. </td>
  1881. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1882. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1883. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1884. <td class="py-2.5 px-3 font-mono text-[11px]">
  1885. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1886. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1887. </td>
  1888. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1889. <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">
  1890. ${p.disabled ? 'Enable' : 'Disable'}
  1891. </button>
  1892. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1893. <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>
  1894. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1895. </td>
  1896. `;
  1897. tbody.appendChild(tr);
  1898. });
  1899. }
  1900. }
  1901. function openAddWGInterfaceModal() {
  1902. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1903. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1904. const nameEl = document.getElementById('wg-iface-modal-name');
  1905. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1906. nameEl.readOnly = false;
  1907. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1908. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1909. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1910. document.getElementById('wg-iface-modal-comment').value = '';
  1911. document.getElementById('wg-iface-modal-pubkey').value = '';
  1912. document.getElementById('wg-iface-modal-privkey').value = '';
  1913. document.getElementById('wg-iface-modal-disabled').checked = false;
  1914. generateWGInterfaceKeys();
  1915. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1916. }
  1917. function openEditWGInterfaceModal(name) {
  1918. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1919. if (!iface) return;
  1920. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1921. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1922. const nameEl = document.getElementById('wg-iface-modal-name');
  1923. nameEl.value = iface.name;
  1924. nameEl.readOnly = false; // ALLOW RENAMING
  1925. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1926. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1927. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1928. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1929. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1930. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1931. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1932. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1933. }
  1934. function closeAddWGInterfaceModal() {
  1935. document.getElementById('wg-iface-modal').classList.add('hidden');
  1936. }
  1937. async function generateWGInterfaceKeys() {
  1938. try {
  1939. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1940. const keys = await res.json();
  1941. if (res.ok) {
  1942. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1943. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1944. }
  1945. } catch (err) {
  1946. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1947. }
  1948. }
  1949. async function onWGInterfacePrivKeyInput() {
  1950. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1951. if (!privKey) return;
  1952. try {
  1953. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1954. method: 'POST',
  1955. headers: { 'Content-Type': 'application/json' },
  1956. body: JSON.stringify({ private_key: privKey })
  1957. });
  1958. if (res.ok) {
  1959. const data = await res.json();
  1960. if (data.public_key) {
  1961. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1962. }
  1963. }
  1964. } catch (err) {
  1965. // Ignore while typing
  1966. }
  1967. }
  1968. function toggleWGPrivKeyVisibility() {
  1969. const el = document.getElementById('wg-iface-modal-privkey');
  1970. const btn = document.getElementById('btn-toggle-wg-privkey');
  1971. if (el.type === 'password') {
  1972. el.type = 'text';
  1973. btn.innerText = '🙈 Hide';
  1974. } else {
  1975. el.type = 'password';
  1976. btn.innerText = '👁️ Show';
  1977. }
  1978. }
  1979. function copyWGInterfacePubKey() {
  1980. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1981. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1982. }
  1983. async function submitSaveWGInterface(e) {
  1984. e.preventDefault();
  1985. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1986. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1987. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1988. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1989. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1990. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1991. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1992. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1993. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1994. try {
  1995. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1996. method: 'POST',
  1997. headers: { 'Content-Type': 'application/json' },
  1998. body: JSON.stringify({
  1999. orig_name: origName,
  2000. name,
  2001. listen_port: port,
  2002. address: addr,
  2003. mtu,
  2004. comment,
  2005. public_key: pub,
  2006. private_key: priv,
  2007. disabled
  2008. })
  2009. });
  2010. const data = await res.json();
  2011. if (res.ok) {
  2012. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2013. closeAddWGInterfaceModal();
  2014. loadWireGuard(false);
  2015. fetchData(false);
  2016. } else {
  2017. showToast('Error', data.error || 'Failed to save interface', 'error');
  2018. }
  2019. } catch (err) {
  2020. showToast('Error', err.message, 'error');
  2021. }
  2022. }
  2023. async function startWGInterface(name) {
  2024. try {
  2025. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2026. if (res.ok) {
  2027. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2028. loadWireGuard(false);
  2029. fetchData(false);
  2030. }
  2031. } catch (err) {
  2032. showToast('Error', err.message, 'error');
  2033. }
  2034. }
  2035. async function stopWGInterface(name) {
  2036. try {
  2037. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2038. if (res.ok) {
  2039. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2040. loadWireGuard(false);
  2041. fetchData(false);
  2042. }
  2043. } catch (err) {
  2044. showToast('Error', err.message, 'error');
  2045. }
  2046. }
  2047. async function toggleWGInterfaceState(name, enable) {
  2048. try {
  2049. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2050. method: 'POST',
  2051. headers: { 'Content-Type': 'application/json' },
  2052. body: JSON.stringify({ enabled: enable })
  2053. });
  2054. if (res.ok) {
  2055. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2056. loadWireGuard(false);
  2057. fetchData(false);
  2058. }
  2059. } catch (err) {
  2060. showToast('Error', err.message, 'error');
  2061. }
  2062. }
  2063. async function deleteWGInterface(name) {
  2064. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2065. try {
  2066. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2067. if (res.ok) {
  2068. showToast('Deleted', `Interface ${name} removed`, 'success');
  2069. loadWireGuard(false);
  2070. fetchData(false);
  2071. }
  2072. } catch (err) {
  2073. showToast('Error', err.message, 'error');
  2074. }
  2075. }
  2076. function populateWGPeerIfaceSelect(selectedIface = '') {
  2077. const sel = document.getElementById('wg-peer-modal-iface');
  2078. if (!sel) return;
  2079. sel.innerHTML = '';
  2080. (state.wgInterfaces || []).forEach(i => {
  2081. const opt = document.createElement('option');
  2082. opt.value = i.name;
  2083. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2084. if (i.name === selectedIface) opt.selected = true;
  2085. sel.appendChild(opt);
  2086. });
  2087. }
  2088. function openAddWGPeerModal() {
  2089. if ((state.wgInterfaces || []).length === 0) {
  2090. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2091. openAddWGInterfaceModal();
  2092. return;
  2093. }
  2094. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2095. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2096. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2097. populateWGPeerIfaceSelect();
  2098. document.getElementById('wg-peer-modal-name').value = '';
  2099. document.getElementById('wg-peer-modal-pubkey').value = '';
  2100. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2101. document.getElementById('wg-peer-modal-endpoint').value = '';
  2102. document.getElementById('wg-peer-modal-port').value = '';
  2103. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2104. document.getElementById('wg-peer-modal-preshared').value = '';
  2105. document.getElementById('wg-peer-modal-disabled').checked = false;
  2106. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2107. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2108. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2109. }
  2110. function openEditWGPeerModal(ifaceName, pubKey) {
  2111. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2112. if (!peer) {
  2113. showToast('Not Found', 'Peer not found', 'warning');
  2114. return;
  2115. }
  2116. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2117. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2118. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2119. populateWGPeerIfaceSelect(peer.interface);
  2120. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2121. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2122. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2123. let epHost = (peer.endpoint_address || '').trim();
  2124. let epPort = peer.endpoint_port || '';
  2125. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2126. const lastColon = epHost.lastIndexOf(':');
  2127. const maybePort = epHost.substring(lastColon + 1);
  2128. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2129. if (!epPort) epPort = parseInt(maybePort, 10);
  2130. epHost = epHost.substring(0, lastColon);
  2131. } else {
  2132. break;
  2133. }
  2134. }
  2135. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2136. document.getElementById('wg-peer-modal-port').value = epPort;
  2137. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2138. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2139. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2140. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2141. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2142. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2143. }
  2144. function closeAddWGPeerModal() {
  2145. document.getElementById('wg-peer-modal').classList.add('hidden');
  2146. }
  2147. async function generatePeerKeypairHelper() {
  2148. try {
  2149. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2150. const keys = await res.json();
  2151. if (res.ok) {
  2152. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2153. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2154. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2155. checkWGPeerKeyValidity();
  2156. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2157. }
  2158. } catch (err) {
  2159. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2160. }
  2161. }
  2162. function copyGeneratedPeerPrivKey() {
  2163. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2164. if (priv) copyToClipboard(priv, 'Client Private Key');
  2165. }
  2166. async function generatePeerPSK() {
  2167. try {
  2168. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2169. const keys = await res.json();
  2170. if (res.ok && keys.private_key) {
  2171. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2172. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2173. }
  2174. } catch (err) {
  2175. showToast('Error', err.message, 'error');
  2176. }
  2177. }
  2178. function checkWGPeerKeyValidity() {
  2179. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2180. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2181. const warningEl = document.getElementById('wg-peer-key-warning');
  2182. if (!warningEl) return;
  2183. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2184. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2185. warningEl.classList.remove('hidden');
  2186. } else {
  2187. warningEl.classList.add('hidden');
  2188. }
  2189. }
  2190. async function submitSaveWGPeer(e) {
  2191. e.preventDefault();
  2192. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2193. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2194. const iface = document.getElementById('wg-peer-modal-iface').value;
  2195. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2196. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2197. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2198. .split(',')
  2199. .map(s => s.trim())
  2200. .filter(s => s.length > 0);
  2201. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2202. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2203. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2204. const lastColon = epHost.lastIndexOf(':');
  2205. const maybePort = epHost.substring(lastColon + 1);
  2206. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2207. if (!epPort) epPort = parseInt(maybePort, 10);
  2208. epHost = epHost.substring(0, lastColon);
  2209. } else {
  2210. break;
  2211. }
  2212. }
  2213. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2214. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2215. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2216. // Validation
  2217. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2218. if (targetIface && targetIface.public_key === pub) {
  2219. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2220. return;
  2221. }
  2222. try {
  2223. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2224. method: 'POST',
  2225. headers: { 'Content-Type': 'application/json' },
  2226. body: JSON.stringify({
  2227. orig_interface: origIface,
  2228. orig_public_key: origPubKey,
  2229. interface: iface,
  2230. name,
  2231. public_key: pub,
  2232. allowed_ips: allowed,
  2233. endpoint_address: epHost,
  2234. endpoint_port: epPort,
  2235. persistent_keepalive: keepalive,
  2236. preshared_key: psk,
  2237. disabled
  2238. })
  2239. });
  2240. const data = await res.json();
  2241. if (res.ok) {
  2242. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2243. closeAddWGPeerModal();
  2244. loadWireGuard(false);
  2245. } else {
  2246. showToast('Error', data.error || 'Failed to save peer', 'error');
  2247. }
  2248. } catch (err) {
  2249. showToast('Error', err.message, 'error');
  2250. }
  2251. }
  2252. async function toggleWGPeerState(iface, pubkey, enable) {
  2253. try {
  2254. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2255. method: 'POST',
  2256. headers: { 'Content-Type': 'application/json' },
  2257. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2258. });
  2259. const data = await res.json();
  2260. if (res.ok) {
  2261. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2262. loadWireGuard(false);
  2263. } else {
  2264. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2265. }
  2266. } catch (err) {
  2267. showToast('Error', err.message, 'error');
  2268. }
  2269. }
  2270. async function deleteWGPeer(iface, pubkey) {
  2271. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2272. try {
  2273. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2274. method: 'POST',
  2275. headers: { 'Content-Type': 'application/json' },
  2276. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2277. });
  2278. const data = await res.json();
  2279. if (res.ok) {
  2280. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2281. loadWireGuard(false);
  2282. } else {
  2283. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2284. }
  2285. } catch (err) {
  2286. showToast('Error', err.message, 'error');
  2287. }
  2288. }
  2289. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2290. function switchIpsecModalTab(tab) {
  2291. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2292. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2293. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2294. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2295. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2296. if (tab === 'p1') {
  2297. if (p1Tab) {
  2298. 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';
  2299. }
  2300. if (p2Tab) {
  2301. 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';
  2302. }
  2303. if (p1Content) p1Content.classList.remove('hidden');
  2304. if (p2Content) p2Content.classList.add('hidden');
  2305. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2306. } else {
  2307. if (p1Tab) {
  2308. 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';
  2309. }
  2310. if (p2Tab) {
  2311. 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';
  2312. }
  2313. if (p1Content) p1Content.classList.add('hidden');
  2314. if (p2Content) p2Content.classList.remove('hidden');
  2315. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2316. }
  2317. }
  2318. function toggleIpsecPhaseStep() {
  2319. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2320. if (p1Content && !p1Content.classList.contains('hidden')) {
  2321. switchIpsecModalTab('p2');
  2322. } else {
  2323. switchIpsecModalTab('p1');
  2324. }
  2325. }
  2326. function toggleIpsecPskVisibility() {
  2327. const pskInput = document.getElementById('ipsec-modal-psk');
  2328. if (!pskInput) return;
  2329. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2330. }
  2331. function addIpsecLocalSubnet(val = '') {
  2332. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2333. if (!container) return;
  2334. const row = document.createElement('div');
  2335. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2336. row.innerHTML = `
  2337. <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">
  2338. <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>
  2339. `;
  2340. container.appendChild(row);
  2341. }
  2342. function addIpsecRemoteSubnet(val = '') {
  2343. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2344. if (!container) return;
  2345. const row = document.createElement('div');
  2346. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2347. row.innerHTML = `
  2348. <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">
  2349. <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>
  2350. `;
  2351. container.appendChild(row);
  2352. }
  2353. function updateIpsecEspProposalFromPFS(val) {
  2354. const prop = document.getElementById('ipsec-modal-espprop');
  2355. if (!prop) return;
  2356. if (val === 'none') {
  2357. prop.value = 'aes256-sha256,aes128-sha256,default';
  2358. } else {
  2359. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2360. }
  2361. }
  2362. function updateIpsecIkeProposalFromDH(dh) {
  2363. const el = document.getElementById('ipsec-modal-ikeprop');
  2364. if (el) {
  2365. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2366. }
  2367. }
  2368. function safeSetVal(id, val) {
  2369. const el = document.getElementById(id);
  2370. if (el) el.value = val;
  2371. }
  2372. function safeSetChecked(id, val) {
  2373. const el = document.getElementById(id);
  2374. if (el) el.checked = !!val;
  2375. }
  2376. function safeGetVal(id, def = '') {
  2377. const el = document.getElementById(id);
  2378. return el ? el.value : def;
  2379. }
  2380. async function loadIPSec(populateInputs = true) {
  2381. try {
  2382. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2383. const list = await res.json();
  2384. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2385. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2386. const badge = document.getElementById('ipsec-sas-badge');
  2387. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2388. const tbody = document.getElementById('ipsec-table-body');
  2389. const empty = document.getElementById('ipsec-empty');
  2390. if (!tbody) return;
  2391. tbody.innerHTML = '';
  2392. if (state.ipsecTunnels.length === 0) {
  2393. if (empty) empty.classList.remove('hidden');
  2394. } else {
  2395. if (empty) empty.classList.add('hidden');
  2396. state.ipsecTunnels.forEach(c => {
  2397. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2398. const tr = document.createElement('tr');
  2399. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2400. // Local subnets tags
  2401. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2402. 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('');
  2403. // Remote subnets tags
  2404. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2405. 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('');
  2406. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2407. const p2Name = c.phase2_name || `${c.name}_p2`;
  2408. tr.innerHTML = `
  2409. <td class="py-2.5 px-3 text-center">
  2410. ${isEstablished ? `
  2411. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2412. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2413. <span>UP</span>
  2414. </span>
  2415. ` : (c.disabled ? `
  2416. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2417. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2418. <span>DOWN</span>
  2419. </span>
  2420. ` : `
  2421. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2422. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2423. <span>IDLE</span>
  2424. </span>
  2425. `)}
  2426. </td>
  2427. <td class="py-2.5 px-4 font-bold text-white">
  2428. <div class="flex items-center gap-2">
  2429. <span class="text-amber-400">🛡</span>
  2430. <div>
  2431. <div>${escapeHtml(c.name)}</div>
  2432. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2433. </div>
  2434. </div>
  2435. </td>
  2436. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2437. <td class="py-2.5 px-4 font-sans">
  2438. <div class="flex items-center gap-1.5">
  2439. <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>
  2440. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2441. </div>
  2442. </td>
  2443. <td class="py-2.5 px-4">
  2444. <div class="space-y-1">
  2445. <div class="flex items-center flex-wrap gap-1">
  2446. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2447. ${localBadges}
  2448. </div>
  2449. <div class="flex items-center flex-wrap gap-1">
  2450. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2451. ${remoteBadges}
  2452. </div>
  2453. </div>
  2454. </td>
  2455. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2456. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2457. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2458. </div>
  2459. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2460. </td>
  2461. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2462. ${isEstablished ? `
  2463. <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>
  2464. ` : `
  2465. <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>
  2466. `}
  2467. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2468. ${c.disabled ? 'Enable' : 'Disable'}
  2469. </button>
  2470. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2471. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2472. </td>
  2473. `;
  2474. tbody.appendChild(tr);
  2475. });
  2476. }
  2477. } catch (err) {
  2478. console.error('Failed to load IPSec:', err);
  2479. }
  2480. }
  2481. function openAddIPSecModal() {
  2482. const modal = document.getElementById('ipsec-modal');
  2483. if (!modal) return;
  2484. const title = document.getElementById('ipsec-modal-title');
  2485. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2486. // Phase 1 Fields
  2487. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2488. const nameEl = document.getElementById('ipsec-modal-name');
  2489. if (nameEl) nameEl.readOnly = false;
  2490. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2491. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2492. safeSetVal('ipsec-modal-remotegw', '');
  2493. safeSetVal('ipsec-modal-localaddrs', '');
  2494. safeSetVal('ipsec-modal-comments', '');
  2495. safeSetVal('ipsec-modal-psk', '');
  2496. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2497. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2498. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2499. safeSetVal('ipsec-modal-localid', '');
  2500. safeSetVal('ipsec-modal-remoteid', '');
  2501. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2502. // Phase 2 Fields
  2503. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2504. safeSetVal('ipsec-modal-espkeylife', '28800');
  2505. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2506. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2507. safeSetChecked('ipsec-modal-autostart', true);
  2508. safeSetChecked('ipsec-modal-disabled', false);
  2509. // Clear & Populate default dynamic subnets
  2510. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2511. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2512. if (localContainer) {
  2513. localContainer.innerHTML = '';
  2514. addIpsecLocalSubnet('192.168.10.0/24');
  2515. }
  2516. if (remoteContainer) {
  2517. remoteContainer.innerHTML = '';
  2518. addIpsecRemoteSubnet('192.168.20.0/24');
  2519. }
  2520. switchIpsecModalTab('p1');
  2521. modal.classList.remove('hidden');
  2522. }
  2523. function openEditIPSecModal(name) {
  2524. const modal = document.getElementById('ipsec-modal');
  2525. if (!modal) return;
  2526. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2527. if (!conn) return;
  2528. const title = document.getElementById('ipsec-modal-title');
  2529. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2530. // Phase 1 Fields
  2531. safeSetVal('ipsec-modal-name', conn.name);
  2532. const nameEl = document.getElementById('ipsec-modal-name');
  2533. if (nameEl) nameEl.readOnly = true;
  2534. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2535. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2536. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2537. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2538. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2539. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2540. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2541. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2542. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2543. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2544. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2545. // Phase 2 Fields
  2546. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2547. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2548. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2549. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2550. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2551. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2552. // Populate dynamic subnets
  2553. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2554. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2555. if (localContainer) {
  2556. localContainer.innerHTML = '';
  2557. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2558. locals.forEach(s => addIpsecLocalSubnet(s));
  2559. }
  2560. if (remoteContainer) {
  2561. remoteContainer.innerHTML = '';
  2562. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2563. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2564. }
  2565. switchIpsecModalTab('p1');
  2566. modal.classList.remove('hidden');
  2567. }
  2568. function closeAddIPSecModal() {
  2569. const modal = document.getElementById('ipsec-modal');
  2570. if (modal) modal.classList.add('hidden');
  2571. }
  2572. async function submitSaveIPSec(e) {
  2573. if (e) e.preventDefault();
  2574. const name = safeGetVal('ipsec-modal-name').trim();
  2575. if (!name) {
  2576. showToast('Error', 'Tunnel name is required', 'error');
  2577. return;
  2578. }
  2579. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2580. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2581. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2582. const comments = safeGetVal('ipsec-modal-comments').trim();
  2583. const psk = safeGetVal('ipsec-modal-psk');
  2584. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2585. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2586. const localId = safeGetVal('ipsec-modal-localid').trim();
  2587. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2588. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2589. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2590. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2591. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2592. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2593. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2594. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2595. // Scrape dynamic local and remote subnets
  2596. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2597. const localSubnets = [];
  2598. localInputs.forEach(inp => {
  2599. const v = inp.value.trim();
  2600. if (v) localSubnets.push(v);
  2601. });
  2602. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2603. const remoteSubnets = [];
  2604. remoteInputs.forEach(inp => {
  2605. const v = inp.value.trim();
  2606. if (v) remoteSubnets.push(v);
  2607. });
  2608. try {
  2609. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2610. method: 'POST',
  2611. headers: { 'Content-Type': 'application/json' },
  2612. body: JSON.stringify({
  2613. name,
  2614. comment: comments,
  2615. ike_version: ikeVersion,
  2616. local_addrs: localAddrs,
  2617. remote_addrs: remotegw,
  2618. preshared_key: psk,
  2619. ike_proposals: ikeProposals,
  2620. ike_keylife: ikeKeylife,
  2621. local_id: localId,
  2622. remote_id: remoteId,
  2623. dpd: dpd,
  2624. phase2_name: phase2Name,
  2625. esp_proposals: espProposals,
  2626. esp_keylife: espKeylife,
  2627. pfs_group: pfsGroup,
  2628. pfs: pfsGroup !== 'none',
  2629. local_subnets: localSubnets,
  2630. remote_subnets: remoteSubnets,
  2631. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2632. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2633. auto_start: autostart,
  2634. disabled
  2635. })
  2636. });
  2637. if (res.ok) {
  2638. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2639. closeAddIPSecModal();
  2640. loadIPSec(false);
  2641. } else {
  2642. const err = await res.json();
  2643. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2644. }
  2645. } catch (err) {
  2646. showToast('Error', err.message, 'error');
  2647. }
  2648. }
  2649. async function startIPSecTunnel(name) {
  2650. try {
  2651. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2652. if (res.ok) {
  2653. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2654. setTimeout(() => loadIPSec(false), 2000);
  2655. }
  2656. } catch (err) {
  2657. showToast('Error', err.message, 'error');
  2658. }
  2659. }
  2660. async function stopIPSecTunnel(name) {
  2661. try {
  2662. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2663. if (res.ok) {
  2664. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2665. loadIPSec(false);
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function toggleIPSecState(name, enable) {
  2672. try {
  2673. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2674. method: 'POST',
  2675. headers: { 'Content-Type': 'application/json' },
  2676. body: JSON.stringify({ enabled: enable })
  2677. });
  2678. if (res.ok) {
  2679. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2680. loadIPSec(false);
  2681. }
  2682. } catch (err) {
  2683. showToast('Error', err.message, 'error');
  2684. }
  2685. }
  2686. async function deleteIPSecConn(name) {
  2687. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2688. try {
  2689. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2690. if (res.ok) {
  2691. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2692. loadIPSec(false);
  2693. fetchData(false);
  2694. }
  2695. } catch (err) {
  2696. showToast('Error', err.message, 'error');
  2697. }
  2698. }
  2699. // ======================== L2TP Multi-Instance ========================
  2700. async function loadL2TP(populateInputs = true) {
  2701. try {
  2702. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2703. await fetchPPPProfilesList();
  2704. }
  2705. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2706. const list = await res.json();
  2707. state.l2tpList = Array.isArray(list) ? list : [];
  2708. const badge = document.getElementById('l2tp-count-badge');
  2709. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2710. const tbody = document.getElementById('l2tp-table-body');
  2711. const empty = document.getElementById('l2tp-empty');
  2712. if (!tbody) return;
  2713. tbody.innerHTML = '';
  2714. if (state.l2tpList.length === 0) {
  2715. if (empty) empty.classList.remove('hidden');
  2716. } else {
  2717. if (empty) empty.classList.add('hidden');
  2718. state.l2tpList.forEach(inst => {
  2719. const tr = document.createElement('tr');
  2720. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2721. tr.innerHTML = `
  2722. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2723. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2724. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2725. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2726. <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>
  2727. <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>
  2728. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2729. <td class="py-2.5 px-3 text-center">
  2730. <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'}">
  2731. ${inst.default_route ? 'Yes' : 'No'}
  2732. </span>
  2733. </td>
  2734. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2735. ${inst.running ? `
  2736. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2737. ` : `
  2738. <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>
  2739. `}
  2740. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2741. ${inst.disabled ? 'Enable' : 'Disable'}
  2742. </button>
  2743. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2744. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2745. </td>
  2746. `;
  2747. tbody.appendChild(tr);
  2748. });
  2749. }
  2750. } catch (err) {
  2751. console.error('Failed to load L2TP:', err);
  2752. }
  2753. }
  2754. async function openAddL2TPModal() {
  2755. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2756. await fetchPPPProfilesList();
  2757. }
  2758. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2759. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2760. document.getElementById('l2tp-modal-name').readOnly = false;
  2761. document.getElementById('l2tp-modal-server').value = '';
  2762. document.getElementById('l2tp-modal-user').value = '';
  2763. document.getElementById('l2tp-modal-pass').value = '';
  2764. document.getElementById('l2tp-modal-ipsec').value = '';
  2765. document.getElementById('l2tp-modal-defroute').checked = true;
  2766. document.getElementById('l2tp-modal-disabled').checked = false;
  2767. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2768. document.getElementById('l2tp-modal').classList.remove('hidden');
  2769. }
  2770. async function openEditL2TPModal(name) {
  2771. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2772. await fetchPPPProfilesList();
  2773. }
  2774. const inst = (state.l2tpList || []).find(i => i.name === name);
  2775. if (!inst) return;
  2776. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2777. document.getElementById('l2tp-modal-name').value = inst.name;
  2778. document.getElementById('l2tp-modal-name').readOnly = true;
  2779. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2780. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2781. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2782. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2783. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2784. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2785. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2786. document.getElementById('l2tp-modal').classList.remove('hidden');
  2787. }
  2788. function closeL2TPModal() {
  2789. document.getElementById('l2tp-modal').classList.add('hidden');
  2790. }
  2791. async function submitSaveL2TP(e) {
  2792. e.preventDefault();
  2793. const name = document.getElementById('l2tp-modal-name').value.trim();
  2794. const server = document.getElementById('l2tp-modal-server').value.trim();
  2795. const user = document.getElementById('l2tp-modal-user').value.trim();
  2796. const pass = document.getElementById('l2tp-modal-pass').value;
  2797. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2798. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2799. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2800. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2801. try {
  2802. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2803. method: 'POST',
  2804. headers: { 'Content-Type': 'application/json' },
  2805. body: JSON.stringify({
  2806. name,
  2807. connect_to: server,
  2808. username: user,
  2809. password: pass,
  2810. profile: profile,
  2811. ipsec_secret: ipsec,
  2812. default_route: defRoute,
  2813. disabled
  2814. })
  2815. });
  2816. if (res.ok) {
  2817. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2818. closeL2TPModal();
  2819. loadL2TP(false);
  2820. fetchData(false);
  2821. }
  2822. } catch (err) {
  2823. showToast('Error', err.message, 'error');
  2824. }
  2825. }
  2826. async function connectL2TPInstance(name) {
  2827. try {
  2828. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2829. if (res.ok) {
  2830. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2831. setTimeout(() => loadL2TP(false), 2000);
  2832. }
  2833. } catch (err) {
  2834. showToast('Error', err.message, 'error');
  2835. }
  2836. }
  2837. async function disconnectL2TPInstance(name) {
  2838. try {
  2839. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2840. if (res.ok) {
  2841. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2842. loadL2TP(false);
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function toggleL2TPState(name, enable) {
  2849. try {
  2850. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2851. method: 'POST',
  2852. headers: { 'Content-Type': 'application/json' },
  2853. body: JSON.stringify({ enabled: enable })
  2854. });
  2855. if (res.ok) {
  2856. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2857. loadL2TP(false);
  2858. }
  2859. } catch (err) {
  2860. showToast('Error', err.message, 'error');
  2861. }
  2862. }
  2863. async function deleteL2TPInstance(name) {
  2864. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2865. try {
  2866. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2867. if (res.ok) {
  2868. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2869. loadL2TP(false);
  2870. fetchData(false);
  2871. }
  2872. } catch (err) {
  2873. showToast('Error', err.message, 'error');
  2874. }
  2875. }
  2876. // ======================== PPTP Multi-Instance ========================
  2877. async function loadPPTP(populateInputs = true) {
  2878. try {
  2879. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2880. await fetchPPPProfilesList();
  2881. }
  2882. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2883. const list = await res.json();
  2884. state.pptpList = Array.isArray(list) ? list : [];
  2885. const badge = document.getElementById('pptp-count-badge');
  2886. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2887. const tbody = document.getElementById('pptp-table-body');
  2888. const empty = document.getElementById('pptp-empty');
  2889. if (!tbody) return;
  2890. tbody.innerHTML = '';
  2891. if (state.pptpList.length === 0) {
  2892. if (empty) empty.classList.remove('hidden');
  2893. } else {
  2894. if (empty) empty.classList.add('hidden');
  2895. state.pptpList.forEach(inst => {
  2896. const tr = document.createElement('tr');
  2897. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2898. tr.innerHTML = `
  2899. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2900. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2901. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2902. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2903. <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>
  2904. <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>
  2905. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2906. <td class="py-2.5 px-3 text-center">
  2907. <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'}">
  2908. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2909. </span>
  2910. </td>
  2911. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2912. ${inst.running ? `
  2913. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2914. ` : `
  2915. <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>
  2916. `}
  2917. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2918. ${inst.disabled ? 'Enable' : 'Disable'}
  2919. </button>
  2920. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2921. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2922. </td>
  2923. `;
  2924. tbody.appendChild(tr);
  2925. });
  2926. }
  2927. } catch (err) {
  2928. console.error('Failed to load PPTP:', err);
  2929. }
  2930. }
  2931. async function openAddPPTPModal() {
  2932. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2933. await fetchPPPProfilesList();
  2934. }
  2935. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2936. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2937. document.getElementById('pptp-modal-name').readOnly = false;
  2938. document.getElementById('pptp-modal-server').value = '';
  2939. document.getElementById('pptp-modal-user').value = '';
  2940. document.getElementById('pptp-modal-pass').value = '';
  2941. document.getElementById('pptp-modal-mppe').checked = true;
  2942. document.getElementById('pptp-modal-defroute').checked = true;
  2943. document.getElementById('pptp-modal-disabled').checked = false;
  2944. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2945. document.getElementById('pptp-modal').classList.remove('hidden');
  2946. }
  2947. async function openEditPPTPModal(name) {
  2948. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2949. await fetchPPPProfilesList();
  2950. }
  2951. const inst = (state.pptpList || []).find(i => i.name === name);
  2952. if (!inst) return;
  2953. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2954. document.getElementById('pptp-modal-name').value = inst.name;
  2955. document.getElementById('pptp-modal-name').readOnly = true;
  2956. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2957. document.getElementById('pptp-modal-user').value = inst.username || '';
  2958. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2959. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2960. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2961. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2962. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2963. document.getElementById('pptp-modal').classList.remove('hidden');
  2964. }
  2965. function closePPTPModal() {
  2966. document.getElementById('pptp-modal').classList.add('hidden');
  2967. }
  2968. async function submitSavePPTP(e) {
  2969. e.preventDefault();
  2970. const name = document.getElementById('pptp-modal-name').value.trim();
  2971. const server = document.getElementById('pptp-modal-server').value.trim();
  2972. const user = document.getElementById('pptp-modal-user').value.trim();
  2973. const pass = document.getElementById('pptp-modal-pass').value;
  2974. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2975. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2976. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2977. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2978. try {
  2979. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2980. method: 'POST',
  2981. headers: { 'Content-Type': 'application/json' },
  2982. body: JSON.stringify({
  2983. name,
  2984. connect_to: server,
  2985. username: user,
  2986. password: pass,
  2987. profile: profile,
  2988. require_mppe: mppe,
  2989. default_route: defRoute,
  2990. auto_reconnect: true,
  2991. disabled
  2992. })
  2993. });
  2994. if (res.ok) {
  2995. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2996. closePPTPModal();
  2997. loadPPTP(false);
  2998. fetchData(false);
  2999. }
  3000. } catch (err) {
  3001. showToast('Error', err.message, 'error');
  3002. }
  3003. }
  3004. async function connectPPTPInstance(name) {
  3005. try {
  3006. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3007. if (res.ok) {
  3008. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3009. setTimeout(() => loadPPTP(false), 2000);
  3010. }
  3011. } catch (err) {
  3012. showToast('Error', err.message, 'error');
  3013. }
  3014. }
  3015. async function disconnectPPTPInstance(name) {
  3016. try {
  3017. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3018. if (res.ok) {
  3019. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3020. loadPPTP(false);
  3021. }
  3022. } catch (err) {
  3023. showToast('Error', err.message, 'error');
  3024. }
  3025. }
  3026. async function togglePPTPState(name, enable) {
  3027. try {
  3028. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3029. method: 'POST',
  3030. headers: { 'Content-Type': 'application/json' },
  3031. body: JSON.stringify({ enabled: enable })
  3032. });
  3033. if (res.ok) {
  3034. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3035. loadPPTP(false);
  3036. }
  3037. } catch (err) {
  3038. showToast('Error', err.message, 'error');
  3039. }
  3040. }
  3041. async function deletePPTPInstance(name) {
  3042. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3043. try {
  3044. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3045. if (res.ok) {
  3046. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3047. loadPPTP(false);
  3048. fetchData(false);
  3049. }
  3050. } catch (err) {
  3051. showToast('Error', err.message, 'error');
  3052. }
  3053. }
  3054. // ---------------- Modal & Helper Functions ----------------
  3055. function openVlanModal(defaultParent = '') {
  3056. const select = document.getElementById('vlan-parent');
  3057. select.innerHTML = '';
  3058. const allIfaces = state.interfaces || [];
  3059. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3060. if (eligible.length === 0) {
  3061. const opt = document.createElement('option');
  3062. opt.value = '';
  3063. opt.innerText = 'No VLAN-capable interfaces available';
  3064. select.appendChild(opt);
  3065. } else {
  3066. eligible.forEach(i => {
  3067. const opt = document.createElement('option');
  3068. opt.value = i.name;
  3069. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3070. if (i.name === defaultParent) opt.selected = true;
  3071. select.appendChild(opt);
  3072. });
  3073. }
  3074. document.getElementById('vlan-id').value = '';
  3075. document.getElementById('vlan-name').value = '';
  3076. document.getElementById('vlan-ip').value = '';
  3077. document.getElementById('vlan-desc').value = '';
  3078. populateRoleSelects('LAN');
  3079. autoSuggestVlanName();
  3080. document.getElementById('vlan-modal').classList.remove('hidden');
  3081. }
  3082. function closeVlanModal() {
  3083. document.getElementById('vlan-modal').classList.add('hidden');
  3084. }
  3085. function autoSuggestVlanName() {
  3086. const parent = document.getElementById('vlan-parent').value;
  3087. if (!parent) return;
  3088. const id = document.getElementById('vlan-id').value;
  3089. const nameInput = document.getElementById('vlan-name');
  3090. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3091. }
  3092. function setSubnetPreset(cidr) {
  3093. const ipInput = document.getElementById('vlan-ip');
  3094. const id = document.getElementById('vlan-id').value || '10';
  3095. ipInput.value = `192.168.${id}.1${cidr}`;
  3096. }
  3097. async function submitCreateVlan(e) {
  3098. e.preventDefault();
  3099. const btn = document.getElementById('vlan-submit-btn');
  3100. btn.disabled = true;
  3101. btn.innerText = 'Creating...';
  3102. const parent = document.getElementById('vlan-parent').value;
  3103. if (!parent) {
  3104. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3105. btn.disabled = false;
  3106. btn.innerText = 'Create VLAN';
  3107. return;
  3108. }
  3109. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3110. const name = document.getElementById('vlan-name').value.trim();
  3111. const ip = document.getElementById('vlan-ip').value.trim();
  3112. const role = document.getElementById('vlan-role').value;
  3113. const desc = document.getElementById('vlan-desc').value.trim();
  3114. try {
  3115. const res = await fetch(`${API_BASE}/vlans`, {
  3116. method: 'POST',
  3117. headers: { 'Content-Type': 'application/json' },
  3118. body: JSON.stringify({
  3119. parent_name: parent,
  3120. vlan_id: id,
  3121. name: name,
  3122. ip_address: ip,
  3123. role: role,
  3124. description: desc,
  3125. mtu: 1500,
  3126. auto_up: true
  3127. })
  3128. });
  3129. const data = await res.json();
  3130. if (res.ok) {
  3131. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3132. state.expandedParents.add(parent);
  3133. closeVlanModal();
  3134. await fetchData(true);
  3135. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3136. } else {
  3137. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3138. }
  3139. } catch (err) {
  3140. showToast('Error', err.message, 'error');
  3141. } finally {
  3142. btn.disabled = false;
  3143. btn.innerText = 'Create VLAN';
  3144. }
  3145. }
  3146. async function confirmDeleteVlan(name) {
  3147. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3148. try {
  3149. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3150. if (res.ok) {
  3151. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3152. closeIfaceModal();
  3153. fetchData(true);
  3154. }
  3155. } catch (err) {
  3156. showToast('Error', err.message, 'error');
  3157. }
  3158. }
  3159. function openIfaceModal(name) {
  3160. const iface = (state.interfaces || []).find(i => i.name === name);
  3161. if (!iface) return;
  3162. state.currentModalIface = iface.name;
  3163. document.getElementById('modal-iface-name').innerText = iface.name;
  3164. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3165. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3166. populateRoleSelects(iface.role || 'LAN');
  3167. document.getElementById('modal-iface-desc').value = iface.description || '';
  3168. const nameInput = document.getElementById('modal-iface-new-name');
  3169. const renameBtn = document.getElementById('modal-btn-rename');
  3170. const renameHelp = document.getElementById('modal-iface-rename-help');
  3171. if (nameInput) {
  3172. nameInput.value = iface.name;
  3173. if (iface.name === 'lo' || iface.type === 'loopback') {
  3174. nameInput.disabled = true;
  3175. if (renameBtn) renameBtn.disabled = true;
  3176. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3177. } else {
  3178. nameInput.disabled = false;
  3179. if (renameBtn) renameBtn.disabled = false;
  3180. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3181. }
  3182. }
  3183. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3184. if (iface.is_vlan) {
  3185. delBtn.classList.remove('hidden');
  3186. } else {
  3187. delBtn.classList.add('hidden');
  3188. }
  3189. renderModalIPs(iface);
  3190. document.getElementById('iface-modal').classList.remove('hidden');
  3191. }
  3192. function renderModalIPs(iface) {
  3193. const container = document.getElementById('modal-ip-list');
  3194. container.innerHTML = '';
  3195. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3196. if (addrs.length === 0) {
  3197. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3198. return;
  3199. }
  3200. addrs.forEach(addr => {
  3201. const row = document.createElement('div');
  3202. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3203. row.innerHTML = `
  3204. <span class="text-white">${addr}</span>
  3205. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3206. `;
  3207. container.appendChild(row);
  3208. });
  3209. }
  3210. function closeIfaceModal() {
  3211. document.getElementById('iface-modal').classList.add('hidden');
  3212. state.currentModalIface = null;
  3213. }
  3214. async function setIfaceState(name, newState) {
  3215. const target = name || state.currentModalIface;
  3216. if (!target) return;
  3217. await toggleInterfaceState(target, newState);
  3218. const updated = (state.interfaces || []).find(i => i.name === target);
  3219. if (updated) openIfaceModal(target);
  3220. }
  3221. async function applyMTU() {
  3222. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3223. try {
  3224. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3225. method: 'POST',
  3226. headers: { 'Content-Type': 'application/json' },
  3227. body: JSON.stringify({ mtu })
  3228. });
  3229. if (res.ok) {
  3230. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3231. fetchData(false);
  3232. }
  3233. } catch (err) {
  3234. showToast('Error', err.message, 'error');
  3235. }
  3236. }
  3237. async function addInterfaceIP() {
  3238. const ip = document.getElementById('modal-new-ip').value.trim();
  3239. if (!ip) return;
  3240. try {
  3241. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3242. method: 'POST',
  3243. headers: { 'Content-Type': 'application/json' },
  3244. body: JSON.stringify({ ip })
  3245. });
  3246. if (res.ok) {
  3247. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3248. document.getElementById('modal-new-ip').value = '';
  3249. await fetchData(false);
  3250. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3251. if (iface) renderModalIPs(iface);
  3252. } else {
  3253. const err = await res.json();
  3254. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3255. }
  3256. } catch (err) {
  3257. showToast('Error', err.message, 'error');
  3258. }
  3259. }
  3260. async function removeInterfaceIP(ip) {
  3261. if (!confirm(`Remove IP ${ip}?`)) return;
  3262. try {
  3263. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3264. method: 'DELETE',
  3265. headers: { 'Content-Type': 'application/json' },
  3266. body: JSON.stringify({ ip })
  3267. });
  3268. if (res.ok) {
  3269. showToast('IP Removed', `Removed ${ip}`, 'success');
  3270. await fetchData(false);
  3271. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3272. if (iface) renderModalIPs(iface);
  3273. }
  3274. } catch (err) {
  3275. showToast('Error', err.message, 'error');
  3276. }
  3277. }
  3278. async function renameInterface() {
  3279. const oldName = state.currentModalIface;
  3280. const newNameInput = document.getElementById('modal-iface-new-name');
  3281. const newName = (newNameInput?.value || '').trim();
  3282. if (!oldName) return;
  3283. if (!newName) {
  3284. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3285. return;
  3286. }
  3287. if (newName === oldName) {
  3288. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3289. return;
  3290. }
  3291. if (newName.length > 15) {
  3292. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3293. return;
  3294. }
  3295. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3296. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3297. return;
  3298. }
  3299. const renameBtn = document.getElementById('modal-btn-rename');
  3300. if (renameBtn) {
  3301. renameBtn.disabled = true;
  3302. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3303. }
  3304. try {
  3305. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3306. method: 'POST',
  3307. headers: { 'Content-Type': 'application/json' },
  3308. body: JSON.stringify({ new_name: newName })
  3309. });
  3310. const data = await res.json();
  3311. if (!res.ok) {
  3312. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3313. return;
  3314. }
  3315. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3316. state.currentModalIface = newName;
  3317. document.getElementById('modal-iface-name').innerText = newName;
  3318. // Refresh application state
  3319. await fetchData(false);
  3320. const updated = (state.interfaces || []).find(i => i.name === newName);
  3321. if (updated) {
  3322. openIfaceModal(newName);
  3323. } else {
  3324. closeIfaceModal();
  3325. }
  3326. } catch (err) {
  3327. showToast('Error', err.message, 'error');
  3328. } finally {
  3329. if (renameBtn) {
  3330. renameBtn.disabled = false;
  3331. renameBtn.innerHTML = `
  3332. <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>
  3333. <span>Rename</span>
  3334. `;
  3335. }
  3336. }
  3337. }
  3338. async function saveInterfaceMetadata() {
  3339. const oldName = state.currentModalIface;
  3340. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3341. const role = document.getElementById('modal-iface-role').value;
  3342. const desc = document.getElementById('modal-iface-desc').value.trim();
  3343. let targetName = oldName;
  3344. // If user changed the name before clicking Save Changes, execute rename first
  3345. if (newName && newName !== oldName && oldName !== 'lo') {
  3346. try {
  3347. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3348. method: 'POST',
  3349. headers: { 'Content-Type': 'application/json' },
  3350. body: JSON.stringify({ new_name: newName })
  3351. });
  3352. const data = await renameRes.json();
  3353. if (!renameRes.ok) {
  3354. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3355. return;
  3356. }
  3357. targetName = newName;
  3358. state.currentModalIface = newName;
  3359. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3360. } catch (err) {
  3361. showToast('Error', err.message, 'error');
  3362. return;
  3363. }
  3364. }
  3365. try {
  3366. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3367. method: 'POST',
  3368. headers: { 'Content-Type': 'application/json' },
  3369. body: JSON.stringify({ role, description: desc })
  3370. });
  3371. if (res.ok) {
  3372. showToast('Saved', 'Interface configuration updated', 'success');
  3373. closeIfaceModal();
  3374. fetchData(false);
  3375. } else {
  3376. const err = await res.json();
  3377. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3378. }
  3379. } catch (err) {
  3380. showToast('Error', err.message, 'error');
  3381. }
  3382. }
  3383. // ======================== IPTABLES FIREWALL ========================
  3384. state.fwSubTab = 'filter';
  3385. state.routesSubTab = 'routes';
  3386. function nativeNATChain(chain) {
  3387. const value = (chain || '').toLowerCase();
  3388. if (value === 'dstnat') return 'prerouting';
  3389. if (value === 'srcnat') return 'postrouting';
  3390. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3391. }
  3392. function nativeFirewallTarget(action) {
  3393. const name = (action || '').toLowerCase();
  3394. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3395. }
  3396. function renderRuleFlag(disabled, hasComment) {
  3397. let flags = '';
  3398. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3399. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3400. return flags || '<span class="text-slate-600">-</span>';
  3401. }
  3402. function renderActionBadge(action) {
  3403. const act = (action || '').toLowerCase();
  3404. let color = 'bg-slate-800 text-slate-300';
  3405. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3406. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3407. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3408. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3409. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3410. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3411. }
  3412. function switchFWSubTab(tab) {
  3413. state.fwSubTab = tab;
  3414. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3415. tabs.forEach(t => {
  3416. const panel = document.getElementById(`fw-subtab-${t}`);
  3417. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3418. if (panel) {
  3419. if (t === tab) panel.classList.remove('hidden');
  3420. else panel.classList.add('hidden');
  3421. }
  3422. if (btn) {
  3423. if (t === tab) {
  3424. 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';
  3425. } else {
  3426. 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';
  3427. }
  3428. }
  3429. });
  3430. const addBtn = document.getElementById('fw-primary-add-btn');
  3431. if (addBtn) {
  3432. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3433. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3434. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3435. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3436. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3437. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3438. }
  3439. if (tab === 'filter') renderFilterRules();
  3440. else if (tab === 'nat') renderNATRules();
  3441. else if (tab === 'mangle') renderMangleRules();
  3442. else if (tab === 'addrlist') renderAddressLists();
  3443. else if (tab === 'geo') loadGeoIP();
  3444. else if (tab === 'connections') loadConnections();
  3445. setTimeout(initTableSorting, 50);
  3446. }
  3447. function openCurrentFWModal() {
  3448. if (state.fwSubTab === 'filter') openAddFilterModal();
  3449. else if (state.fwSubTab === 'nat') openAddNATModal();
  3450. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3451. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3452. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3453. else if (state.fwSubTab === 'connections') loadConnections();
  3454. }
  3455. async function loadFirewall(populateDropdowns = true) {
  3456. try {
  3457. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3458. fetch(`${API_BASE}/firewall/summary`),
  3459. fetch(`${API_BASE}/firewall/filter`),
  3460. fetch(`${API_BASE}/firewall/nat`),
  3461. fetch(`${API_BASE}/firewall/mangle`),
  3462. fetch(`${API_BASE}/firewall/address-lists`),
  3463. fetch(`${API_BASE}/firewall/geoip/status`),
  3464. fetch(`${API_BASE}/firewall/geoip/countries`)
  3465. ]);
  3466. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3467. const applyError = document.getElementById('fw-apply-error');
  3468. if (applyError) {
  3469. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3470. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3471. }
  3472. if (filterRes.ok) state.filterRules = await filterRes.json();
  3473. if (natRes.ok) state.natRules = await natRes.json();
  3474. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3475. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3476. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3477. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3478. 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); }
  3479. // Badges
  3480. const bFilter = document.getElementById('fw-badge-filter');
  3481. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3482. const bNat = document.getElementById('fw-badge-nat');
  3483. if (bNat) bNat.innerText = (state.natRules || []).length;
  3484. const bMangle = document.getElementById('fw-badge-mangle');
  3485. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3486. const bAddr = document.getElementById('fw-badge-addrlist');
  3487. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3488. const bGeo = document.getElementById('fw-badge-geo');
  3489. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3490. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3491. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3492. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3493. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3494. const tbodyFilter = document.getElementById('filter-table-body');
  3495. if (tbodyFilter) {
  3496. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3497. tbodyFilter.dataset.sig = sigFilter;
  3498. renderFilterRules();
  3499. } else {
  3500. // In-place live stats update (ZERO flicker)
  3501. (state.filterRules || []).forEach(r => {
  3502. const p = document.getElementById(`filter-pkts-${r.id}`);
  3503. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3504. const b = document.getElementById(`filter-bytes-${r.id}`);
  3505. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3506. });
  3507. }
  3508. }
  3509. const tbodyNat = document.getElementById('nat-table-body');
  3510. if (tbodyNat) {
  3511. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3512. tbodyNat.dataset.sig = sigNat;
  3513. renderNATRules();
  3514. } else {
  3515. (state.natRules || []).forEach(r => {
  3516. const p = document.getElementById(`nat-pkts-${r.id}`);
  3517. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3518. const b = document.getElementById(`nat-bytes-${r.id}`);
  3519. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3520. });
  3521. }
  3522. }
  3523. const tbodyMangle = document.getElementById('mangle-table-body');
  3524. if (tbodyMangle) {
  3525. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3526. tbodyMangle.dataset.sig = sigMangle;
  3527. renderMangleRules();
  3528. } else {
  3529. (state.mangleRules || []).forEach(r => {
  3530. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3531. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3532. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3533. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3534. });
  3535. }
  3536. }
  3537. const tbodyAddr = document.getElementById('addrlist-table-body');
  3538. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3539. tbodyAddr.dataset.sig = sigAddr;
  3540. renderAddressLists();
  3541. }
  3542. renderGeoCountries();
  3543. if (state.fwSubTab === 'connections') {
  3544. loadConnections();
  3545. }
  3546. } catch (err) {
  3547. console.error('Failed to load firewall:', err);
  3548. }
  3549. }
  3550. // ----------------- Filter Rules -----------------
  3551. function renderFilterRules() {
  3552. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3553. const tbody = document.getElementById('filter-table-body');
  3554. const empty = document.getElementById('filter-empty');
  3555. if (!tbody) return;
  3556. tbody.innerHTML = '';
  3557. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3558. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3559. if (rules.length === 0) {
  3560. empty?.classList.remove('hidden');
  3561. return;
  3562. }
  3563. empty?.classList.add('hidden');
  3564. rules.forEach((raw, idx) => {
  3565. const r = safeFirewallRow(raw);
  3566. const tr = document.createElement('tr');
  3567. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3568. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3569. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3570. let actionExtra = '';
  3571. if (r.action === 'reject') {
  3572. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3573. } else if (r.action === 'jump') {
  3574. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3575. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3576. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3577. } else if (r.action === 'log' && r.log_prefix) {
  3578. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3579. }
  3580. tr.innerHTML = `
  3581. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3582. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3583. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3584. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3585. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3586. <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>
  3587. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3588. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3589. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3590. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3591. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3592. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3593. </td>
  3594. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3595. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3596. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3597. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3598. <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>
  3599. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3600. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3601. </td>
  3602. `;
  3603. tbody.appendChild(tr);
  3604. });
  3605. }
  3606. function formatTarget(addr, list, geo) {
  3607. const parts = [];
  3608. if (addr) parts.push(`<span>${addr}</span>`);
  3609. if (list) {
  3610. const inv = list.startsWith('!') ? '!' : '';
  3611. const clean = list.replace(/^!/, '');
  3612. 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>`);
  3613. }
  3614. if (geo) {
  3615. const inv = geo.startsWith('!') ? '!' : '';
  3616. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3617. 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>`);
  3618. }
  3619. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3620. return parts.join(' ');
  3621. }
  3622. function populateInterfaceSelect(selectId, currentVal = '') {
  3623. const sel = document.getElementById(selectId);
  3624. if (!sel) return;
  3625. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3626. (state.interfaces || []).forEach(i => {
  3627. const opt = document.createElement('option');
  3628. opt.value = i.name;
  3629. opt.innerText = `${i.name} (${i.role || i.type})`;
  3630. if (i.name === currentVal) opt.selected = true;
  3631. sel.appendChild(opt);
  3632. });
  3633. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3634. const optgroup = document.createElement('optgroup');
  3635. optgroup.label = 'SD-WAN Groups';
  3636. state.sdwanGroups.forEach(g => {
  3637. const opt = document.createElement('option');
  3638. opt.value = g.name;
  3639. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3640. if (g.name === currentVal) opt.selected = true;
  3641. optgroup.appendChild(opt);
  3642. });
  3643. sel.appendChild(optgroup);
  3644. }
  3645. }
  3646. function populateAddressListSelect(selectId, currentVal = '') {
  3647. const sel = document.getElementById(selectId);
  3648. if (!sel) return;
  3649. sel.innerHTML = '<option value="">(None)</option>';
  3650. const cleanVal = (currentVal || '').replace(/^!/, '');
  3651. 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_'));
  3652. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3653. customNames.forEach(name => {
  3654. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3655. const opt = document.createElement('option');
  3656. opt.value = name;
  3657. opt.innerText = `${name} (${count} entries)`;
  3658. if (name === cleanVal) opt.selected = true;
  3659. sel.appendChild(opt);
  3660. });
  3661. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3662. const opt = document.createElement('option');
  3663. opt.value = cleanVal;
  3664. opt.innerText = cleanVal;
  3665. opt.selected = true;
  3666. sel.appendChild(opt);
  3667. }
  3668. populateCommonAddrListDatalist();
  3669. }
  3670. function populateCommonAddrListDatalist() {
  3671. const dl = document.getElementById('fw-addrlist-datalist');
  3672. if (!dl) return;
  3673. dl.innerHTML = '';
  3674. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3675. names.forEach(name => {
  3676. const opt = document.createElement('option');
  3677. opt.value = name;
  3678. dl.appendChild(opt);
  3679. });
  3680. }
  3681. function populateGeoIPSelect(selectId, currentVal = '') {
  3682. const sel = document.getElementById(selectId);
  3683. if (!sel) return;
  3684. sel.innerHTML = '<option value="">(None)</option>';
  3685. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3686. // Presets optgroup
  3687. const grpPresets = document.createElement('optgroup');
  3688. grpPresets.label = '⚡ Regional Presets';
  3689. const presets = [
  3690. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3691. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3692. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3693. ];
  3694. presets.forEach(p => {
  3695. const opt = document.createElement('option');
  3696. opt.value = p.code;
  3697. opt.innerText = p.label;
  3698. if (p.code === cleanVal) opt.selected = true;
  3699. grpPresets.appendChild(opt);
  3700. });
  3701. sel.appendChild(grpPresets);
  3702. // All Countries optgroup
  3703. const grpCountries = document.createElement('optgroup');
  3704. grpCountries.label = '🌍 All Countries';
  3705. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3706. countries.forEach(c => {
  3707. const opt = document.createElement('option');
  3708. opt.value = c.code;
  3709. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3710. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3711. if (c.code === cleanVal) opt.selected = true;
  3712. grpCountries.appendChild(opt);
  3713. });
  3714. sel.appendChild(grpCountries);
  3715. }
  3716. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3717. function switchFwRuleTab(tab) {
  3718. state.activeFwRuleTab = tab;
  3719. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3720. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3721. btn.classList.add('text-slate-400', 'border-transparent');
  3722. });
  3723. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3724. if (activeBtn) {
  3725. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3726. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3727. }
  3728. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3729. const activePane = document.getElementById(`fw-pane-${tab}`);
  3730. if (activePane) activePane.classList.remove('hidden');
  3731. if (tab === 'statistics') {
  3732. startFwStatPolling();
  3733. } else {
  3734. stopFwStatPolling();
  3735. }
  3736. }
  3737. function toggleFwField(fieldKey, expand) {
  3738. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3739. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3740. if (!plusBtn || !fieldBox) return;
  3741. if (expand) {
  3742. plusBtn.classList.add('hidden');
  3743. fieldBox.classList.remove('hidden');
  3744. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3745. if (valInput) valInput.focus();
  3746. } else {
  3747. fieldBox.classList.add('hidden');
  3748. plusBtn.classList.remove('hidden');
  3749. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3750. if (valInput) {
  3751. if (valInput.tagName === 'SELECT') {
  3752. valInput.selectedIndex = 0;
  3753. } else {
  3754. valInput.value = '';
  3755. }
  3756. }
  3757. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3758. if (invInput) invInput.checked = false;
  3759. if (fieldKey === 'cs') {
  3760. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3761. const el = document.getElementById(id);
  3762. if (el) el.checked = false;
  3763. });
  3764. }
  3765. if (fieldKey === 'natstate') {
  3766. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3767. const el = document.getElementById(id);
  3768. if (el) el.checked = false;
  3769. });
  3770. }
  3771. if (fieldKey === 'days') {
  3772. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3773. const el = document.getElementById(`fw-day-${d}`);
  3774. if (el) el.checked = true;
  3775. });
  3776. }
  3777. }
  3778. }
  3779. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3780. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3781. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3782. toggleFwField(fieldKey, true);
  3783. let strVal = String(value);
  3784. if (hasInvert) {
  3785. const inv = strVal.startsWith('!');
  3786. if (inv) strVal = strVal.slice(1);
  3787. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3788. if (invEl) invEl.checked = inv;
  3789. else if (inv) strVal = '!'+strVal;
  3790. }
  3791. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3792. 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; }
  3793. } else {
  3794. toggleFwField(fieldKey, false);
  3795. }
  3796. }
  3797. function getFwFieldVal(fieldKey, hasInvert = false) {
  3798. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3799. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3800. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3801. let v = valEl ? valEl.value.trim() : '';
  3802. if (!v) return '';
  3803. if (hasInvert) {
  3804. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3805. if (invEl && invEl.checked) {
  3806. v = '!' + v.replace(/^!/, '');
  3807. }
  3808. }
  3809. return v;
  3810. }
  3811. function toggleMaximizeFilterModal() {
  3812. const win = document.getElementById('filter-modal-window');
  3813. if (!win) return;
  3814. if (win.classList.contains('max-w-[720px]')) {
  3815. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3816. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3817. } else {
  3818. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3819. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3820. }
  3821. }
  3822. const FW_NATIVE_CHAINS = {
  3823. filter: [
  3824. { id: 'forward', label: 'FORWARD (routed through router)' },
  3825. { id: 'input', label: 'INPUT (destined to this router)' },
  3826. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3827. ],
  3828. nat: [
  3829. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3830. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3831. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3832. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3833. ],
  3834. mangle: [
  3835. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3836. { id: 'input', label: 'INPUT (destined to this machine)' },
  3837. { id: 'forward', label: 'FORWARD (routed through router)' },
  3838. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3839. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3840. ]
  3841. };
  3842. function populateChainDropdown(table, currentChain) {
  3843. const sel = document.getElementById(`${table}-modal-chain-select`);
  3844. if (!sel) return;
  3845. const cur = (currentChain || '').trim();
  3846. const lower = cur.toLowerCase();
  3847. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3848. const rules = state[rulesKey] || [];
  3849. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3850. const customChains = new Set();
  3851. rules.forEach(r => {
  3852. if (r.chain) {
  3853. const c = r.chain.trim();
  3854. const l = c.toLowerCase();
  3855. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3856. customChains.add(c);
  3857. }
  3858. }
  3859. });
  3860. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3861. if (isCurrentCustom) {
  3862. customChains.add(cur);
  3863. }
  3864. let html = '';
  3865. FW_NATIVE_CHAINS[table].forEach(c => {
  3866. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3867. });
  3868. if (customChains.size > 0) {
  3869. html += `<optgroup label="Custom Chains">`;
  3870. customChains.forEach(c => {
  3871. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3872. });
  3873. html += `</optgroup>`;
  3874. }
  3875. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3876. sel.innerHTML = html;
  3877. if (isCurrentCustom) {
  3878. sel.value = cur;
  3879. } else if (nativeIds.includes(lower)) {
  3880. sel.value = lower;
  3881. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3882. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3883. } else {
  3884. sel.value = nativeIds[0];
  3885. }
  3886. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3887. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3888. if (isCurrentCustom || sel.value === '__custom__') {
  3889. if (customWrap) customWrap.classList.remove('hidden');
  3890. if (customInput) customInput.value = cur;
  3891. } else {
  3892. if (customWrap) customWrap.classList.add('hidden');
  3893. if (customInput) customInput.value = '';
  3894. }
  3895. const chainInput = document.getElementById(`${table}-modal-chain`);
  3896. if (chainInput) chainInput.value = cur || sel.value;
  3897. }
  3898. function syncFilterChainFromSelect() {
  3899. const sel = document.getElementById('filter-modal-chain-select');
  3900. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3901. const customInput = document.getElementById('filter-modal-custom-input');
  3902. const chainInput = document.getElementById('filter-modal-chain');
  3903. if (!sel || !chainInput) return;
  3904. if (sel.value === '__custom__') {
  3905. if (customWrap) customWrap.classList.remove('hidden');
  3906. if (customInput) {
  3907. customInput.value = '';
  3908. customInput.focus();
  3909. }
  3910. chainInput.value = '';
  3911. } else {
  3912. if (customWrap) customWrap.classList.add('hidden');
  3913. chainInput.value = sel.value;
  3914. }
  3915. handleFilterChainChange();
  3916. }
  3917. function syncFilterCustomChainInput() {
  3918. const customInput = document.getElementById('filter-modal-custom-input');
  3919. const chainInput = document.getElementById('filter-modal-chain');
  3920. if (customInput && chainInput) {
  3921. chainInput.value = customInput.value.trim();
  3922. }
  3923. handleFilterChainChange();
  3924. }
  3925. function handleFilterChainChange() {
  3926. const chainInput = document.getElementById('filter-modal-chain');
  3927. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3928. const sel = document.getElementById('filter-modal-chain-select');
  3929. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3930. if (['forward', 'input', 'output'].includes(chain)) {
  3931. sel.value = chain;
  3932. }
  3933. }
  3934. const hintEl = document.getElementById('filter-chain-hint');
  3935. if (hintEl) {
  3936. if (chain === 'forward') {
  3937. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3938. } else if (chain === 'input') {
  3939. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3940. } else if (chain === 'output') {
  3941. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3942. } else {
  3943. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3944. }
  3945. }
  3946. const rowIn = document.getElementById('fw-row-iniface');
  3947. const rowInList = document.getElementById('fw-row-inifacelist');
  3948. const rowOut = document.getElementById('fw-row-outiface');
  3949. const rowOutList = document.getElementById('fw-row-outifacelist');
  3950. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3951. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3952. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3953. if (chain === 'input') {
  3954. if (rowIn) rowIn.classList.remove('hidden');
  3955. if (rowInList) rowInList.classList.remove('hidden');
  3956. if (rowOut) rowOut.classList.add('hidden');
  3957. if (rowOutList) rowOutList.classList.add('hidden');
  3958. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3959. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  3960. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3961. } else if (chain === 'output') {
  3962. if (rowIn) rowIn.classList.add('hidden');
  3963. if (rowInList) rowInList.classList.add('hidden');
  3964. if (rowOut) rowOut.classList.remove('hidden');
  3965. if (rowOutList) rowOutList.classList.remove('hidden');
  3966. if (rowInBridge) rowInBridge.classList.add('hidden');
  3967. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  3968. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  3969. } else {
  3970. if (rowIn) rowIn.classList.remove('hidden');
  3971. if (rowInList) rowInList.classList.remove('hidden');
  3972. if (rowOut) rowOut.classList.remove('hidden');
  3973. if (rowOutList) rowOutList.classList.remove('hidden');
  3974. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3975. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  3976. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3977. }
  3978. checkFilterActionChainCompatibility();
  3979. }
  3980. function checkFilterActionChainCompatibility() {
  3981. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  3982. const warnBox = document.getElementById('filter-action-incompatible-warn');
  3983. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  3984. if (!warnBox || !warnMsg) return;
  3985. if (chain === 'prerouting' || chain === 'postrouting') {
  3986. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  3987. warnBox.classList.remove('hidden');
  3988. } else {
  3989. warnBox.classList.add('hidden');
  3990. }
  3991. }
  3992. function openAddFilterModal() {
  3993. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3994. switchFwRuleTab('general');
  3995. setFirewallDays('fw', '');
  3996. const badge = document.getElementById('fw-modal-badge');
  3997. if (badge) badge.innerText = 'New...';
  3998. document.getElementById('filter-modal-id').value = '';
  3999. document.getElementById('filter-modal-family').value = '4';
  4000. document.getElementById('filter-modal-enabled').checked = true;
  4001. document.getElementById('filter-modal-comment').value = '';
  4002. document.getElementById('filter-modal-chain').value = 'forward';
  4003. populateChainDropdown('filter', 'forward');
  4004. handleFilterChainChange();
  4005. document.getElementById('filter-modal-action').value = 'accept';
  4006. document.getElementById('filter-modal-log').checked = false;
  4007. populateInterfaceSelect('fw-val-iniface');
  4008. populateInterfaceSelect('fw-val-outiface');
  4009. populateAddressListSelect('fw-val-srclist');
  4010. populateAddressListSelect('fw-val-dstlist');
  4011. populateGeoIPSelect('fw-val-srcgeo');
  4012. populateGeoIPSelect('fw-val-dstgeo');
  4013. const allFieldKeys = [
  4014. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4015. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4016. 'routingmark', 'conntype', 'cs', 'natstate',
  4017. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4018. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4019. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4020. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4021. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4022. ];
  4023. allFieldKeys.forEach(k => toggleFwField(k, false));
  4024. resetRuleCounterDisplay();
  4025. toggleFilterActionFields();
  4026. refreshFirewallRejectTypes();
  4027. document.getElementById('filter-modal').classList.remove('hidden');
  4028. }
  4029. function openEditFilterModal(id) {
  4030. id = decodeURIComponent(id);
  4031. const r = (state.filterRules || []).find(rule => rule.id === id);
  4032. if (!r) return;
  4033. switchFwRuleTab('general');
  4034. const badge = document.getElementById('fw-modal-badge');
  4035. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4036. document.getElementById('filter-modal-id').value = r.id;
  4037. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4038. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4039. document.getElementById('filter-modal-comment').value = r.comment || '';
  4040. const filterChain = r.chain || 'forward';
  4041. document.getElementById('filter-modal-chain').value = filterChain;
  4042. populateChainDropdown('filter', filterChain);
  4043. handleFilterChainChange();
  4044. setFirewallActionSelection('filter', r.action || 'accept');
  4045. document.getElementById('filter-modal-log').checked = !!r.log;
  4046. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4047. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4048. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4049. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4050. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4051. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4052. setFwFieldVal('src', r.src_address, true);
  4053. setFwFieldVal('dst', r.dst_address, true);
  4054. setFwFieldVal('srclist', r.src_address_list, true);
  4055. setFwFieldVal('dstlist', r.dst_address_list, true);
  4056. setFwFieldVal('srcgeo', r.src_geoip, true);
  4057. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4058. if (r.protocol && r.protocol !== 'all') {
  4059. setFwFieldVal('proto', r.protocol, true);
  4060. } else {
  4061. toggleFwField('proto', false);
  4062. }
  4063. setFwFieldVal('sport', r.src_port, true);
  4064. setFwFieldVal('dport', r.dst_port, true);
  4065. setFwFieldVal('anyport', r.any_port, true);
  4066. setFwFieldVal('iniface', r.in_interface, true);
  4067. setFwFieldVal('outiface', r.out_interface, true);
  4068. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4069. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4070. setFwFieldVal('pktmark', r.packet_mark, true);
  4071. setFwFieldVal('connmark', r.connection_mark, true);
  4072. setFwFieldVal('routingmark', r.routing_mark, true);
  4073. setFwFieldVal('conntype', r.connection_type, false);
  4074. const states = r.connection_state || [];
  4075. if (states.length > 0) {
  4076. toggleFwField('cs', true);
  4077. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4078. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4079. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4080. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4081. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4082. } else {
  4083. toggleFwField('cs', false);
  4084. }
  4085. const natStates = r.connection_nat_state || [];
  4086. if (natStates.length > 0) {
  4087. toggleFwField('natstate', true);
  4088. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4089. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4090. } else {
  4091. toggleFwField('natstate', false);
  4092. }
  4093. // Advanced tab fields
  4094. setFwFieldVal('layer7', r.layer7_protocol, false);
  4095. setFwFieldVal('content', r.content, false);
  4096. setFwFieldVal('connbytes', r.connection_bytes, false);
  4097. setFwFieldVal('connrate', r.connection_rate, false);
  4098. setFwFieldVal('pcc', r.pcc, false);
  4099. setFwFieldVal('srcmac', r.src_mac_address, true);
  4100. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4101. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4102. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4103. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4104. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4105. setFwFieldVal('tlshost', r.tls_host, false);
  4106. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4107. setFwFieldVal('priority', r.priority, false);
  4108. setFwFieldVal('dscp', r.dscp, false);
  4109. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4110. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4111. setFwFieldVal('pktsize', r.packet_size, false);
  4112. setFwFieldVal('random', r.random, false);
  4113. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4114. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4115. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4116. setFwFieldVal('ttl', r.ttl, false);
  4117. // Extra tab fields
  4118. setFwFieldVal('time', r.time, false);
  4119. if (r.days) {
  4120. toggleFwField('days', true);
  4121. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4122. const chk = document.getElementById(`fw-day-${d}`);
  4123. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4124. });
  4125. } else {
  4126. toggleFwField('days', false);
  4127. }
  4128. setFwFieldVal('limit', r.limit, false);
  4129. setFwFieldVal('dstlimit', r.dst_limit, false);
  4130. setFwFieldVal('psd', r.psd, false);
  4131. // Action fields
  4132. if (r.reject_with) {
  4133. const rwEl = document.getElementById('filter-modal-rejectwith');
  4134. if (rwEl) rwEl.value = r.reject_with;
  4135. }
  4136. if (r.jump_target) {
  4137. const jtEl = document.getElementById('filter-modal-jumptarget');
  4138. if (jtEl) jtEl.value = r.jump_target;
  4139. }
  4140. if (r.address_list) {
  4141. const alEl = document.getElementById('filter-modal-action-addrlist');
  4142. if (alEl) alEl.value = r.address_list;
  4143. }
  4144. if (r.address_list_timeout) {
  4145. const toEl = document.getElementById('filter-modal-action-timeout');
  4146. if (toEl) toEl.value = r.address_list_timeout;
  4147. }
  4148. setFwFieldVal('logprefix', r.log_prefix, false);
  4149. // Statistics
  4150. const bEl = document.getElementById('fw-stat-bytes');
  4151. const pEl = document.getElementById('fw-stat-packets');
  4152. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4153. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4154. state.fwLastBytes = r.bytes || 0;
  4155. state.fwLastPackets = r.packets || 0;
  4156. state.fwLastTimestamp = Date.now();
  4157. state.fwStatRateHistory = new Array(30).fill(0);
  4158. state.fwStatPktHistory = new Array(30).fill(0);
  4159. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4160. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4161. toggleFilterActionFields();
  4162. refreshFirewallRejectTypes();
  4163. document.getElementById('filter-modal').classList.remove('hidden');
  4164. }
  4165. function closeFilterModal() {
  4166. stopFwStatPolling();
  4167. document.getElementById('filter-modal').classList.add('hidden');
  4168. }
  4169. function toggleFilterActionFields() {
  4170. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4171. const rejectBox = document.getElementById('filter-action-reject-box');
  4172. const jumpBox = document.getElementById('filter-action-jump-box');
  4173. const addrBox = document.getElementById('filter-action-addrlist-box');
  4174. if (rejectBox) {
  4175. if (act === 'reject') rejectBox.classList.remove('hidden');
  4176. else rejectBox.classList.add('hidden');
  4177. }
  4178. if (jumpBox) {
  4179. if (act === 'jump') jumpBox.classList.remove('hidden');
  4180. else jumpBox.classList.add('hidden');
  4181. }
  4182. if (addrBox) {
  4183. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4184. addrBox.classList.remove('hidden');
  4185. } else {
  4186. addrBox.classList.add('hidden');
  4187. }
  4188. }
  4189. if (act === 'log') {
  4190. const logEl = document.getElementById('filter-modal-log');
  4191. if (logEl) logEl.checked = true;
  4192. toggleFwField('logprefix', true);
  4193. }
  4194. }
  4195. function toggleFwLogPrefix() {
  4196. const isLog = document.getElementById('filter-modal-log')?.checked;
  4197. toggleFwField('logprefix', !!isLog);
  4198. }
  4199. function copyFilterRule() {
  4200. document.getElementById('filter-modal-id').value = '';
  4201. const badge = document.getElementById('fw-modal-badge');
  4202. if (badge) badge.innerText = 'New...';
  4203. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4204. }
  4205. function resetRuleCounterDisplay() {
  4206. state.fwStatRateHistory = new Array(30).fill(0);
  4207. state.fwStatPktHistory = new Array(30).fill(0);
  4208. state.fwLastBytes = 0;
  4209. state.fwLastPackets = 0;
  4210. state.fwLastTimestamp = Date.now();
  4211. const bEl = document.getElementById('fw-stat-bytes');
  4212. const pEl = document.getElementById('fw-stat-packets');
  4213. const rEl = document.getElementById('fw-stat-rate');
  4214. const prEl = document.getElementById('fw-stat-pktrate');
  4215. if (bEl) bEl.value = '0 B';
  4216. if (pEl) pEl.value = '0';
  4217. if (rEl) rEl.value = '0 bps';
  4218. if (prEl) prEl.value = '0 p/s';
  4219. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4220. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4221. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4222. }
  4223. async function resetAllFwCounters() {
  4224. try {
  4225. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4226. if (res.ok) {
  4227. resetRuleCounterDisplay();
  4228. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4229. loadFirewall(false);
  4230. }
  4231. } catch (err) {
  4232. showToast('Error', err.message, 'error');
  4233. }
  4234. }
  4235. async function applyFilterRule(closeAfter = false) {
  4236. const id = document.getElementById('filter-modal-id').value;
  4237. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4238. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4239. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4240. const chainLower = chain.toLowerCase();
  4241. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4242. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4243. switchFwRuleTab('general');
  4244. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4245. return;
  4246. }
  4247. const action = document.getElementById('filter-modal-action').value;
  4248. const comment = document.getElementById('filter-modal-comment').value.trim();
  4249. const enabled = document.getElementById('filter-modal-enabled').checked;
  4250. const src = getFwFieldVal('src', true);
  4251. const dst = getFwFieldVal('dst', true);
  4252. const srclist = getFwFieldVal('srclist', true);
  4253. const dstlist = getFwFieldVal('dstlist', true);
  4254. const srcgeo = getFwFieldVal('srcgeo', true);
  4255. const dstgeo = getFwFieldVal('dstgeo', true);
  4256. const proto = getFwFieldVal('proto', true);
  4257. const sport = getFwFieldVal('sport', true);
  4258. const dport = getFwFieldVal('dport', true);
  4259. const anyport = getFwFieldVal('anyport', true);
  4260. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4261. switchFwRuleTab('general'); toggleFwField('proto', true);
  4262. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4263. }
  4264. let iniface = getFwFieldVal('iniface', true);
  4265. let outiface = getFwFieldVal('outiface', true);
  4266. let inifacelist = getFwFieldVal('inifacelist', true);
  4267. let outifacelist = getFwFieldVal('outifacelist', true);
  4268. if (chainLower === 'input') {
  4269. outiface = '';
  4270. outifacelist = '';
  4271. } else if (chainLower === 'output') {
  4272. iniface = '';
  4273. inifacelist = '';
  4274. }
  4275. const pktmark = getFwFieldVal('pktmark', true);
  4276. const connmark = getFwFieldVal('connmark', true);
  4277. const routingmark = getFwFieldVal('routingmark', true);
  4278. const conntype = getFwFieldVal('conntype', false);
  4279. const states = [];
  4280. const csBox = document.getElementById('fw-field-cs');
  4281. if (csBox && !csBox.classList.contains('hidden')) {
  4282. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4283. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4284. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4285. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4286. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4287. }
  4288. const natStates = [];
  4289. const natBox = document.getElementById('fw-field-natstate');
  4290. if (natBox && !natBox.classList.contains('hidden')) {
  4291. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4292. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4293. }
  4294. const payload = {
  4295. ip_version: Number(document.getElementById('filter-modal-family').value),
  4296. id,
  4297. chain,
  4298. action,
  4299. protocol: proto || 'all',
  4300. src_address: src,
  4301. dst_address: dst,
  4302. src_port: sport,
  4303. dst_port: dport,
  4304. any_port: anyport,
  4305. in_interface: iniface,
  4306. out_interface: outiface,
  4307. in_interface_list: inifacelist,
  4308. out_interface_list: outifacelist,
  4309. packet_mark: pktmark,
  4310. connection_mark: connmark,
  4311. routing_mark: routingmark,
  4312. connection_type: conntype,
  4313. connection_state: states,
  4314. connection_nat_state: natStates,
  4315. src_address_list: srclist,
  4316. dst_address_list: dstlist,
  4317. src_geoip: srcgeo,
  4318. dst_geoip: dstgeo,
  4319. comment,
  4320. disabled: !enabled,
  4321. // Advanced tab
  4322. content: getFwFieldVal('content', false),
  4323. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4324. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4325. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4326. ipsec_policy: getFwFieldVal('ipsec', false),
  4327. dscp: getFwFieldVal('dscp', false),
  4328. tcp_mss: getFwFieldVal('tcpmss', false),
  4329. tos: document.getElementById('fw-val-tos')?.value || '',
  4330. packet_size: getFwFieldVal('pktsize', false),
  4331. random: getFwFieldVal('random', false),
  4332. tcp_flags: getFwFieldVal('tcpflags', false),
  4333. icmp_options: getFwFieldVal('icmpoptions', false),
  4334. ttl: getFwFieldVal('ttl', false),
  4335. days: selectedDays,
  4336. // Extra tab
  4337. time: getFwFieldVal('time', false),
  4338. limit: getFwFieldVal('limit', false),
  4339. // Action tab
  4340. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4341. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4342. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4343. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4344. log: document.getElementById('filter-modal-log')?.checked || false,
  4345. log_prefix: getFwFieldVal('logprefix', false)
  4346. };
  4347. try {
  4348. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4349. method: 'POST',
  4350. headers: { 'Content-Type': 'application/json' },
  4351. body: JSON.stringify(payload)
  4352. });
  4353. if (res.ok) {
  4354. const data = await res.json();
  4355. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4356. loadFirewall(false);
  4357. if (closeAfter) {
  4358. closeFilterModal();
  4359. } else {
  4360. if (data.id) {
  4361. document.getElementById('filter-modal-id').value = data.id;
  4362. const badge = document.getElementById('fw-modal-badge');
  4363. if (badge) badge.innerText = `#${data.id}`;
  4364. }
  4365. }
  4366. } else {
  4367. const err = await res.json();
  4368. showToast('Error', err.message || 'Failed to save rule', 'error');
  4369. }
  4370. } catch (err) {
  4371. showToast('Error', err.message, 'error');
  4372. }
  4373. }
  4374. function submitSaveFilterRule(e) {
  4375. if (e && e.preventDefault) e.preventDefault();
  4376. return applyFilterRule(true);
  4377. }
  4378. function startFwStatPolling() {
  4379. stopFwStatPolling();
  4380. pollRuleStats();
  4381. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4382. }
  4383. function stopFwStatPolling() {
  4384. if (state.fwStatInterval) {
  4385. clearInterval(state.fwStatInterval);
  4386. state.fwStatInterval = null;
  4387. }
  4388. }
  4389. async function pollRuleStats() {
  4390. const id = document.getElementById('filter-modal-id')?.value;
  4391. if (!id) {
  4392. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4393. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4394. return;
  4395. }
  4396. try {
  4397. const res = await fetch(`${API_BASE}/firewall/filter`);
  4398. if (!res.ok) return;
  4399. const rules = await res.json();
  4400. const r = rules.find(x => x.id === id);
  4401. if (!r) return;
  4402. const now = Date.now();
  4403. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4404. state.fwLastTimestamp = now;
  4405. const curBytes = r.bytes || 0;
  4406. const curPackets = r.packets || 0;
  4407. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4408. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4409. state.fwLastBytes = curBytes;
  4410. state.fwLastPackets = curPackets;
  4411. const rateBps = Math.round((deltaBytes * 8) / dt);
  4412. const ratePkt = Math.round(deltaPkts / dt);
  4413. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4414. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4415. state.fwStatRateHistory.push(rateBps);
  4416. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4417. state.fwStatPktHistory.push(ratePkt);
  4418. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4419. const bEl = document.getElementById('fw-stat-bytes');
  4420. const pEl = document.getElementById('fw-stat-packets');
  4421. const rEl = document.getElementById('fw-stat-rate');
  4422. const prEl = document.getElementById('fw-stat-pktrate');
  4423. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4424. if (pEl) pEl.value = curPackets.toLocaleString();
  4425. if (rEl) rEl.value = formatBps(rateBps);
  4426. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4427. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4428. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4429. } catch (e) {
  4430. console.error('Error polling rule stats', e);
  4431. }
  4432. }
  4433. function formatBps(bps) {
  4434. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4435. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4436. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4437. return bps + ' bps';
  4438. }
  4439. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4440. const svg = document.getElementById(svgId);
  4441. if (!svg) return;
  4442. const w = 500;
  4443. const h = 100;
  4444. const paddingRight = 45;
  4445. const graphWidth = w - paddingRight;
  4446. const maxVal = Math.max(5, ...dataArray);
  4447. const currentVal = dataArray[dataArray.length - 1] || 0;
  4448. const leg = document.getElementById(legendId);
  4449. if (leg) {
  4450. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4451. }
  4452. let gridLines = '';
  4453. for (let i = 0; i <= 5; i++) {
  4454. const y = 8 + (i * (h - 18) / 5);
  4455. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4456. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4457. gridLines += `
  4458. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4459. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4460. `;
  4461. }
  4462. const step = graphWidth / (dataArray.length - 1);
  4463. const points = dataArray.map((val, idx) => {
  4464. const x = idx * step;
  4465. const y = (h - 10) - (val / maxVal) * (h - 20);
  4466. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4467. });
  4468. const polylineStr = points.join(' ');
  4469. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4470. svg.innerHTML = `
  4471. ${gridLines}
  4472. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4473. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4474. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4475. `;
  4476. }
  4477. async function moveFilterRule(id, dir) {
  4478. id = decodeURIComponent(id);
  4479. try {
  4480. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4481. method: 'POST',
  4482. headers: { 'Content-Type': 'application/json' },
  4483. body: JSON.stringify({ direction: dir })
  4484. });
  4485. if (!res.ok) throw new Error(await responseError(res));
  4486. await loadFirewall(false);
  4487. } catch (err) {
  4488. showToast('Error', err.message, 'error');
  4489. }
  4490. }
  4491. async function toggleFilterRuleState(id, disabled) {
  4492. id = decodeURIComponent(id);
  4493. try {
  4494. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4495. method: 'POST',
  4496. headers: { 'Content-Type': 'application/json' },
  4497. body: JSON.stringify({ disabled })
  4498. });
  4499. if (!res.ok) throw new Error(await responseError(res));
  4500. await loadFirewall(false);
  4501. } catch (err) {
  4502. showToast('Error', err.message, 'error');
  4503. }
  4504. }
  4505. async function deleteFilterRule(id) {
  4506. id = decodeURIComponent(id);
  4507. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4508. try {
  4509. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4510. if (!res.ok) throw new Error(await responseError(res));
  4511. {
  4512. showToast('Deleted', 'Filter rule removed', 'success');
  4513. loadFirewall(false);
  4514. }
  4515. } catch (err) {
  4516. showToast('Error', err.message, 'error');
  4517. }
  4518. }
  4519. // ----------------- NAT Rules -----------------
  4520. function renderNATRules() {
  4521. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4522. const tbody = document.getElementById('nat-table-body');
  4523. const empty = document.getElementById('nat-empty');
  4524. if (!tbody) return;
  4525. tbody.innerHTML = '';
  4526. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4527. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4528. if (rules.length === 0) {
  4529. empty?.classList.remove('hidden');
  4530. return;
  4531. }
  4532. empty?.classList.add('hidden');
  4533. rules.forEach((raw, idx) => {
  4534. const r = safeFirewallRow(raw);
  4535. const tr = document.createElement('tr');
  4536. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4537. let toTarget = '-';
  4538. if (r.action === 'jump') {
  4539. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4540. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4541. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4542. } else if (r.action === 'redirect') {
  4543. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4544. } else if (r.action === 'masquerade') {
  4545. 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>`;
  4546. } else if (r.action === 'log') {
  4547. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4548. } else {
  4549. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4550. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4551. }
  4552. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4553. tr.innerHTML = `
  4554. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4555. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4556. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4557. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4558. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4559. <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>
  4560. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4561. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4562. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4563. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4564. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4565. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4566. </td>
  4567. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4568. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4569. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4570. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4571. <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>
  4572. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4573. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4574. </td>
  4575. `;
  4576. tbody.appendChild(tr);
  4577. });
  4578. }
  4579. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4580. function switchNATRuleTab(tab) {
  4581. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4582. state.activeNATRuleTab = tab;
  4583. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4584. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4585. btn.classList.add('text-slate-400', 'border-transparent');
  4586. });
  4587. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4588. if (activeBtn) {
  4589. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4590. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4591. }
  4592. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4593. const activePane = document.getElementById(`nat-pane-${tab}`);
  4594. if (activePane) activePane.classList.remove('hidden');
  4595. if (tab === 'statistics') {
  4596. startNATStatPolling();
  4597. } else {
  4598. stopNATStatPolling();
  4599. }
  4600. }
  4601. function toggleNATField(fieldKey, expand) {
  4602. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4603. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4604. if (!plusBtn || !fieldBox) return;
  4605. if (expand) {
  4606. plusBtn.classList.add('hidden');
  4607. fieldBox.classList.remove('hidden');
  4608. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4609. if (valInput) valInput.focus();
  4610. } else {
  4611. fieldBox.classList.add('hidden');
  4612. plusBtn.classList.remove('hidden');
  4613. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4614. if (valInput) {
  4615. if (valInput.tagName === 'SELECT') {
  4616. valInput.selectedIndex = 0;
  4617. } else {
  4618. valInput.value = '';
  4619. }
  4620. }
  4621. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4622. if (invInput) invInput.checked = false;
  4623. if (fieldKey === 'days') {
  4624. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4625. const el = document.getElementById(`nat-day-${d}`);
  4626. if (el) el.checked = true;
  4627. });
  4628. }
  4629. }
  4630. }
  4631. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4632. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4633. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4634. toggleNATField(fieldKey, true);
  4635. let strVal = String(value);
  4636. if (hasInvert) {
  4637. const inv = strVal.startsWith('!');
  4638. if (inv) strVal = strVal.slice(1);
  4639. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4640. if (invEl) invEl.checked = inv;
  4641. else if (inv) strVal = '!'+strVal;
  4642. }
  4643. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4644. 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; }
  4645. } else {
  4646. toggleNATField(fieldKey, false);
  4647. }
  4648. }
  4649. function getNATFieldVal(fieldKey, hasInvert = false) {
  4650. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4651. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4652. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4653. let v = valEl ? valEl.value.trim() : '';
  4654. if (!v) return '';
  4655. if (hasInvert) {
  4656. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4657. if (invEl && invEl.checked) {
  4658. v = '!' + v.replace(/^!/, '');
  4659. }
  4660. }
  4661. return v;
  4662. }
  4663. function toggleMaximizeNATModal() {
  4664. const win = document.getElementById('nat-modal-window');
  4665. if (!win) return;
  4666. if (win.classList.contains('max-w-[720px]')) {
  4667. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4668. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4669. } else {
  4670. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4671. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4672. }
  4673. }
  4674. function syncNATChainFromSelect() {
  4675. const sel = document.getElementById('nat-modal-chain-select');
  4676. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4677. const customInput = document.getElementById('nat-modal-custom-input');
  4678. const chainInput = document.getElementById('nat-modal-chain');
  4679. if (!sel || !chainInput) return;
  4680. if (sel.value === '__custom__') {
  4681. if (customWrap) customWrap.classList.remove('hidden');
  4682. if (customInput) {
  4683. customInput.value = '';
  4684. customInput.focus();
  4685. }
  4686. chainInput.value = '';
  4687. } else {
  4688. if (customWrap) customWrap.classList.add('hidden');
  4689. chainInput.value = sel.value;
  4690. const actEl = document.getElementById('nat-modal-action');
  4691. if (actEl) {
  4692. const curAct = actEl.value;
  4693. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4694. actEl.value = 'dst-nat';
  4695. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4696. actEl.value = 'masquerade';
  4697. }
  4698. }
  4699. }
  4700. handleNATChainChange();
  4701. }
  4702. function syncNATCustomChainInput() {
  4703. const customInput = document.getElementById('nat-modal-custom-input');
  4704. const chainInput = document.getElementById('nat-modal-chain');
  4705. if (customInput && chainInput) {
  4706. chainInput.value = customInput.value.trim();
  4707. }
  4708. handleNATChainChange();
  4709. }
  4710. function handleNATChainChange() {
  4711. const chainInput = document.getElementById('nat-modal-chain');
  4712. const rawChain = (chainInput?.value || 'postrouting').trim();
  4713. const chain = nativeNATChain(rawChain).toLowerCase();
  4714. const sel = document.getElementById('nat-modal-chain-select');
  4715. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4716. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4717. sel.value = chain;
  4718. }
  4719. }
  4720. const hintEl = document.getElementById('nat-chain-hint');
  4721. if (hintEl) {
  4722. if (chain === 'prerouting') {
  4723. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4724. } else if (chain === 'postrouting') {
  4725. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4726. } else if (chain === 'output') {
  4727. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4728. } else if (chain === 'input') {
  4729. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4730. } else {
  4731. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4732. }
  4733. }
  4734. const rowIn = document.getElementById('nat-row-iniface');
  4735. const rowInList = document.getElementById('nat-row-inifacelist');
  4736. const rowOut = document.getElementById('nat-row-outiface');
  4737. const rowOutList = document.getElementById('nat-row-outifacelist');
  4738. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4739. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4740. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4741. if (chain === 'prerouting' || chain === 'input') {
  4742. if (rowIn) rowIn.classList.remove('hidden');
  4743. if (rowInList) rowInList.classList.remove('hidden');
  4744. if (rowOut) rowOut.classList.add('hidden');
  4745. if (rowOutList) rowOutList.classList.add('hidden');
  4746. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4747. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4748. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4749. } else if (chain === 'postrouting' || chain === 'output') {
  4750. if (rowIn) rowIn.classList.add('hidden');
  4751. if (rowInList) rowInList.classList.add('hidden');
  4752. if (rowOut) rowOut.classList.remove('hidden');
  4753. if (rowOutList) rowOutList.classList.remove('hidden');
  4754. if (rowInBridge) rowInBridge.classList.add('hidden');
  4755. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4756. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4757. } else {
  4758. if (rowIn) rowIn.classList.remove('hidden');
  4759. if (rowInList) rowInList.classList.remove('hidden');
  4760. if (rowOut) rowOut.classList.remove('hidden');
  4761. if (rowOutList) rowOutList.classList.remove('hidden');
  4762. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4763. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4764. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4765. }
  4766. checkNATActionChainCompatibility();
  4767. toggleNATActionFields();
  4768. }
  4769. function checkNATActionChainCompatibility() {
  4770. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4771. const chain = nativeNATChain(rawChain).toLowerCase();
  4772. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4773. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4774. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4775. if (!warnBox || !warnMsg) return;
  4776. let msg = '';
  4777. if (['dst-nat', 'redirect'].includes(action)) {
  4778. if (chain !== 'prerouting' && chain !== 'output') {
  4779. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4780. }
  4781. } else if (action === 'masquerade') {
  4782. if (chain !== 'postrouting') {
  4783. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4784. }
  4785. } else if (action === 'src-nat') {
  4786. if (chain !== 'postrouting' && chain !== 'input') {
  4787. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4788. }
  4789. }
  4790. if (msg) {
  4791. warnMsg.textContent = msg;
  4792. warnBox.classList.remove('hidden');
  4793. } else {
  4794. warnBox.classList.add('hidden');
  4795. }
  4796. }
  4797. function toggleNATActionFields() {
  4798. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4799. const rowAddr = document.getElementById('nat-row-toaddr');
  4800. const rowPort = document.getElementById('nat-row-toport');
  4801. const jumpBox = document.getElementById('nat-action-jump-box');
  4802. const addrBox = document.getElementById('nat-action-addrlist-box');
  4803. // Hide all dynamic rows first
  4804. if (rowAddr) rowAddr.classList.add('hidden');
  4805. if (rowPort) rowPort.classList.add('hidden');
  4806. if (jumpBox) jumpBox.classList.add('hidden');
  4807. if (addrBox) addrBox.classList.add('hidden');
  4808. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4809. if (rowAddr) rowAddr.classList.remove('hidden');
  4810. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4811. } else if (act === 'redirect' || act === 'masquerade') {
  4812. if (rowPort) rowPort.classList.remove('hidden');
  4813. } else if (act === 'jump') {
  4814. if (jumpBox) jumpBox.classList.remove('hidden');
  4815. } else if (act.includes('address-list') || act.includes('address list')) {
  4816. if (addrBox) addrBox.classList.remove('hidden');
  4817. }
  4818. if (act === 'log') {
  4819. const logEl = document.getElementById('nat-modal-log');
  4820. if (logEl) logEl.checked = true;
  4821. toggleNATField('logprefix', true);
  4822. }
  4823. }
  4824. function handleNATActionChange() {
  4825. toggleNATActionFields();
  4826. checkNATActionChainCompatibility();
  4827. }
  4828. function toggleNATLogPrefix() {
  4829. const isLog = document.getElementById('nat-modal-log')?.checked;
  4830. toggleNATField('logprefix', !!isLog);
  4831. }
  4832. function openAddNATModal() {
  4833. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4834. switchNATRuleTab('general');
  4835. setFirewallDays('nat', '');
  4836. const badge = document.getElementById('nat-modal-badge');
  4837. if (badge) badge.innerText = 'New...';
  4838. document.getElementById('nat-modal-id').value = '';
  4839. document.getElementById('nat-modal-family').value = '4';
  4840. document.getElementById('nat-modal-enabled').checked = true;
  4841. document.getElementById('nat-modal-comment').value = '';
  4842. document.getElementById('nat-modal-chain').value = 'postrouting';
  4843. populateChainDropdown('nat', 'postrouting');
  4844. handleNATChainChange();
  4845. document.getElementById('nat-modal-action').value = 'masquerade';
  4846. document.getElementById('nat-modal-toaddr').value = '';
  4847. document.getElementById('nat-modal-toport').value = '';
  4848. document.getElementById('nat-modal-log').checked = false;
  4849. populateInterfaceSelect('nat-val-iniface');
  4850. populateInterfaceSelect('nat-val-outiface');
  4851. populateAddressListSelect('nat-val-srclist');
  4852. populateAddressListSelect('nat-val-dstlist');
  4853. populateGeoIPSelect('nat-val-srcgeo');
  4854. populateGeoIPSelect('nat-val-dstgeo');
  4855. const allFieldKeys = [
  4856. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4857. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4858. 'routingmark', 'conntype',
  4859. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4860. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4861. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4862. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4863. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4864. ];
  4865. allFieldKeys.forEach(k => toggleNATField(k, false));
  4866. resetNATCounterDisplay();
  4867. toggleNATActionFields();
  4868. document.getElementById('nat-modal').classList.remove('hidden');
  4869. }
  4870. function openEditNATModal(id) {
  4871. id = decodeURIComponent(id);
  4872. const r = (state.natRules || []).find(rule => rule.id === id);
  4873. if (!r) return;
  4874. setFirewallDays('nat', r.days || '');
  4875. switchNATRuleTab('general');
  4876. const badge = document.getElementById('nat-modal-badge');
  4877. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4878. document.getElementById('nat-modal-id').value = r.id;
  4879. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4880. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4881. document.getElementById('nat-modal-comment').value = r.comment || '';
  4882. const natChain = nativeNATChain(r.chain || 'postrouting');
  4883. document.getElementById('nat-modal-chain').value = natChain;
  4884. populateChainDropdown('nat', natChain);
  4885. handleNATChainChange();
  4886. setFirewallActionSelection('nat', r.action || 'accept');
  4887. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4888. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4889. document.getElementById('nat-modal-log').checked = !!r.log;
  4890. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4891. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4892. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4893. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4894. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4895. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4896. setNATFieldVal('src', r.src_address, true);
  4897. setNATFieldVal('dst', r.dst_address, true);
  4898. setNATFieldVal('srclist', r.src_address_list, true);
  4899. setNATFieldVal('dstlist', r.dst_address_list, true);
  4900. setNATFieldVal('srcgeo', r.src_geoip, true);
  4901. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4902. if (r.protocol && r.protocol !== 'all') {
  4903. setNATFieldVal('proto', r.protocol, true);
  4904. } else {
  4905. toggleNATField('proto', false);
  4906. }
  4907. setNATFieldVal('sport', r.src_port, true);
  4908. setNATFieldVal('dport', r.dst_port, true);
  4909. setNATFieldVal('anyport', r.any_port, true);
  4910. setNATFieldVal('iniface', r.in_interface, true);
  4911. setNATFieldVal('outiface', r.out_interface, true);
  4912. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4913. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4914. setNATFieldVal('pktmark', r.packet_mark, true);
  4915. setNATFieldVal('connmark', r.connection_mark, true);
  4916. setNATFieldVal('routingmark', r.routing_mark, true);
  4917. setNATFieldVal('conntype', r.connection_type, false);
  4918. // Advanced tab fields
  4919. setNATFieldVal('layer7', r.layer7_protocol, false);
  4920. setNATFieldVal('content', r.content, false);
  4921. setNATFieldVal('connbytes', r.connection_bytes, false);
  4922. setNATFieldVal('connrate', r.connection_rate, false);
  4923. setNATFieldVal('pcc', r.pcc, false);
  4924. setNATFieldVal('srcmac', r.src_mac_address, true);
  4925. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4926. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4927. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4928. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4929. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4930. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4931. setNATFieldVal('priority', r.priority, false);
  4932. setNATFieldVal('dscp', r.dscp, false);
  4933. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4934. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4935. setNATFieldVal('pktsize', r.packet_size, false);
  4936. setNATFieldVal('random', r.random, false);
  4937. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4938. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4939. setNATFieldVal('ttl', r.ttl, false);
  4940. // Extra tab fields
  4941. setNATFieldVal('time', r.time, false);
  4942. if (r.days) {
  4943. toggleNATField('days', true);
  4944. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4945. const chk = document.getElementById(`nat-day-${d}`);
  4946. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4947. });
  4948. } else {
  4949. toggleNATField('days', false);
  4950. }
  4951. setNATFieldVal('limit', r.limit, false);
  4952. setNATFieldVal('dstlimit', r.dst_limit, false);
  4953. setNATFieldVal('psd', r.psd, false);
  4954. // Action fields
  4955. if (r.jump_target) {
  4956. const jtEl = document.getElementById('nat-modal-jumptarget');
  4957. if (jtEl) jtEl.value = r.jump_target;
  4958. }
  4959. if (r.address_list) {
  4960. const alEl = document.getElementById('nat-modal-action-addrlist');
  4961. if (alEl) alEl.value = r.address_list;
  4962. }
  4963. if (r.address_list_timeout) {
  4964. const toEl = document.getElementById('nat-modal-action-timeout');
  4965. if (toEl) toEl.value = r.address_list_timeout;
  4966. }
  4967. setNATFieldVal('logprefix', r.log_prefix, false);
  4968. // Statistics
  4969. const bEl = document.getElementById('nat-stat-bytes');
  4970. const pEl = document.getElementById('nat-stat-packets');
  4971. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4972. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4973. state.natLastBytes = r.bytes || 0;
  4974. state.natLastPackets = r.packets || 0;
  4975. state.natLastTimestamp = Date.now();
  4976. state.natStatRateHistory = new Array(30).fill(0);
  4977. state.natStatPktHistory = new Array(30).fill(0);
  4978. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4979. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4980. toggleNATActionFields();
  4981. document.getElementById('nat-modal').classList.remove('hidden');
  4982. }
  4983. function closeNATModal() {
  4984. stopNATStatPolling();
  4985. document.getElementById('nat-modal').classList.add('hidden');
  4986. }
  4987. function copyNATRule() {
  4988. document.getElementById('nat-modal-id').value = '';
  4989. const badge = document.getElementById('nat-modal-badge');
  4990. if (badge) badge.innerText = 'New...';
  4991. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4992. }
  4993. function resetNATCounterDisplay() {
  4994. state.natStatRateHistory = new Array(30).fill(0);
  4995. state.natStatPktHistory = new Array(30).fill(0);
  4996. state.natLastBytes = 0;
  4997. state.natLastPackets = 0;
  4998. state.natLastTimestamp = Date.now();
  4999. const bEl = document.getElementById('nat-stat-bytes');
  5000. const pEl = document.getElementById('nat-stat-packets');
  5001. const rEl = document.getElementById('nat-stat-rate');
  5002. const prEl = document.getElementById('nat-stat-pktrate');
  5003. if (bEl) bEl.value = '0 B';
  5004. if (pEl) pEl.value = '0';
  5005. if (rEl) rEl.value = '0 bps';
  5006. if (prEl) prEl.value = '0 p/s';
  5007. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5008. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5009. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5010. }
  5011. async function applyNATRule(closeAfter = false) {
  5012. const id = document.getElementById('nat-modal-id').value;
  5013. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5014. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5015. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5016. const chainLower = nativeNATChain(chain).toLowerCase();
  5017. const action = document.getElementById('nat-modal-action').value;
  5018. const comment = document.getElementById('nat-modal-comment').value.trim();
  5019. const enabled = document.getElementById('nat-modal-enabled').checked;
  5020. const src = getNATFieldVal('src', true);
  5021. const dst = getNATFieldVal('dst', true);
  5022. const srclist = getNATFieldVal('srclist', true);
  5023. const dstlist = getNATFieldVal('dstlist', true);
  5024. const srcgeo = getNATFieldVal('srcgeo', true);
  5025. const dstgeo = getNATFieldVal('dstgeo', true);
  5026. const proto = getNATFieldVal('proto', true);
  5027. const sport = getNATFieldVal('sport', true);
  5028. const dport = getNATFieldVal('dport', true);
  5029. const anyport = getNATFieldVal('anyport', true);
  5030. let iniface = getNATFieldVal('iniface', true);
  5031. let outiface = getNATFieldVal('outiface', true);
  5032. let inifacelist = getNATFieldVal('inifacelist', true);
  5033. let outifacelist = getNATFieldVal('outifacelist', true);
  5034. if (chainLower === 'prerouting' || chainLower === 'input') {
  5035. outiface = '';
  5036. outifacelist = '';
  5037. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5038. iniface = '';
  5039. inifacelist = '';
  5040. }
  5041. const pktmark = getNATFieldVal('pktmark', true);
  5042. const connmark = getNATFieldVal('connmark', true);
  5043. const routingmark = getNATFieldVal('routingmark', true);
  5044. const conntype = getNATFieldVal('conntype', false);
  5045. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5046. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5047. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5048. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5049. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5050. switchNATRuleTab('general');
  5051. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5052. return;
  5053. }
  5054. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5055. switchNATRuleTab('general');
  5056. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5057. return;
  5058. }
  5059. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5060. switchNATRuleTab('general');
  5061. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5062. return;
  5063. }
  5064. 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; }
  5065. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5066. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5067. 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;
  5068. }
  5069. const payload = {
  5070. ip_version: Number(document.getElementById('nat-modal-family').value),
  5071. id,
  5072. chain,
  5073. action,
  5074. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5075. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5076. protocol: proto || 'all',
  5077. src_address: src,
  5078. dst_address: dst,
  5079. src_port: sport,
  5080. dst_port: dport,
  5081. any_port: anyport,
  5082. in_interface: iniface,
  5083. out_interface: outiface,
  5084. in_interface_list: inifacelist,
  5085. out_interface_list: outifacelist,
  5086. packet_mark: pktmark,
  5087. connection_mark: connmark,
  5088. routing_mark: routingmark,
  5089. connection_type: conntype,
  5090. src_address_list: srclist,
  5091. dst_address_list: dstlist,
  5092. src_geoip: srcgeo,
  5093. dst_geoip: dstgeo,
  5094. comment,
  5095. disabled: !enabled,
  5096. // Advanced tab
  5097. content: getNATFieldVal('content', false),
  5098. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5099. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5100. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5101. ipsec_policy: getNATFieldVal('ipsec', false),
  5102. dscp: getNATFieldVal('dscp', false),
  5103. tcp_mss: getNATFieldVal('tcpmss', false),
  5104. tos: document.getElementById('nat-val-tos')?.value || '',
  5105. packet_size: getNATFieldVal('pktsize', false),
  5106. random: getNATFieldVal('random', false),
  5107. icmp_options: getNATFieldVal('icmpoptions', false),
  5108. ttl: getNATFieldVal('ttl', false),
  5109. days: selectedDays,
  5110. // Extra tab
  5111. time: getNATFieldVal('time', false),
  5112. limit: getNATFieldVal('limit', false),
  5113. // Action tab
  5114. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5115. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5116. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5117. log: document.getElementById('nat-modal-log')?.checked || false,
  5118. log_prefix: getNATFieldVal('logprefix', false)
  5119. };
  5120. try {
  5121. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5122. method: 'POST',
  5123. headers: { 'Content-Type': 'application/json' },
  5124. body: JSON.stringify(payload)
  5125. });
  5126. if (res.ok) {
  5127. const data = await res.json();
  5128. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5129. loadFirewall(false);
  5130. if (closeAfter) {
  5131. closeNATModal();
  5132. } else {
  5133. if (data.id) {
  5134. document.getElementById('nat-modal-id').value = data.id;
  5135. const badge = document.getElementById('nat-modal-badge');
  5136. if (badge) badge.innerText = `#${data.id}`;
  5137. }
  5138. }
  5139. } else {
  5140. const err = await res.json();
  5141. showToast('Error', err.message || 'Failed to save rule', 'error');
  5142. }
  5143. } catch (err) {
  5144. showToast('Error', err.message, 'error');
  5145. }
  5146. }
  5147. function submitSaveNATRule(e) {
  5148. if (e && e.preventDefault) e.preventDefault();
  5149. return applyNATRule(true);
  5150. }
  5151. function startNATStatPolling() {
  5152. stopNATStatPolling();
  5153. pollNATRuleStats();
  5154. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5155. }
  5156. function stopNATStatPolling() {
  5157. if (state.natStatInterval) {
  5158. clearInterval(state.natStatInterval);
  5159. state.natStatInterval = null;
  5160. }
  5161. }
  5162. async function pollNATRuleStats() {
  5163. const id = document.getElementById('nat-modal-id')?.value;
  5164. if (!id) {
  5165. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5166. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5167. return;
  5168. }
  5169. try {
  5170. const res = await fetch(`${API_BASE}/firewall/nat`);
  5171. if (!res.ok) return;
  5172. const rules = await res.json();
  5173. const r = rules.find(x => x.id === id);
  5174. if (!r) return;
  5175. const now = Date.now();
  5176. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5177. state.natLastTimestamp = now;
  5178. const curBytes = r.bytes || 0;
  5179. const curPackets = r.packets || 0;
  5180. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5181. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5182. state.natLastBytes = curBytes;
  5183. state.natLastPackets = curPackets;
  5184. const rateBps = Math.round((deltaBytes * 8) / dt);
  5185. const ratePkt = Math.round(deltaPkts / dt);
  5186. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5187. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5188. state.natStatRateHistory.push(rateBps);
  5189. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5190. state.natStatPktHistory.push(ratePkt);
  5191. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5192. const bEl = document.getElementById('nat-stat-bytes');
  5193. const pEl = document.getElementById('nat-stat-packets');
  5194. const rEl = document.getElementById('nat-stat-rate');
  5195. const prEl = document.getElementById('nat-stat-pktrate');
  5196. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5197. if (pEl) pEl.value = curPackets.toLocaleString();
  5198. if (rEl) rEl.value = formatBps(rateBps);
  5199. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5200. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5201. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5202. } catch (e) {
  5203. console.error('Error polling NAT rule stats', e);
  5204. }
  5205. }
  5206. async function moveNATRule(id, dir) {
  5207. id = decodeURIComponent(id);
  5208. try {
  5209. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5210. method: 'POST',
  5211. headers: { 'Content-Type': 'application/json' },
  5212. body: JSON.stringify({ direction: dir })
  5213. });
  5214. if (!res.ok) throw new Error(await responseError(res));
  5215. await loadFirewall(false);
  5216. } catch (err) {
  5217. showToast('Error', err.message, 'error');
  5218. }
  5219. }
  5220. async function toggleNATRuleState(id, disabled) {
  5221. id = decodeURIComponent(id);
  5222. try {
  5223. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5224. method: 'POST',
  5225. headers: { 'Content-Type': 'application/json' },
  5226. body: JSON.stringify({ disabled })
  5227. });
  5228. if (!res.ok) throw new Error(await responseError(res));
  5229. await loadFirewall(false);
  5230. } catch (err) {
  5231. showToast('Error', err.message, 'error');
  5232. }
  5233. }
  5234. async function deleteNATRule(id) {
  5235. id = decodeURIComponent(id);
  5236. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5237. try {
  5238. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5239. if (!res.ok) throw new Error(await responseError(res));
  5240. {
  5241. showToast('Deleted', 'NAT rule removed', 'success');
  5242. loadFirewall(false);
  5243. }
  5244. } catch (err) {
  5245. showToast('Error', err.message, 'error');
  5246. }
  5247. }
  5248. // ----------------- Mangle Rules -----------------
  5249. function renderMangleRules() {
  5250. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5251. const tbody = document.getElementById('mangle-table-body');
  5252. const empty = document.getElementById('mangle-empty');
  5253. if (!tbody) return;
  5254. tbody.innerHTML = '';
  5255. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5256. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5257. if (rules.length === 0) {
  5258. empty?.classList.remove('hidden');
  5259. return;
  5260. }
  5261. empty?.classList.add('hidden');
  5262. rules.forEach((raw, idx) => {
  5263. const r = safeFirewallRow(raw);
  5264. const tr = document.createElement('tr');
  5265. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5266. let markVal = '<span class="text-slate-500">-</span>';
  5267. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5268. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5269. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5270. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5271. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5272. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5273. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5274. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5275. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5276. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5277. 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>`;
  5278. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5279. tr.innerHTML = `
  5280. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5281. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5282. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5283. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5284. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5285. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5286. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5287. <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>
  5288. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5289. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5290. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5291. </td>
  5292. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5293. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5294. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5295. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5296. <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>
  5297. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5298. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5299. </td>
  5300. `;
  5301. tbody.appendChild(tr);
  5302. });
  5303. }
  5304. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5305. function switchMangleRuleTab(tab) {
  5306. state.activeMangleRuleTab = tab;
  5307. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5308. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5309. btn.classList.add('text-slate-400', 'border-transparent');
  5310. });
  5311. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5312. if (activeBtn) {
  5313. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5314. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5315. }
  5316. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5317. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5318. if (activePane) activePane.classList.remove('hidden');
  5319. if (tab === 'statistics') {
  5320. startMangleStatPolling();
  5321. } else {
  5322. stopMangleStatPolling();
  5323. }
  5324. }
  5325. function toggleMangleField(fieldKey, expand) {
  5326. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5327. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5328. if (!plusBtn || !fieldBox) return;
  5329. if (expand) {
  5330. plusBtn.classList.add('hidden');
  5331. fieldBox.classList.remove('hidden');
  5332. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5333. if (valInput) valInput.focus();
  5334. } else {
  5335. fieldBox.classList.add('hidden');
  5336. plusBtn.classList.remove('hidden');
  5337. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5338. if (valInput) {
  5339. if (valInput.tagName === 'SELECT') {
  5340. valInput.selectedIndex = 0;
  5341. } else {
  5342. valInput.value = '';
  5343. }
  5344. }
  5345. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5346. if (invInput) invInput.checked = false;
  5347. if (fieldKey === 'cs') {
  5348. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5349. const el = document.getElementById(id);
  5350. if (el) el.checked = false;
  5351. });
  5352. }
  5353. if (fieldKey === 'natstate') {
  5354. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5355. const el = document.getElementById(id);
  5356. if (el) el.checked = false;
  5357. });
  5358. }
  5359. }
  5360. }
  5361. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5362. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5363. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5364. toggleMangleField(fieldKey, true);
  5365. let strVal = String(value);
  5366. if (hasInvert) {
  5367. const inv = strVal.startsWith('!');
  5368. if (inv) strVal = strVal.slice(1);
  5369. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5370. if (invEl) invEl.checked = inv;
  5371. else if (inv) strVal = '!'+strVal;
  5372. }
  5373. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5374. 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; }
  5375. } else {
  5376. toggleMangleField(fieldKey, false);
  5377. }
  5378. }
  5379. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5380. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5381. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5382. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5383. let v = valEl ? valEl.value.trim() : '';
  5384. if (!v) return '';
  5385. if (hasInvert) {
  5386. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5387. if (invEl && invEl.checked) {
  5388. v = '!' + v.replace(/^!/, '');
  5389. }
  5390. }
  5391. return v;
  5392. }
  5393. function toggleMaximizeMangleModal() {
  5394. const win = document.getElementById('mangle-modal-window');
  5395. if (!win) return;
  5396. if (win.classList.contains('max-w-[720px]')) {
  5397. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5398. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5399. } else {
  5400. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5401. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5402. }
  5403. }
  5404. function syncMangleChainFromSelect() {
  5405. const sel = document.getElementById('mangle-modal-chain-select');
  5406. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5407. const customInput = document.getElementById('mangle-modal-custom-input');
  5408. const chainInput = document.getElementById('mangle-modal-chain');
  5409. if (!sel || !chainInput) return;
  5410. if (sel.value === '__custom__') {
  5411. if (customWrap) customWrap.classList.remove('hidden');
  5412. if (customInput) {
  5413. customInput.value = '';
  5414. customInput.focus();
  5415. }
  5416. chainInput.value = '';
  5417. } else {
  5418. if (customWrap) customWrap.classList.add('hidden');
  5419. chainInput.value = sel.value;
  5420. }
  5421. handleMangleChainChange();
  5422. }
  5423. function syncMangleCustomChainInput() {
  5424. const customInput = document.getElementById('mangle-modal-custom-input');
  5425. const chainInput = document.getElementById('mangle-modal-chain');
  5426. if (customInput && chainInput) {
  5427. chainInput.value = customInput.value.trim();
  5428. }
  5429. handleMangleChainChange();
  5430. }
  5431. function handleMangleChainChange() {
  5432. const chainInput = document.getElementById('mangle-modal-chain');
  5433. const rawChain = (chainInput?.value || 'prerouting').trim();
  5434. const chain = rawChain.toLowerCase();
  5435. const sel = document.getElementById('mangle-modal-chain-select');
  5436. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5437. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5438. sel.value = chain;
  5439. }
  5440. }
  5441. const hintEl = document.getElementById('mangle-chain-hint');
  5442. if (hintEl) {
  5443. if (chain === 'prerouting') {
  5444. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5445. } else if (chain === 'input') {
  5446. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5447. } else if (chain === 'forward') {
  5448. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5449. } else if (chain === 'output') {
  5450. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5451. } else if (chain === 'postrouting') {
  5452. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5453. } else {
  5454. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5455. }
  5456. }
  5457. const rowIn = document.getElementById('mangle-row-iniface');
  5458. const rowInList = document.getElementById('mangle-row-inifacelist');
  5459. const rowOut = document.getElementById('mangle-row-outiface');
  5460. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5461. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5462. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5463. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5464. if (chain === 'prerouting' || chain === 'input') {
  5465. if (rowIn) rowIn.classList.remove('hidden');
  5466. if (rowInList) rowInList.classList.remove('hidden');
  5467. if (rowOut) rowOut.classList.add('hidden');
  5468. if (rowOutList) rowOutList.classList.add('hidden');
  5469. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5470. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5471. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5472. } else if (chain === 'output' || chain === 'postrouting') {
  5473. if (rowIn) rowIn.classList.add('hidden');
  5474. if (rowInList) rowInList.classList.add('hidden');
  5475. if (rowOut) rowOut.classList.remove('hidden');
  5476. if (rowOutList) rowOutList.classList.remove('hidden');
  5477. if (rowInBridge) rowInBridge.classList.add('hidden');
  5478. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5479. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5480. } else {
  5481. if (rowIn) rowIn.classList.remove('hidden');
  5482. if (rowInList) rowInList.classList.remove('hidden');
  5483. if (rowOut) rowOut.classList.remove('hidden');
  5484. if (rowOutList) rowOutList.classList.remove('hidden');
  5485. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5486. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5487. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5488. }
  5489. checkMangleActionChainCompatibility();
  5490. toggleMangleActionFields();
  5491. }
  5492. function checkMangleActionChainCompatibility() {
  5493. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5494. const chain = rawChain.toLowerCase();
  5495. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5496. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5497. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5498. if (!warnBox || !warnMsg) return;
  5499. let msg = '';
  5500. if (action === 'set-priority' && chain !== 'postrouting') {
  5501. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5502. }
  5503. if (msg) {
  5504. warnMsg.textContent = msg;
  5505. warnBox.classList.remove('hidden');
  5506. } else {
  5507. warnBox.classList.add('hidden');
  5508. }
  5509. }
  5510. function toggleMangleActionFields() {
  5511. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5512. // Hide all dynamic rows first
  5513. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5514. const el = document.getElementById(`mangle-row-${id}`);
  5515. if (el) el.classList.add('hidden');
  5516. });
  5517. const jumpBox = document.getElementById('mangle-action-jump-box');
  5518. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5519. if (jumpBox) jumpBox.classList.add('hidden');
  5520. if (addrBox) addrBox.classList.add('hidden');
  5521. // Activate matching rows
  5522. if (act === 'mark-connection') {
  5523. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5524. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5525. } else if (act === 'mark-routing') {
  5526. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5527. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5528. } else if (act === 'mark-packet') {
  5529. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5530. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5531. } else if (act === 'change-mss') {
  5532. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5533. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5534. } else if (act === 'change-dscp') {
  5535. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5536. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5537. } else if (act === 'change-ttl') {
  5538. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5539. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5540. } else if (act === 'set-priority') {
  5541. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5542. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5543. } else if (act === 'route') {
  5544. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5545. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5546. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5547. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5548. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5549. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5550. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5551. } else if (act === 'jump') {
  5552. if (jumpBox) jumpBox.classList.remove('hidden');
  5553. } else if (act.includes('address-list') || act.includes('address list')) {
  5554. if (addrBox) addrBox.classList.remove('hidden');
  5555. }
  5556. if (act === 'log') {
  5557. const logEl = document.getElementById('mangle-modal-log');
  5558. if (logEl) logEl.checked = true;
  5559. toggleMangleField('logprefix', true);
  5560. }
  5561. checkMangleActionChainCompatibility();
  5562. }
  5563. function toggleMangleLogPrefix() {
  5564. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5565. toggleMangleField('logprefix', !!isLog);
  5566. }
  5567. const allMangleFieldKeys = [
  5568. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5569. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5570. 'routingmark', 'conntype', 'cs', 'natstate',
  5571. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5572. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5573. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5574. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5575. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5576. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5577. ];
  5578. function openAddMangleModal() {
  5579. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5580. switchMangleRuleTab('general');
  5581. const badge = document.getElementById('mangle-modal-badge');
  5582. if (badge) badge.innerText = 'New...';
  5583. document.getElementById('mangle-modal-id').value = '';
  5584. document.getElementById('mangle-modal-family').value = '4';
  5585. document.getElementById('mangle-modal-enabled').checked = true;
  5586. document.getElementById('mangle-modal-comment').value = '';
  5587. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5588. populateChainDropdown('mangle', 'prerouting');
  5589. handleMangleChainChange();
  5590. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5591. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5592. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5593. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5594. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5595. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5596. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5597. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5598. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5599. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5600. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5601. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5602. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5603. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5604. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5605. populateInterfaceSelect('mangle-val-iniface');
  5606. populateInterfaceSelect('mangle-val-outiface');
  5607. populateAddressListSelect('mangle-val-srclist');
  5608. populateAddressListSelect('mangle-val-dstlist');
  5609. populateGeoIPSelect('mangle-val-srcgeo');
  5610. populateGeoIPSelect('mangle-val-dstgeo');
  5611. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5612. resetMangleCounterDisplay();
  5613. toggleMangleActionFields();
  5614. document.getElementById('mangle-modal').classList.remove('hidden');
  5615. }
  5616. function openEditMangleModal(id) {
  5617. id = decodeURIComponent(id);
  5618. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5619. if (!r) return;
  5620. switchMangleRuleTab('general');
  5621. const badge = document.getElementById('mangle-modal-badge');
  5622. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5623. document.getElementById('mangle-modal-id').value = r.id;
  5624. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5625. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5626. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5627. const mangleChain = r.chain || 'prerouting';
  5628. document.getElementById('mangle-modal-chain').value = mangleChain;
  5629. populateChainDropdown('mangle', mangleChain);
  5630. handleMangleChainChange();
  5631. setFirewallActionSelection('mangle', r.action || 'accept');
  5632. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5633. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5634. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5635. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5636. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5637. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5638. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5639. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5640. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5641. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5642. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5643. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5644. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5645. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5646. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5647. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5648. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5649. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5650. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5651. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5652. setMangleFieldVal('src', r.src_address, true);
  5653. setMangleFieldVal('dst', r.dst_address, true);
  5654. setMangleFieldVal('srclist', r.src_address_list, true);
  5655. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5656. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5657. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5658. if (r.protocol && r.protocol !== 'all') {
  5659. setMangleFieldVal('proto', r.protocol, true);
  5660. } else {
  5661. toggleMangleField('proto', false);
  5662. }
  5663. setMangleFieldVal('sport', r.src_port, true);
  5664. setMangleFieldVal('dport', r.dst_port, true);
  5665. setMangleFieldVal('anyport', r.any_port, true);
  5666. setMangleFieldVal('iniface', r.in_interface, true);
  5667. setMangleFieldVal('outiface', r.out_interface, true);
  5668. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5669. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5670. setMangleFieldVal('pktmark', r.packet_mark, true);
  5671. setMangleFieldVal('connmark', r.connection_mark, true);
  5672. setMangleFieldVal('routingmark', r.routing_mark, true);
  5673. setMangleFieldVal('conntype', r.connection_type, false);
  5674. // Connection State
  5675. const states = r.connection_state || [];
  5676. if (states.length > 0) {
  5677. toggleMangleField('cs', true);
  5678. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5679. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5680. if (el) el.checked = states.includes(s);
  5681. });
  5682. } else {
  5683. toggleMangleField('cs', false);
  5684. }
  5685. // Connection NAT State
  5686. const natStates = r.connection_nat_state || [];
  5687. if (natStates.length > 0) {
  5688. toggleMangleField('natstate', true);
  5689. ['srcnat', 'dstnat'].forEach(s => {
  5690. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5691. if (el) el.checked = natStates.includes(s);
  5692. });
  5693. } else {
  5694. toggleMangleField('natstate', false);
  5695. }
  5696. // Advanced tab fields
  5697. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5698. setMangleFieldVal('content', r.content, false);
  5699. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5700. setMangleFieldVal('connrate', r.connection_rate, false);
  5701. setMangleFieldVal('pcc', r.pcc, false);
  5702. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5703. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5704. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5705. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5706. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5707. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5708. setMangleFieldVal('tlshost', r.tls_host, false);
  5709. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5710. setMangleFieldVal('priority', r.priority, false);
  5711. setMangleFieldVal('dscp', r.dscp, false);
  5712. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5713. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5714. setMangleFieldVal('pktsize', r.packet_size, false);
  5715. setMangleFieldVal('random', r.random, false);
  5716. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5717. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5718. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5719. setMangleFieldVal('ttl', r.ttl, false);
  5720. // Extra tab fields
  5721. setMangleFieldVal('nth', r.nth, false);
  5722. setMangleFieldVal('connlimit', r.connection_limit, false);
  5723. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5724. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5725. setMangleFieldVal('hotspot', r.hotspot, false);
  5726. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5727. setMangleFieldVal('limit', r.limit, false);
  5728. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5729. setMangleFieldVal('time', r.time, false);
  5730. setMangleFieldVal('psd', r.psd, false);
  5731. // Action fields
  5732. if (r.jump_target) {
  5733. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5734. if (jtEl) jtEl.value = r.jump_target;
  5735. }
  5736. if (r.address_list) {
  5737. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5738. if (alEl) alEl.value = r.address_list;
  5739. }
  5740. if (r.address_list_timeout) {
  5741. const toEl = document.getElementById('mangle-modal-action-timeout');
  5742. if (toEl) toEl.value = r.address_list_timeout;
  5743. }
  5744. setMangleFieldVal('logprefix', r.log_prefix, false);
  5745. // Statistics
  5746. const bEl = document.getElementById('mangle-stat-bytes');
  5747. const pEl = document.getElementById('mangle-stat-packets');
  5748. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5749. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5750. state.mangleLastBytes = r.bytes || 0;
  5751. state.mangleLastPackets = r.packets || 0;
  5752. state.mangleLastTimestamp = Date.now();
  5753. state.mangleStatRateHistory = new Array(30).fill(0);
  5754. state.mangleStatPktHistory = new Array(30).fill(0);
  5755. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5756. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5757. toggleMangleActionFields();
  5758. document.getElementById('mangle-modal').classList.remove('hidden');
  5759. }
  5760. function closeMangleModal() {
  5761. stopMangleStatPolling();
  5762. document.getElementById('mangle-modal').classList.add('hidden');
  5763. }
  5764. function copyMangleRule() {
  5765. document.getElementById('mangle-modal-id').value = '';
  5766. const badge = document.getElementById('mangle-modal-badge');
  5767. if (badge) badge.innerText = 'New...';
  5768. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5769. }
  5770. function resetMangleCounterDisplay() {
  5771. state.mangleStatRateHistory = new Array(30).fill(0);
  5772. state.mangleStatPktHistory = new Array(30).fill(0);
  5773. state.mangleLastBytes = 0;
  5774. state.mangleLastPackets = 0;
  5775. state.mangleLastTimestamp = Date.now();
  5776. const bEl = document.getElementById('mangle-stat-bytes');
  5777. const pEl = document.getElementById('mangle-stat-packets');
  5778. const rEl = document.getElementById('mangle-stat-rate');
  5779. const prEl = document.getElementById('mangle-stat-pktrate');
  5780. if (bEl) bEl.value = '0 B';
  5781. if (pEl) pEl.value = '0';
  5782. if (rEl) rEl.value = '0 bps';
  5783. if (prEl) prEl.value = '0 p/s';
  5784. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5785. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5786. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5787. }
  5788. async function applyMangleRule(closeAfter = false) {
  5789. const id = document.getElementById('mangle-modal-id').value;
  5790. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5791. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5792. const chainLower = chain.toLowerCase();
  5793. const action = document.getElementById('mangle-modal-action').value;
  5794. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5795. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5796. const src = getMangleFieldVal('src', true);
  5797. const dst = getMangleFieldVal('dst', true);
  5798. const srclist = getMangleFieldVal('srclist', true);
  5799. const dstlist = getMangleFieldVal('dstlist', true);
  5800. const srcgeo = getMangleFieldVal('srcgeo', true);
  5801. const dstgeo = getMangleFieldVal('dstgeo', true);
  5802. const proto = getMangleFieldVal('proto', true);
  5803. const sport = getMangleFieldVal('sport', true);
  5804. const dport = getMangleFieldVal('dport', true);
  5805. const anyport = getMangleFieldVal('anyport', true);
  5806. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5807. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5808. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5809. }
  5810. let iniface = getMangleFieldVal('iniface', true);
  5811. let outiface = getMangleFieldVal('outiface', true);
  5812. let inifacelist = getMangleFieldVal('inifacelist', true);
  5813. let outifacelist = getMangleFieldVal('outifacelist', true);
  5814. if (chainLower === 'prerouting' || chainLower === 'input') {
  5815. outiface = '';
  5816. outifacelist = '';
  5817. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5818. iniface = '';
  5819. inifacelist = '';
  5820. }
  5821. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5822. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5823. switchMangleRuleTab('general');
  5824. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5825. return;
  5826. }
  5827. const pktmark = getMangleFieldVal('pktmark', true);
  5828. const connmark = getMangleFieldVal('connmark', true);
  5829. const routingmark = getMangleFieldVal('routingmark', true);
  5830. const conntype = getMangleFieldVal('conntype', false);
  5831. const states = [];
  5832. const csBox = document.getElementById('mangle-field-cs');
  5833. if (csBox && !csBox.classList.contains('hidden')) {
  5834. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5835. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5836. });
  5837. }
  5838. const natStates = [];
  5839. const natBox = document.getElementById('mangle-field-natstate');
  5840. if (natBox && !natBox.classList.contains('hidden')) {
  5841. ['srcnat', 'dstnat'].forEach(s => {
  5842. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5843. });
  5844. }
  5845. const payload = {
  5846. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5847. id,
  5848. chain,
  5849. action,
  5850. protocol: proto || 'all',
  5851. src_address: src,
  5852. dst_address: dst,
  5853. src_port: sport,
  5854. dst_port: dport,
  5855. any_port: anyport,
  5856. in_interface: iniface,
  5857. out_interface: outiface,
  5858. in_interface_list: inifacelist,
  5859. out_interface_list: outifacelist,
  5860. packet_mark: pktmark,
  5861. connection_mark: connmark,
  5862. routing_mark: routingmark,
  5863. connection_type: conntype,
  5864. connection_state: states,
  5865. connection_nat_state: natStates,
  5866. src_address_list: srclist,
  5867. dst_address_list: dstlist,
  5868. src_geoip: srcgeo,
  5869. dst_geoip: dstgeo,
  5870. comment,
  5871. disabled: !enabled,
  5872. // Advanced tab
  5873. content: getMangleFieldVal('content', false),
  5874. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5875. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5876. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5877. ipsec_policy: getMangleFieldVal('ipsec', false),
  5878. dscp: getMangleFieldVal('dscp', false),
  5879. tcp_mss: getMangleFieldVal('tcpmss', false),
  5880. tos: document.getElementById('mangle-val-tos')?.value || '',
  5881. packet_size: getMangleFieldVal('pktsize', false),
  5882. random: getMangleFieldVal('random', false),
  5883. tcp_flags: getMangleFieldVal('tcpflags', false),
  5884. icmp_options: getMangleFieldVal('icmpoptions', false),
  5885. ttl: getMangleFieldVal('ttl', false),
  5886. // Extra tab
  5887. nth: getMangleFieldVal('nth', false),
  5888. connection_limit: getMangleFieldVal('connlimit', false),
  5889. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5890. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5891. ip_fragment: getMangleFieldVal('ipfragment', false),
  5892. limit: getMangleFieldVal('limit', false),
  5893. time: getMangleFieldVal('time', false),
  5894. // Action tab
  5895. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5896. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5897. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5898. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5899. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5900. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5901. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5902. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5903. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5904. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5905. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5906. log: document.getElementById('mangle-modal-log')?.checked || false,
  5907. log_prefix: getMangleFieldVal('logprefix', false)
  5908. };
  5909. try {
  5910. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5911. method: 'POST',
  5912. headers: { 'Content-Type': 'application/json' },
  5913. body: JSON.stringify(payload)
  5914. });
  5915. if (res.ok) {
  5916. const data = await res.json();
  5917. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5918. loadFirewall(false);
  5919. if (closeAfter) {
  5920. closeMangleModal();
  5921. } else {
  5922. if (data.id) {
  5923. document.getElementById('mangle-modal-id').value = data.id;
  5924. const badge = document.getElementById('mangle-modal-badge');
  5925. if (badge) badge.innerText = `#${data.id}`;
  5926. }
  5927. }
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. function submitSaveMangleRule(e) {
  5937. if (e && e.preventDefault) e.preventDefault();
  5938. return applyMangleRule(true);
  5939. }
  5940. function startMangleStatPolling() {
  5941. stopMangleStatPolling();
  5942. pollMangleRuleStats();
  5943. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5944. }
  5945. function stopMangleStatPolling() {
  5946. if (state.mangleStatInterval) {
  5947. clearInterval(state.mangleStatInterval);
  5948. state.mangleStatInterval = null;
  5949. }
  5950. }
  5951. async function pollMangleRuleStats() {
  5952. const id = document.getElementById('mangle-modal-id')?.value;
  5953. if (!id) {
  5954. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5955. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5956. return;
  5957. }
  5958. try {
  5959. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5960. if (!res.ok) return;
  5961. const rules = await res.json();
  5962. const r = rules.find(x => x.id === id);
  5963. if (!r) return;
  5964. const now = Date.now();
  5965. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5966. state.mangleLastTimestamp = now;
  5967. const curBytes = r.bytes || 0;
  5968. const curPackets = r.packets || 0;
  5969. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5970. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5971. state.mangleLastBytes = curBytes;
  5972. state.mangleLastPackets = curPackets;
  5973. const rateBps = Math.round((deltaBytes * 8) / dt);
  5974. const ratePkt = Math.round(deltaPkts / dt);
  5975. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5976. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5977. state.mangleStatRateHistory.push(rateBps);
  5978. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5979. state.mangleStatPktHistory.push(ratePkt);
  5980. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5981. const bEl = document.getElementById('mangle-stat-bytes');
  5982. const pEl = document.getElementById('mangle-stat-packets');
  5983. const rEl = document.getElementById('mangle-stat-rate');
  5984. const prEl = document.getElementById('mangle-stat-pktrate');
  5985. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5986. if (pEl) pEl.value = curPackets.toLocaleString();
  5987. if (rEl) rEl.value = formatBps(rateBps);
  5988. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5989. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5990. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5991. } catch (e) {
  5992. console.error('Error polling Mangle rule stats', e);
  5993. }
  5994. }
  5995. async function moveMangleRule(id, dir) {
  5996. id = decodeURIComponent(id);
  5997. try {
  5998. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5999. method: 'POST',
  6000. headers: { 'Content-Type': 'application/json' },
  6001. body: JSON.stringify({ direction: dir })
  6002. });
  6003. if (!res.ok) throw new Error(await responseError(res));
  6004. await loadFirewall(false);
  6005. } catch (err) {
  6006. showToast('Error', err.message, 'error');
  6007. }
  6008. }
  6009. async function toggleMangleRuleState(id, disabled) {
  6010. id = decodeURIComponent(id);
  6011. try {
  6012. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6013. method: 'POST',
  6014. headers: { 'Content-Type': 'application/json' },
  6015. body: JSON.stringify({ disabled })
  6016. });
  6017. if (!res.ok) throw new Error(await responseError(res));
  6018. await loadFirewall(false);
  6019. } catch (err) {
  6020. showToast('Error', err.message, 'error');
  6021. }
  6022. }
  6023. async function deleteMangleRule(id) {
  6024. id = decodeURIComponent(id);
  6025. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6026. try {
  6027. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6028. if (!res.ok) throw new Error(await responseError(res));
  6029. {
  6030. showToast('Deleted', 'Mangle rule removed', 'success');
  6031. loadFirewall(false);
  6032. }
  6033. } catch (err) {
  6034. showToast('Error', err.message, 'error');
  6035. }
  6036. }
  6037. // ----------------- Address Lists -----------------
  6038. function renderAddressLists() {
  6039. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6040. const tbody = document.getElementById('addrlist-table-body');
  6041. const empty = document.getElementById('addrlist-empty');
  6042. if (!tbody) return;
  6043. tbody.innerHTML = '';
  6044. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6045. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6046. // Update filter select
  6047. const sel = document.getElementById('addrlist-filter-name');
  6048. if (sel) {
  6049. const cur = sel.value;
  6050. sel.innerHTML = '<option value="">All Lists</option>';
  6051. const set = new Set((state.addressLists || []).map(a => a.name));
  6052. set.forEach(n => {
  6053. const opt = document.createElement('option');
  6054. opt.value = n;
  6055. opt.innerText = n;
  6056. if (n === cur) opt.selected = true;
  6057. sel.appendChild(opt);
  6058. });
  6059. }
  6060. if (entries.length === 0) {
  6061. empty?.classList.remove('hidden');
  6062. return;
  6063. }
  6064. empty?.classList.add('hidden');
  6065. entries.forEach((raw, idx) => {
  6066. const e = safeFirewallRow(raw);
  6067. const tr = document.createElement('tr');
  6068. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6069. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6070. tr.innerHTML = `
  6071. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6072. <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>
  6073. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6074. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6075. <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>
  6076. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6077. ${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>
  6078. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6079. `}
  6080. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6081. </td>
  6082. `;
  6083. tbody.appendChild(tr);
  6084. });
  6085. populateCommonAddrListDatalist();
  6086. }
  6087. function openAddAddrListModal() {
  6088. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6089. document.getElementById('addrlist-modal-id').value = '';
  6090. document.getElementById('addrlist-modal-name').value = '';
  6091. document.getElementById('addrlist-modal-addr').value = '';
  6092. document.getElementById('addrlist-modal-comment').value = '';
  6093. document.getElementById('addrlist-modal-disabled').checked = false;
  6094. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6095. if (submitBtn) submitBtn.innerText = 'Add to List';
  6096. document.getElementById('addrlist-modal').classList.remove('hidden');
  6097. }
  6098. function openEditAddrListModal(id) {
  6099. id = decodeURIComponent(id);
  6100. const e = (state.addressLists || []).find(item => item.id === id);
  6101. if (!e) return;
  6102. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6103. document.getElementById('addrlist-modal-id').value = e.id;
  6104. document.getElementById('addrlist-modal-name').value = e.name;
  6105. document.getElementById('addrlist-modal-addr').value = e.address;
  6106. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6107. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6108. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6109. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6110. document.getElementById('addrlist-modal').classList.remove('hidden');
  6111. }
  6112. function closeAddrListModal() {
  6113. document.getElementById('addrlist-modal').classList.add('hidden');
  6114. }
  6115. async function submitSaveAddrList(e) {
  6116. e.preventDefault();
  6117. const id = document.getElementById('addrlist-modal-id').value;
  6118. const name = document.getElementById('addrlist-modal-name').value.trim();
  6119. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6120. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6121. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6122. try {
  6123. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6124. method: 'POST',
  6125. headers: { 'Content-Type': 'application/json' },
  6126. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6127. });
  6128. if (res.ok) {
  6129. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6130. closeAddrListModal();
  6131. loadFirewall(false);
  6132. } else {
  6133. const err = await res.json();
  6134. showToast('Error', err.message || 'Failed to save address list', 'error');
  6135. }
  6136. } catch (err) {
  6137. showToast('Error', err.message, 'error');
  6138. }
  6139. }
  6140. async function toggleAddrListState(id, disabled) {
  6141. id = decodeURIComponent(id);
  6142. try {
  6143. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6144. method: 'POST',
  6145. headers: { 'Content-Type': 'application/json' },
  6146. body: JSON.stringify({ disabled })
  6147. });
  6148. if (res.ok) {
  6149. loadFirewall(false);
  6150. }
  6151. } catch (err) {
  6152. showToast('Error', err.message, 'error');
  6153. }
  6154. }
  6155. async function deleteAddrList(id) {
  6156. id = decodeURIComponent(id);
  6157. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6158. try {
  6159. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6160. if (res.ok) {
  6161. showToast('Deleted', 'Address list item removed', 'info');
  6162. loadFirewall(false);
  6163. }
  6164. } catch (err) {
  6165. showToast('Error', err.message, 'error');
  6166. }
  6167. }
  6168. // ----------------- Geo-Location IP Management -----------------
  6169. async function loadGeoIP() {
  6170. try {
  6171. const [statusRes, countriesRes] = await Promise.all([
  6172. fetch(`${API_BASE}/firewall/geoip/status`),
  6173. fetch(`${API_BASE}/firewall/geoip/countries`)
  6174. ]);
  6175. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6176. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6177. updateGeoHeader();
  6178. renderGeoCountries();
  6179. } catch (err) {
  6180. console.error('Failed to load GeoIP:', err);
  6181. }
  6182. }
  6183. function getGeoUsageMap() {
  6184. const usage = {};
  6185. const checkRule = (r, type) => {
  6186. ['src_geoip', 'dst_geoip'].forEach(field => {
  6187. let val = (r && r[field]) || '';
  6188. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6189. if (code) {
  6190. if (!usage[code]) usage[code] = [];
  6191. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6192. if (!usage[code].includes(label)) usage[code].push(label);
  6193. }
  6194. });
  6195. };
  6196. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6197. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6198. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6199. return usage;
  6200. }
  6201. function updateGeoHeader() {
  6202. const s = state.geoStatus || {};
  6203. const statusBadge = document.getElementById('geo-status-badge');
  6204. if (statusBadge) {
  6205. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6206. statusBadge.className = s.auto_update
  6207. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6208. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6209. }
  6210. const intervalLabel = document.getElementById('geo-interval-label');
  6211. if (intervalLabel) {
  6212. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6213. }
  6214. const usageMap = getGeoUsageMap();
  6215. const inUseCount = Object.keys(usageMap).length;
  6216. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6217. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6218. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6219. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6220. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6221. if (lastSyncEl) {
  6222. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6223. const d = new Date(s.last_updated);
  6224. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6225. } else {
  6226. lastSyncEl.innerText = 'Never (Sync Pending)';
  6227. }
  6228. }
  6229. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6230. if (nextSyncEl) {
  6231. if (s.next_update && !s.next_update.startsWith('0001')) {
  6232. const d = new Date(s.next_update);
  6233. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6234. } else {
  6235. nextSyncEl.innerText = '-';
  6236. }
  6237. }
  6238. const badge = document.getElementById('fw-badge-geo');
  6239. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6240. }
  6241. function renderGeoCountries() {
  6242. const tbody = document.getElementById('geo-table-body');
  6243. const empty = document.getElementById('geo-empty');
  6244. if (!tbody) return;
  6245. tbody.innerHTML = '';
  6246. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6247. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6248. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6249. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6250. const usageMap = getGeoUsageMap();
  6251. const countries = (state.geoCountries || []).filter(c => {
  6252. const isUsed = !!usageMap[c.code];
  6253. if (inUseOnly && !isUsed) return false;
  6254. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6255. if (continent && c.continent !== continent) return false;
  6256. if (q) {
  6257. const matchCode = c.code.toLowerCase().includes(q);
  6258. const matchName = c.name.toLowerCase().includes(q);
  6259. if (!matchCode && !matchName) return false;
  6260. }
  6261. return true;
  6262. });
  6263. if (countries.length === 0) {
  6264. empty?.classList.remove('hidden');
  6265. return;
  6266. }
  6267. empty?.classList.add('hidden');
  6268. countries.forEach(c => {
  6269. const tr = document.createElement('tr');
  6270. const isUsed = !!usageMap[c.code];
  6271. const rulesUsing = usageMap[c.code] || [];
  6272. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6273. let statusHtml = '';
  6274. if (isUsed) {
  6275. 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>`;
  6276. } else if (c.subnet_count > 0) {
  6277. 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>';
  6278. } else {
  6279. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6280. }
  6281. tr.innerHTML = `
  6282. <td class="py-2.5 px-3 text-center">
  6283. <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'}">
  6284. ${c.code}
  6285. </span>
  6286. </td>
  6287. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6288. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6289. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6290. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6291. </td>
  6292. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6293. <td class="py-2.5 px-3">
  6294. ${statusHtml}
  6295. </td>
  6296. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6297. <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>
  6298. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6299. </td>
  6300. `;
  6301. tbody.appendChild(tr);
  6302. });
  6303. }
  6304. function quickFilterGeo(preset) {
  6305. const searchInput = document.getElementById('geo-search-input');
  6306. const continentSel = document.getElementById('geo-continent-filter');
  6307. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6308. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6309. if (searchInput) searchInput.value = '';
  6310. if (continentSel) continentSel.value = '';
  6311. if (inUseCheck) inUseCheck.checked = false;
  6312. if (cachedCheck) cachedCheck.checked = false;
  6313. if (preset === 'GR') {
  6314. if (searchInput) searchInput.value = 'Greece';
  6315. } else if (preset === 'Europe') {
  6316. if (continentSel) continentSel.value = 'Europe';
  6317. } else if (preset === 'HIGHRISK') {
  6318. if (searchInput) searchInput.value = 'China';
  6319. }
  6320. renderGeoCountries();
  6321. }
  6322. async function toggleGeoCountry(code, enabled) {
  6323. try {
  6324. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6325. method: 'POST',
  6326. headers: { 'Content-Type': 'application/json' },
  6327. body: JSON.stringify({ enabled })
  6328. });
  6329. if (res.ok) {
  6330. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6331. loadGeoIP();
  6332. } else {
  6333. const err = await res.json();
  6334. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6335. }
  6336. } catch (err) {
  6337. showToast('Error', err.message, 'error');
  6338. }
  6339. }
  6340. async function updateGeoCountry(code) {
  6341. try {
  6342. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6343. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6344. if (res.ok) {
  6345. const data = await res.json();
  6346. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6347. loadGeoIP();
  6348. } else {
  6349. const err = await res.json();
  6350. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6351. }
  6352. } catch (err) {
  6353. showToast('Error', err.message, 'error');
  6354. }
  6355. }
  6356. async function triggerGeoUpdateNow() {
  6357. const spinner = document.getElementById('geo-update-spinner');
  6358. if (spinner) spinner.classList.remove('hidden');
  6359. try {
  6360. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6361. if (res.ok) {
  6362. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6363. setTimeout(() => {
  6364. loadGeoIP();
  6365. if (spinner) spinner.classList.add('hidden');
  6366. }, 2500);
  6367. } else {
  6368. const err = await res.json();
  6369. showToast('Notice', err.message || 'Update in progress', 'info');
  6370. if (spinner) spinner.classList.add('hidden');
  6371. }
  6372. } catch (err) {
  6373. showToast('Error', err.message, 'error');
  6374. if (spinner) spinner.classList.add('hidden');
  6375. }
  6376. }
  6377. async function applyGeoPreset(preset) {
  6378. try {
  6379. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6380. method: 'POST',
  6381. headers: { 'Content-Type': 'application/json' },
  6382. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6383. });
  6384. if (res.ok) {
  6385. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6386. loadGeoIP();
  6387. }
  6388. } catch (err) {
  6389. showToast('Error', err.message, 'error');
  6390. }
  6391. }
  6392. function openGeoIntervalModal() {
  6393. const s = state.geoStatus || {};
  6394. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6395. const sel = document.getElementById('geo-cfg-interval');
  6396. const customBox = document.getElementById('geo-cfg-custom-box');
  6397. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6398. const curHours = s.interval_hours || 24;
  6399. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6400. if (matchOption) {
  6401. sel.value = String(curHours);
  6402. customBox.classList.add('hidden');
  6403. } else {
  6404. sel.value = 'custom';
  6405. customHoursInput.value = curHours;
  6406. customBox.classList.remove('hidden');
  6407. }
  6408. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6409. }
  6410. function closeGeoIntervalModal() {
  6411. document.getElementById('geo-interval-modal').classList.add('hidden');
  6412. }
  6413. function toggleCustomGeoInterval() {
  6414. const val = document.getElementById('geo-cfg-interval').value;
  6415. const customBox = document.getElementById('geo-cfg-custom-box');
  6416. if (val === 'custom') {
  6417. customBox.classList.remove('hidden');
  6418. } else {
  6419. customBox.classList.add('hidden');
  6420. }
  6421. }
  6422. async function submitGeoIntervalSettings(e) {
  6423. e.preventDefault();
  6424. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6425. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6426. let hours = 24;
  6427. if (intervalVal === 'custom') {
  6428. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6429. } else {
  6430. hours = parseInt(intervalVal, 10) || 24;
  6431. }
  6432. try {
  6433. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6434. method: 'POST',
  6435. headers: { 'Content-Type': 'application/json' },
  6436. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6437. });
  6438. if (res.ok) {
  6439. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6440. closeGeoIntervalModal();
  6441. loadGeoIP();
  6442. } else {
  6443. const err = await res.json();
  6444. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6445. }
  6446. } catch (err) {
  6447. showToast('Error', err.message, 'error');
  6448. }
  6449. }
  6450. async function viewGeoSubnets(code, name) {
  6451. if (!name) {
  6452. const found = (state.geoCountries || []).find(x => x.code === code);
  6453. name = found ? found.name : code;
  6454. }
  6455. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6456. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6457. const listEl = document.getElementById('geo-subnets-list');
  6458. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6459. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6460. try {
  6461. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6462. if (res.ok) {
  6463. const data = await res.json();
  6464. const subnets = data.subnets || [];
  6465. if (subnets.length === 0) {
  6466. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6467. } else {
  6468. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6469. }
  6470. } else {
  6471. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6472. }
  6473. } catch (err) {
  6474. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6475. }
  6476. }
  6477. function closeGeoSubnetsModal() {
  6478. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6479. }
  6480. // ----------------- Active Connections Tracking -----------------
  6481. async function loadConnections() {
  6482. try {
  6483. const res = await fetch(`${API_BASE}/firewall/connections`);
  6484. const data = await res.json();
  6485. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6486. state.connections = Array.isArray(data) ? data : [];
  6487. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6488. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6489. renderConnections();
  6490. } catch (err) {
  6491. console.error('Failed to load connections:', err);
  6492. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6493. }
  6494. }
  6495. function renderConnections() {
  6496. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6497. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6498. const tbody = document.getElementById('conns-table-body');
  6499. const empty = document.getElementById('conns-empty');
  6500. if (!tbody) return;
  6501. tbody.innerHTML = '';
  6502. const conns = (state.connections || []).filter(c => {
  6503. if (protoFilter && c.protocol !== protoFilter) return false;
  6504. if (search) {
  6505. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6506. if (!line.includes(search)) return false;
  6507. }
  6508. return true;
  6509. });
  6510. if (conns.length === 0) {
  6511. empty?.classList.remove('hidden');
  6512. return;
  6513. }
  6514. empty?.classList.add('hidden');
  6515. conns.slice(0, 150).forEach(c => {
  6516. const tr = document.createElement('tr');
  6517. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6518. let stateColor = 'text-slate-400';
  6519. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6520. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6521. tr.innerHTML = `
  6522. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6523. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6524. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6525. <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>
  6526. <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>
  6527. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6528. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6529. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6530. <td class="py-2.5 px-3 text-right font-sans">
  6531. ${['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>` : ''}
  6532. </td>
  6533. `;
  6534. tbody.appendChild(tr);
  6535. });
  6536. }
  6537. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6538. try {
  6539. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6540. method: 'POST',
  6541. headers: { 'Content-Type': 'application/json' },
  6542. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6543. });
  6544. if (res.ok) {
  6545. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6546. loadConnections();
  6547. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6548. } catch (err) {
  6549. showToast('Error', err.message, 'error');
  6550. }
  6551. }
  6552. async function resetFirewallCounters() {
  6553. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6554. try {
  6555. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6556. if (res.ok) {
  6557. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6558. loadFirewall(false);
  6559. }
  6560. } catch (err) {
  6561. showToast('Error', err.message, 'error');
  6562. }
  6563. }
  6564. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6565. function switchRoutesSubTab(tab) {
  6566. state.routesSubTab = tab;
  6567. const tabs = ['routes', 'rules', 'tables'];
  6568. tabs.forEach(t => {
  6569. const panel = document.getElementById(`routes-subtab-${t}`);
  6570. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6571. if (panel) {
  6572. if (t === tab) panel.classList.remove('hidden');
  6573. else panel.classList.add('hidden');
  6574. }
  6575. if (btn) {
  6576. if (t === tab) {
  6577. 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';
  6578. } else {
  6579. 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';
  6580. }
  6581. }
  6582. });
  6583. setTimeout(initTableSorting, 50);
  6584. }
  6585. async function loadRoutes() {
  6586. try {
  6587. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6588. fetch(`${API_BASE}/routes`),
  6589. fetch(`${API_BASE}/routing/rules`),
  6590. fetch(`${API_BASE}/routing/tables`)
  6591. ]);
  6592. if (routesRes.ok) state.routes = await routesRes.json();
  6593. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6594. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6595. const bRoutes = document.getElementById('routes-badge-routes');
  6596. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6597. const showSystem = document.getElementById('prule-show-system')?.checked;
  6598. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6599. const bRules = document.getElementById('routes-badge-rules');
  6600. if (bRules) bRules.innerText = userRules.length;
  6601. const bTables = document.getElementById('routes-badge-tables');
  6602. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6603. const bRoutesCount = document.getElementById('badge-routes-count');
  6604. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6605. renderRoutesList();
  6606. renderPolicyRules();
  6607. renderRoutingTables();
  6608. } catch (err) {
  6609. console.error('Failed to load routing:', err);
  6610. }
  6611. }
  6612. function getRouteProtocolBadge(proto) {
  6613. const p = (proto || 'static').toLowerCase();
  6614. switch (p) {
  6615. case 'bgp':
  6616. 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>`;
  6617. case 'ibgp':
  6618. 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>`;
  6619. case 'ospf':
  6620. 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>`;
  6621. case 'rip':
  6622. 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>`;
  6623. case 'static':
  6624. 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>`;
  6625. case 'connected':
  6626. 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>`;
  6627. case 'dhcp':
  6628. 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>`;
  6629. case 'multicast':
  6630. 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>`;
  6631. default:
  6632. 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>`;
  6633. }
  6634. }
  6635. function renderRoutesList() {
  6636. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6637. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6638. const tbody = document.getElementById('routes-table-body');
  6639. const empty = document.getElementById('routes-empty');
  6640. if (!tbody) return;
  6641. // Update table filter select
  6642. const sel = document.getElementById('routes-filter-table');
  6643. if (sel) {
  6644. const cur = sel.value;
  6645. sel.innerHTML = '<option value="">All Tables</option>';
  6646. (state.routingTables || []).forEach(t => {
  6647. const opt = document.createElement('option');
  6648. opt.value = t.name;
  6649. opt.innerText = t.name;
  6650. if (t.name === cur) opt.selected = true;
  6651. sel.appendChild(opt);
  6652. });
  6653. }
  6654. const routes = (state.routes || []).filter(r => {
  6655. if (tableFilter && r.routing_table !== tableFilter) return false;
  6656. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6657. if (typeFilter === 'multicast' && !r.multicast) return false;
  6658. if (typeFilter === 'static' && !r.static) return false;
  6659. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6660. if (typeFilter === 'connected' && !r.connect) return false;
  6661. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6662. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6663. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6664. return true;
  6665. });
  6666. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6667. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6668. let summaryText = `${routes.length} Routes`;
  6669. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6670. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6671. const badgeEl = document.getElementById('routes-count-badge');
  6672. if (badgeEl) badgeEl.innerText = summaryText;
  6673. if (routes.length === 0) {
  6674. empty?.classList.remove('hidden');
  6675. tbody.innerHTML = '';
  6676. return;
  6677. }
  6678. empty?.classList.add('hidden');
  6679. 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(';');
  6680. if (tbody.dataset.sig === sig) {
  6681. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6682. }
  6683. tbody.dataset.sig = sig;
  6684. tbody.innerHTML = '';
  6685. routes.forEach(r => {
  6686. const tr = document.createElement('tr');
  6687. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6688. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6689. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6690. let flags = '';
  6691. if (r.dynamic) flags += 'D';
  6692. if (r.active) flags += 'A';
  6693. if (r.connect) flags += 'C';
  6694. if (r.static) flags += 'S';
  6695. if (r.ecmp) flags += 'E';
  6696. if (r.multicast) flags += 'M';
  6697. if (r.disabled) flags += 'X';
  6698. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6699. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6700. if (r.check_gateway === 'internet') {
  6701. if (r.health_status === 'online') {
  6702. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6703. healthCell = `
  6704. <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)">
  6705. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6706. <span>Internet OK (${ms}ms)</span>
  6707. </span>
  6708. `;
  6709. } else if (r.health_status === 'offline') {
  6710. healthCell = `
  6711. <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.">
  6712. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6713. <span>Internet Down</span>
  6714. </span>
  6715. `;
  6716. } else {
  6717. healthCell = `
  6718. <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">
  6719. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6720. <span>Checking...</span>
  6721. </span>
  6722. `;
  6723. }
  6724. } else if (r.check_gateway === 'ping') {
  6725. if (r.health_status === 'online') {
  6726. healthCell = `
  6727. <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">
  6728. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6729. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6730. </span>
  6731. `;
  6732. } else if (r.health_status === 'offline') {
  6733. healthCell = `
  6734. <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">
  6735. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6736. <span>Gateway Dead</span>
  6737. </span>
  6738. `;
  6739. }
  6740. }
  6741. const flagDescriptions = [];
  6742. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6743. if (r.active) flagDescriptions.push('Active (A)');
  6744. if (r.connect) flagDescriptions.push('Connected (C)');
  6745. if (r.static) flagDescriptions.push('Static (S)');
  6746. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6747. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6748. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6749. tr.innerHTML = `
  6750. <td class="py-2.5 px-3 text-center">
  6751. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6752. 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')
  6753. }" title="Flags: ${flagDescriptions.join(', ')}">
  6754. ${flags || '-'}
  6755. </span>
  6756. </td>
  6757. <td class="py-2.5 px-3">
  6758. <div class="flex items-center gap-1.5 flex-wrap">
  6759. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6760. ${r.ecmp ? `
  6761. <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)">
  6762. <span>⚡ ECMP</span>
  6763. </span>
  6764. ` : ''}
  6765. ${r.multicast ? `
  6766. <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">
  6767. <span>IGMP</span>
  6768. </span>
  6769. ` : ''}
  6770. </div>
  6771. </td>
  6772. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6773. <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>
  6774. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6775. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6776. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6777. <td class="py-2.5 px-3">${healthCell}</td>
  6778. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6779. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6780. ${r.static ? `
  6781. <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>
  6782. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6783. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6784. ` : `
  6785. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6786. `}
  6787. </td>
  6788. `;
  6789. tbody.appendChild(tr);
  6790. });
  6791. }
  6792. function openAddRouteModal() {
  6793. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6794. document.getElementById('route-modal-id').value = '';
  6795. document.getElementById('route-modal-old-dst').value = '';
  6796. document.getElementById('route-modal-old-gw').value = '';
  6797. document.getElementById('route-modal-old-distance').value = '';
  6798. document.getElementById('route-modal-old-table').value = '';
  6799. document.getElementById('route-modal-old-iface').value = '';
  6800. const dstInput = document.getElementById('route-modal-dst');
  6801. const gwInput = document.getElementById('route-modal-gw');
  6802. const distInput = document.getElementById('route-modal-distance');
  6803. const ifaceSelect = document.getElementById('route-modal-iface');
  6804. const tableSelect = document.getElementById('route-modal-table');
  6805. const commentInput = document.getElementById('route-modal-comment');
  6806. const disCheck = document.getElementById('route-modal-disabled');
  6807. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6808. dstInput.disabled = false;
  6809. dstInput.value = '0.0.0.0/0';
  6810. gwInput.disabled = false;
  6811. gwInput.value = '';
  6812. distInput.disabled = false;
  6813. distInput.value = '1';
  6814. ifaceSelect.disabled = false;
  6815. tableSelect.disabled = false;
  6816. commentInput.disabled = false;
  6817. commentInput.value = '';
  6818. disCheck.disabled = false;
  6819. disCheck.checked = false;
  6820. if (saveBtn) saveBtn.classList.remove('hidden');
  6821. const checkGw = document.getElementById('route-modal-check-gw');
  6822. if (checkGw) checkGw.value = 'internet';
  6823. const checkTarget = document.getElementById('route-modal-check-target');
  6824. if (checkTarget) checkTarget.value = '1.1.1.1';
  6825. const checkInterval = document.getElementById('route-modal-check-interval');
  6826. if (checkInterval) checkInterval.value = '5';
  6827. const checkThresh = document.getElementById('route-modal-check-threshold');
  6828. if (checkThresh) checkThresh.value = '3';
  6829. toggleRouteCheckModeUI();
  6830. populateInterfaceSelect('route-modal-iface');
  6831. // Populate tables
  6832. tableSelect.innerHTML = '';
  6833. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6834. const opt = document.createElement('option');
  6835. opt.value = t.name;
  6836. opt.innerText = t.name;
  6837. if (t.name === 'main') opt.selected = true;
  6838. tableSelect.appendChild(opt);
  6839. });
  6840. document.getElementById('route-modal').classList.remove('hidden');
  6841. }
  6842. function openEditRouteModal(id) {
  6843. const r = (state.routes || []).find(route => route.id === id);
  6844. if (!r) return;
  6845. const isStatic = !!r.static;
  6846. document.getElementById('route-modal-title').innerText = isStatic
  6847. ? `Edit Route: ${r.dst_address}`
  6848. : `Route Properties (Read Only): ${r.dst_address}`;
  6849. document.getElementById('route-modal-id').value = r.id;
  6850. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6851. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6852. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6853. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6854. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6855. const dstInput = document.getElementById('route-modal-dst');
  6856. const gwInput = document.getElementById('route-modal-gw');
  6857. const distInput = document.getElementById('route-modal-distance');
  6858. const ifaceSelect = document.getElementById('route-modal-iface');
  6859. const tableSelect = document.getElementById('route-modal-table');
  6860. const commentInput = document.getElementById('route-modal-comment');
  6861. const disCheck = document.getElementById('route-modal-disabled');
  6862. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6863. dstInput.value = r.dst_address;
  6864. gwInput.value = r.gateway || '';
  6865. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6866. commentInput.value = r.comment || '';
  6867. disCheck.checked = !!r.disabled;
  6868. const checkGw = document.getElementById('route-modal-check-gw');
  6869. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6870. const checkTarget = document.getElementById('route-modal-check-target');
  6871. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6872. const checkInterval = document.getElementById('route-modal-check-interval');
  6873. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6874. const checkThresh = document.getElementById('route-modal-check-threshold');
  6875. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6876. toggleRouteCheckModeUI();
  6877. dstInput.disabled = !isStatic;
  6878. gwInput.disabled = !isStatic;
  6879. distInput.disabled = !isStatic;
  6880. ifaceSelect.disabled = !isStatic;
  6881. tableSelect.disabled = !isStatic;
  6882. commentInput.disabled = !isStatic;
  6883. disCheck.disabled = !isStatic;
  6884. if (checkGw) checkGw.disabled = !isStatic;
  6885. if (checkTarget) checkTarget.disabled = !isStatic;
  6886. if (checkInterval) checkInterval.disabled = !isStatic;
  6887. if (checkThresh) checkThresh.disabled = !isStatic;
  6888. if (saveBtn) {
  6889. if (isStatic) {
  6890. saveBtn.classList.remove('hidden');
  6891. } else {
  6892. saveBtn.classList.add('hidden');
  6893. }
  6894. }
  6895. populateInterfaceSelect('route-modal-iface', r.interface);
  6896. tableSelect.innerHTML = '';
  6897. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6898. const opt = document.createElement('option');
  6899. opt.value = t.name;
  6900. opt.innerText = t.name;
  6901. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6902. tableSelect.appendChild(opt);
  6903. });
  6904. document.getElementById('route-modal').classList.remove('hidden');
  6905. }
  6906. function closeRouteModal() {
  6907. document.getElementById('route-modal').classList.add('hidden');
  6908. }
  6909. function setRouteCheckTarget(ip) {
  6910. const inp = document.getElementById('route-modal-check-target');
  6911. if (inp) inp.value = ip;
  6912. }
  6913. function toggleRouteCheckModeUI() {
  6914. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6915. const targetRow = document.getElementById('route-row-check-target');
  6916. const paramsRow = document.getElementById('route-row-check-params');
  6917. if (mode === 'none') {
  6918. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6919. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6920. } else if (mode === 'ping') {
  6921. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6922. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6923. } else { // internet
  6924. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6925. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6926. }
  6927. }
  6928. async function submitSaveRoute(e) {
  6929. e.preventDefault();
  6930. const id = document.getElementById('route-modal-id').value;
  6931. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6932. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6933. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6934. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6935. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6936. const dst = document.getElementById('route-modal-dst').value.trim();
  6937. const gw = document.getElementById('route-modal-gw').value.trim();
  6938. const table = document.getElementById('route-modal-table').value;
  6939. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6940. const iface = document.getElementById('route-modal-iface').value;
  6941. const comment = document.getElementById('route-modal-comment').value.trim();
  6942. const disabled = document.getElementById('route-modal-disabled').checked;
  6943. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6944. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6945. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6946. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6947. if (!dst) {
  6948. showToast('Error', 'Destination address is required', 'error');
  6949. return;
  6950. }
  6951. if (!gw && !iface) {
  6952. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6953. return;
  6954. }
  6955. const payload = {
  6956. id,
  6957. old_dst_address: oldDst,
  6958. old_gateway: oldGw,
  6959. old_routing_table: oldTable,
  6960. old_interface: oldIface,
  6961. dst_address: dst,
  6962. gateway: gw || iface,
  6963. routing_table: table,
  6964. distance,
  6965. interface: iface,
  6966. comment,
  6967. disabled,
  6968. check_gateway,
  6969. check_target,
  6970. check_interval,
  6971. check_threshold
  6972. };
  6973. if (oldDistStr !== undefined && oldDistStr !== '') {
  6974. payload.old_distance = parseInt(oldDistStr, 10);
  6975. }
  6976. try {
  6977. const res = await fetch(`${API_BASE}/routes`, {
  6978. method: 'POST',
  6979. headers: { 'Content-Type': 'application/json' },
  6980. body: JSON.stringify(payload)
  6981. });
  6982. if (res.ok) {
  6983. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6984. closeRouteModal();
  6985. loadRoutes();
  6986. } else {
  6987. const err = await res.json();
  6988. showToast('Error', err.message || 'Failed to save route', 'error');
  6989. }
  6990. } catch (err) {
  6991. showToast('Error', err.message, 'error');
  6992. }
  6993. }
  6994. async function toggleRouteState(id, disabled) {
  6995. try {
  6996. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6997. method: 'POST',
  6998. headers: { 'Content-Type': 'application/json' },
  6999. body: JSON.stringify({ disabled })
  7000. });
  7001. if (res.ok) loadRoutes();
  7002. } catch (err) {
  7003. showToast('Error', err.message, 'error');
  7004. }
  7005. }
  7006. async function deleteRoute(id) {
  7007. if (!confirm('Are you sure you want to delete this route?')) return;
  7008. try {
  7009. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7010. if (res.ok) {
  7011. showToast('Deleted', 'Route removed', 'success');
  7012. loadRoutes();
  7013. }
  7014. } catch (err) {
  7015. showToast('Error', err.message, 'error');
  7016. }
  7017. }
  7018. // ----------------- Policy Rules (/ip route rule) -----------------
  7019. function renderPolicyRules() {
  7020. const tbody = document.getElementById('rules-table-body');
  7021. const empty = document.getElementById('rules-empty');
  7022. if (!tbody) return;
  7023. const showSystem = document.getElementById('prule-show-system')?.checked;
  7024. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7025. const countBadge = document.getElementById('rules-count-badge');
  7026. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7027. const bRules = document.getElementById('routes-badge-rules');
  7028. if (bRules) bRules.innerText = filtered.length;
  7029. if (filtered.length === 0) {
  7030. empty?.classList.remove('hidden');
  7031. tbody.innerHTML = '';
  7032. return;
  7033. }
  7034. empty?.classList.add('hidden');
  7035. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7036. if (tbody.dataset.sig === sig) return;
  7037. tbody.dataset.sig = sig;
  7038. tbody.innerHTML = '';
  7039. filtered.forEach(pr => {
  7040. const isSys = pr.is_default || pr.is_system;
  7041. const tr = document.createElement('tr');
  7042. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7043. tr.innerHTML = `
  7044. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7045. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7046. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7047. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7048. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7049. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7050. <td class="py-2.5 px-3 text-right font-sans">
  7051. ${!pr.is_default ? `
  7052. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7053. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7054. </td>
  7055. `;
  7056. tbody.appendChild(tr);
  7057. });
  7058. }
  7059. function openAddPolicyRuleModal() {
  7060. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7061. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7062. document.getElementById('prule-modal-mark').value = '';
  7063. document.getElementById('prule-modal-src').value = '';
  7064. document.getElementById('prule-modal-dst').value = '';
  7065. const sel = document.getElementById('prule-modal-table');
  7066. sel.innerHTML = '';
  7067. (state.routingTables || []).forEach(t => {
  7068. const opt = document.createElement('option');
  7069. opt.value = t.name;
  7070. opt.innerText = t.name;
  7071. sel.appendChild(opt);
  7072. });
  7073. document.getElementById('prule-modal').classList.remove('hidden');
  7074. }
  7075. function closePolicyRuleModal() {
  7076. document.getElementById('prule-modal').classList.add('hidden');
  7077. }
  7078. async function submitSavePolicyRule(e) {
  7079. e.preventDefault();
  7080. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7081. const mark = document.getElementById('prule-modal-mark').value.trim();
  7082. const src = document.getElementById('prule-modal-src').value.trim();
  7083. const dst = document.getElementById('prule-modal-dst').value.trim();
  7084. const table = document.getElementById('prule-modal-table').value;
  7085. const action = document.getElementById('prule-modal-action').value;
  7086. try {
  7087. const res = await fetch(`${API_BASE}/routing/rules`, {
  7088. method: 'POST',
  7089. headers: { 'Content-Type': 'application/json' },
  7090. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7091. });
  7092. if (res.ok) {
  7093. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7094. closePolicyRuleModal();
  7095. loadRoutes();
  7096. } else {
  7097. const err = await res.json();
  7098. showToast('Error', err.message, 'error');
  7099. }
  7100. } catch (err) {
  7101. showToast('Error', err.message, 'error');
  7102. }
  7103. }
  7104. async function deletePolicyRule(id) {
  7105. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7106. try {
  7107. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7108. if (res.ok) {
  7109. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7110. loadRoutes();
  7111. }
  7112. } catch (err) {
  7113. showToast('Error', err.message, 'error');
  7114. }
  7115. }
  7116. // ----------------- Routing Tables -----------------
  7117. function renderRoutingTables() {
  7118. const tbody = document.getElementById('tables-table-body');
  7119. if (!tbody) return;
  7120. const tables = state.routingTables || [];
  7121. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7122. if (tbody.dataset.sig === sig) return;
  7123. tbody.dataset.sig = sig;
  7124. tbody.innerHTML = '';
  7125. (state.routingTables || []).forEach(t => {
  7126. const tr = document.createElement('tr');
  7127. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7128. tr.innerHTML = `
  7129. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7130. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7131. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7132. `;
  7133. tbody.appendChild(tr);
  7134. });
  7135. }
  7136. function openAddTableModal() {
  7137. document.getElementById('table-modal-name').value = '';
  7138. document.getElementById('table-modal-id').value = '';
  7139. document.getElementById('table-modal-comment').value = '';
  7140. document.getElementById('table-modal').classList.remove('hidden');
  7141. }
  7142. function closeTableModal() {
  7143. document.getElementById('table-modal').classList.add('hidden');
  7144. }
  7145. async function submitSaveTable(e) {
  7146. e.preventDefault();
  7147. const name = document.getElementById('table-modal-name').value.trim();
  7148. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7149. const comment = document.getElementById('table-modal-comment').value.trim();
  7150. try {
  7151. const res = await fetch(`${API_BASE}/routing/tables`, {
  7152. method: 'POST',
  7153. headers: { 'Content-Type': 'application/json' },
  7154. body: JSON.stringify({ name, table_id: id, comment })
  7155. });
  7156. if (res.ok) {
  7157. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7158. closeTableModal();
  7159. loadRoutes();
  7160. } else {
  7161. const err = await res.json();
  7162. showToast('Error', err.message, 'error');
  7163. }
  7164. } catch (err) {
  7165. showToast('Error', err.message, 'error');
  7166. }
  7167. }
  7168. async function loadDebianConfig() {
  7169. const view = document.getElementById('debian-config-view');
  7170. view.innerText = 'Generating live configuration...';
  7171. try {
  7172. const res = await fetch(`${API_BASE}/debian/config`);
  7173. const data = await res.json();
  7174. view.innerText = data.content || '# Empty config';
  7175. } catch (err) {
  7176. view.innerText = 'Failed to generate Debian network config.';
  7177. }
  7178. }
  7179. async function saveDebianConfig() {
  7180. try {
  7181. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7182. const data = await res.json();
  7183. if (res.ok) {
  7184. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7185. loadDebianConfig();
  7186. }
  7187. } catch (err) {
  7188. showToast('Error', err.message, 'error');
  7189. }
  7190. }
  7191. function showToast(title, message, type = 'info') {
  7192. const container = document.getElementById('toast-container');
  7193. const toast = document.createElement('div');
  7194. const borderColors = {
  7195. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7196. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7197. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7198. };
  7199. 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}`;
  7200. toast.innerHTML = `
  7201. <div class="flex-1">
  7202. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7203. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7204. </div>
  7205. `;
  7206. container.appendChild(toast);
  7207. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7208. setTimeout(() => {
  7209. toast.classList.add('opacity-0', 'translate-y-2');
  7210. setTimeout(() => toast.remove(), 300);
  7211. }, 4000);
  7212. }
  7213. function formatTraffic(bytesPerSec) {
  7214. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7215. const kb = bytesPerSec / 1024;
  7216. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7217. const mb = kb / 1024;
  7218. return `${mb.toFixed(2)} MB/s`;
  7219. }
  7220. function toggleSidebar() {
  7221. const sb = document.getElementById('sidebar');
  7222. sb.classList.toggle('-translate-x-full');
  7223. }
  7224. // ======================== EoIP (Ethernet over IP) ========================
  7225. async function loadEoIP(populate = true) {
  7226. try {
  7227. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7228. const data = await res.json();
  7229. state.eoipTunnels = Array.isArray(data) ? data : [];
  7230. const badge = document.getElementById('eoip-count-badge');
  7231. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7232. const sideBadge = document.getElementById('badge-eoip-count');
  7233. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7234. renderEoIPTunnels();
  7235. } catch (err) {
  7236. console.error('Failed to load EoIP:', err);
  7237. }
  7238. }
  7239. function renderEoIPTunnels() {
  7240. const tbody = document.getElementById('eoip-table-body');
  7241. const empty = document.getElementById('eoip-empty');
  7242. if (!tbody) return;
  7243. tbody.innerHTML = '';
  7244. const tunnels = state.eoipTunnels || [];
  7245. if (tunnels.length === 0) {
  7246. empty?.classList.remove('hidden');
  7247. return;
  7248. }
  7249. empty?.classList.add('hidden');
  7250. tunnels.forEach(t => {
  7251. const tr = document.createElement('tr');
  7252. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7253. tr.innerHTML = `
  7254. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7255. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7256. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7257. <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>
  7258. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7259. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7260. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7261. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7262. <td class="py-2.5 px-3 font-mono text-[11px]">
  7263. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7264. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7265. </td>
  7266. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7267. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7268. <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>
  7269. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7270. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7271. </td>
  7272. `;
  7273. tbody.appendChild(tr);
  7274. });
  7275. }
  7276. function openAddEoIPModal() {
  7277. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7278. document.getElementById('eoip-modal-id').value = '';
  7279. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7280. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7281. document.getElementById('eoip-modal-remote').value = '';
  7282. document.getElementById('eoip-modal-ip').value = '';
  7283. document.getElementById('eoip-modal-local').value = '';
  7284. document.getElementById('eoip-modal-mac').value = '';
  7285. document.getElementById('eoip-modal-mtu').value = '1500';
  7286. document.getElementById('eoip-modal-comment').value = '';
  7287. document.getElementById('eoip-modal-clampmss').checked = true;
  7288. document.getElementById('eoip-modal-disabled').checked = false;
  7289. document.getElementById('eoip-modal').classList.remove('hidden');
  7290. }
  7291. function openEditEoIPModal(id) {
  7292. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7293. if (!t) return;
  7294. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7295. document.getElementById('eoip-modal-id').value = t.id;
  7296. document.getElementById('eoip-modal-name').value = t.name;
  7297. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7298. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7299. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7300. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7301. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7302. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7303. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7304. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7305. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7306. document.getElementById('eoip-modal').classList.remove('hidden');
  7307. }
  7308. function closeEoIPModal() {
  7309. document.getElementById('eoip-modal').classList.add('hidden');
  7310. }
  7311. async function submitSaveEoIP(e) {
  7312. e.preventDefault();
  7313. const id = document.getElementById('eoip-modal-id').value;
  7314. const name = document.getElementById('eoip-modal-name').value.trim();
  7315. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7316. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7317. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7318. const local = document.getElementById('eoip-modal-local').value.trim();
  7319. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7320. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7321. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7322. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7323. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7324. try {
  7325. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7326. method: 'POST',
  7327. headers: { 'Content-Type': 'application/json' },
  7328. body: JSON.stringify({
  7329. id,
  7330. name,
  7331. tunnel_id: tunnelId,
  7332. remote_address: remote,
  7333. ip_address: ipAddress,
  7334. local_address: local,
  7335. mac_address: mac,
  7336. mtu,
  7337. clamp_mss: clampMss,
  7338. comment,
  7339. disabled
  7340. })
  7341. });
  7342. if (res.ok) {
  7343. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7344. closeEoIPModal();
  7345. loadEoIP(false);
  7346. fetchData(false);
  7347. } else {
  7348. const err = await res.json();
  7349. showToast('Error', err.message, 'error');
  7350. }
  7351. } catch (err) {
  7352. showToast('Error', err.message, 'error');
  7353. }
  7354. }
  7355. async function toggleEoIPState(id, disabled) {
  7356. try {
  7357. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7358. method: 'POST',
  7359. headers: { 'Content-Type': 'application/json' },
  7360. body: JSON.stringify({ disabled })
  7361. });
  7362. if (res.ok) {
  7363. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7364. loadEoIP(false);
  7365. fetchData(false);
  7366. }
  7367. } catch (err) {
  7368. showToast('Error', err.message, 'error');
  7369. }
  7370. }
  7371. async function deleteEoIP(id) {
  7372. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7373. try {
  7374. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7375. if (res.ok) {
  7376. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7377. loadEoIP(false);
  7378. fetchData(false);
  7379. }
  7380. } catch (err) {
  7381. showToast('Error', err.message, 'error');
  7382. }
  7383. }
  7384. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7385. async function loadVXLAN(populate = true) {
  7386. try {
  7387. const [tunnelsRes, vtepsRes] = await Promise.all([
  7388. fetch(`${API_BASE}/vpn/vxlan`),
  7389. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7390. ]);
  7391. if (tunnelsRes.ok) {
  7392. state.vxlanTunnels = await tunnelsRes.json() || [];
  7393. }
  7394. if (vtepsRes.ok) {
  7395. state.vxlanVteps = await vtepsRes.json() || [];
  7396. }
  7397. renderVXLANTable();
  7398. renderVXLANVtepsTable();
  7399. const countBadge = document.getElementById('vxlan-count-badge');
  7400. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7401. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7402. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7403. const navBadge = document.getElementById('badge-vxlan-count');
  7404. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7405. } catch (err) {
  7406. console.error('Error loading VXLAN:', err);
  7407. }
  7408. }
  7409. function renderVXLANTable() {
  7410. const tbody = document.getElementById('vxlan-table-body');
  7411. const empty = document.getElementById('vxlan-empty');
  7412. if (!tbody || !empty) return;
  7413. tbody.innerHTML = '';
  7414. const tunnels = state.vxlanTunnels || [];
  7415. if (tunnels.length === 0) {
  7416. empty.classList.remove('hidden');
  7417. return;
  7418. }
  7419. empty.classList.add('hidden');
  7420. tunnels.forEach(t => {
  7421. const tr = document.createElement('tr');
  7422. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7423. let flag = '';
  7424. if (t.disabled) {
  7425. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
  7426. } else if (t.running) {
  7427. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
  7428. } else {
  7429. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
  7430. }
  7431. const vtepCount = (t.vteps || []).length;
  7432. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7433. tr.innerHTML = `
  7434. <td class="py-2.5 px-3 text-center">${flag}</td>
  7435. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7436. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7437. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7438. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7439. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7440. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7441. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7442. <td class="py-2.5 px-3 font-mono">
  7443. <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
  7444. </td>
  7445. <td class="py-2.5 px-3 font-mono text-[11px]">
  7446. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7447. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7448. </td>
  7449. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7450. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7451. <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7452. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7453. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7454. </td>
  7455. `;
  7456. tbody.appendChild(tr);
  7457. });
  7458. }
  7459. function renderVXLANVtepsTable() {
  7460. const tbody = document.getElementById('vxlan-vteps-table-body');
  7461. const empty = document.getElementById('vxlan-vteps-empty');
  7462. if (!tbody || !empty) return;
  7463. tbody.innerHTML = '';
  7464. const vteps = state.vxlanVteps || [];
  7465. if (vteps.length === 0) {
  7466. empty.classList.remove('hidden');
  7467. return;
  7468. }
  7469. empty.classList.add('hidden');
  7470. vteps.forEach(v => {
  7471. const tr = document.createElement('tr');
  7472. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7473. tr.innerHTML = `
  7474. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7475. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7476. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7477. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7478. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7479. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7480. </td>
  7481. `;
  7482. tbody.appendChild(tr);
  7483. });
  7484. }
  7485. function openAddVXLANModal() {
  7486. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7487. document.getElementById('vxlan-modal-id').value = '';
  7488. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7489. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7490. document.getElementById('vxlan-modal-port').value = '4789';
  7491. document.getElementById('vxlan-modal-ip').value = '';
  7492. document.getElementById('vxlan-modal-parent').value = '';
  7493. document.getElementById('vxlan-modal-local').value = '';
  7494. document.getElementById('vxlan-modal-remote').value = '';
  7495. document.getElementById('vxlan-modal-group').value = '';
  7496. document.getElementById('vxlan-modal-mac').value = '';
  7497. document.getElementById('vxlan-modal-mtu').value = '1500';
  7498. document.getElementById('vxlan-modal-comment').value = '';
  7499. document.getElementById('vxlan-modal-learning').checked = true;
  7500. document.getElementById('vxlan-modal-disabled').checked = false;
  7501. document.getElementById('vxlan-modal').classList.remove('hidden');
  7502. }
  7503. function openEditVXLANModal(id) {
  7504. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7505. if (!t) return;
  7506. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7507. document.getElementById('vxlan-modal-id').value = t.id;
  7508. document.getElementById('vxlan-modal-name').value = t.name;
  7509. document.getElementById('vxlan-modal-vni').value = t.vni;
  7510. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7511. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7512. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7513. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7514. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7515. document.getElementById('vxlan-modal-group').value = t.group || '';
  7516. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7517. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7518. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7519. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7520. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7521. document.getElementById('vxlan-modal').classList.remove('hidden');
  7522. }
  7523. function closeVXLANModal() {
  7524. document.getElementById('vxlan-modal').classList.add('hidden');
  7525. }
  7526. async function submitSaveVXLAN(e) {
  7527. e.preventDefault();
  7528. const id = document.getElementById('vxlan-modal-id').value;
  7529. const name = document.getElementById('vxlan-modal-name').value.trim();
  7530. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7531. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7532. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7533. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7534. const local = document.getElementById('vxlan-modal-local').value.trim();
  7535. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7536. const group = document.getElementById('vxlan-modal-group').value.trim();
  7537. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7538. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7539. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7540. const learning = document.getElementById('vxlan-modal-learning').checked;
  7541. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7542. try {
  7543. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7544. method: 'POST',
  7545. headers: { 'Content-Type': 'application/json' },
  7546. body: JSON.stringify({
  7547. id,
  7548. name,
  7549. vni,
  7550. port,
  7551. ip_address: ipAddress,
  7552. parent_interface: parentInterface,
  7553. local_address: local,
  7554. remote_address: remote,
  7555. group,
  7556. mac_address: mac,
  7557. mtu,
  7558. learning,
  7559. comment,
  7560. disabled
  7561. })
  7562. });
  7563. if (res.ok) {
  7564. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7565. closeVXLANModal();
  7566. loadVXLAN(false);
  7567. fetchData(false);
  7568. } else {
  7569. const err = await res.json();
  7570. showToast('Error', err.message, 'error');
  7571. }
  7572. } catch (err) {
  7573. showToast('Error', err.message, 'error');
  7574. }
  7575. }
  7576. async function toggleVXLANState(id, disabled) {
  7577. try {
  7578. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7579. method: 'POST',
  7580. headers: { 'Content-Type': 'application/json' },
  7581. body: JSON.stringify({ disabled })
  7582. });
  7583. if (res.ok) {
  7584. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7585. loadVXLAN(false);
  7586. fetchData(false);
  7587. }
  7588. } catch (err) {
  7589. showToast('Error', err.message, 'error');
  7590. }
  7591. }
  7592. async function deleteVXLAN(id) {
  7593. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7594. try {
  7595. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7596. if (res.ok) {
  7597. showToast('Deleted', 'VXLAN interface removed', 'success');
  7598. loadVXLAN(false);
  7599. fetchData(false);
  7600. }
  7601. } catch (err) {
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. }
  7605. function openAddVXLANVtepModal(defaultIface = '') {
  7606. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7607. if (sel) {
  7608. sel.innerHTML = '';
  7609. const tunnels = state.vxlanTunnels || [];
  7610. tunnels.forEach(t => {
  7611. const opt = document.createElement('option');
  7612. opt.value = t.name;
  7613. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7614. if (defaultIface && t.name === defaultIface) {
  7615. opt.selected = true;
  7616. }
  7617. sel.appendChild(opt);
  7618. });
  7619. }
  7620. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7621. document.getElementById('vxlan-vtep-modal-port').value = '';
  7622. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7623. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7624. }
  7625. function closeVXLANVtepModal() {
  7626. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7627. }
  7628. async function submitSaveVXLANVtep(e) {
  7629. e.preventDefault();
  7630. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7631. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7632. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7633. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7634. try {
  7635. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7636. method: 'POST',
  7637. headers: { 'Content-Type': 'application/json' },
  7638. body: JSON.stringify({
  7639. interface: iface,
  7640. remote_ip: remote,
  7641. port,
  7642. comment
  7643. })
  7644. });
  7645. if (res.ok) {
  7646. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7647. closeVXLANVtepModal();
  7648. loadVXLAN(false);
  7649. fetchData(false);
  7650. } else {
  7651. const err = await res.json();
  7652. showToast('Error', err.message, 'error');
  7653. }
  7654. } catch (err) {
  7655. showToast('Error', err.message, 'error');
  7656. }
  7657. }
  7658. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7659. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7660. try {
  7661. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7662. method: 'DELETE'
  7663. });
  7664. if (res.ok) {
  7665. showToast('Deleted', 'Remote VTEP removed', 'success');
  7666. loadVXLAN(false);
  7667. fetchData(false);
  7668. }
  7669. } catch (err) {
  7670. showToast('Error', err.message, 'error');
  7671. }
  7672. }
  7673. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7674. const aeroRateSamples = new Map();
  7675. const aeroLiveRates = new Map();
  7676. async function loadAeroTUN(populate = true) {
  7677. try {
  7678. const [tunnelsRes, statsRes] = await Promise.all([
  7679. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7680. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7681. ]);
  7682. if (tunnelsRes.ok) {
  7683. const data = await tunnelsRes.json();
  7684. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7685. const now = Date.now();
  7686. for (const t of state.aerotunTunnels) {
  7687. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7688. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7689. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7690. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7691. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7692. }
  7693. }
  7694. if (statsRes.ok) {
  7695. state.aerotunStats = await statsRes.json();
  7696. }
  7697. const countBadge = document.getElementById('aerotun-count-badge');
  7698. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7699. const sideBadge = document.getElementById('badge-aerotun-count');
  7700. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7701. renderAeroTUN();
  7702. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7703. } catch (err) {
  7704. console.error('Failed to load AeroTUN:', err);
  7705. }
  7706. }
  7707. function renderAeroTUN() {
  7708. const tbody = document.getElementById('aerotun-table-body');
  7709. const empty = document.getElementById('aerotun-empty');
  7710. // Update summary cards
  7711. const stats = state.aerotunStats || {};
  7712. const tunnels = state.aerotunTunnels || [];
  7713. const statActive = document.getElementById('aerotun-stat-active');
  7714. if (statActive) {
  7715. const activeCount = tunnels.filter(t => t.connected).length;
  7716. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7717. }
  7718. const statSaved = document.getElementById('aerotun-stat-saved');
  7719. if (statSaved) {
  7720. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7721. }
  7722. const statRatio = document.getElementById('aerotun-stat-ratio');
  7723. if (statRatio) {
  7724. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7725. }
  7726. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7727. if (statTraffic) {
  7728. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7729. }
  7730. if (!tbody) return;
  7731. tbody.innerHTML = '';
  7732. if (tunnels.length === 0) {
  7733. empty?.classList.remove('hidden');
  7734. return;
  7735. }
  7736. empty?.classList.add('hidden');
  7737. tunnels.forEach(t => {
  7738. const tr = document.createElement('tr');
  7739. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7740. const modeBadge = t.mode === 'server'
  7741. ? `<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>`
  7742. : `<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>`;
  7743. const endpointInfo = t.mode === 'server'
  7744. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7745. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7746. const compBadge = t.compression
  7747. ? `<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>`
  7748. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7749. const activePeer = t.connected && t.active_peer_endpoint
  7750. ? `<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>`
  7751. : `<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>`;
  7752. const rawRx = formatBytes(t.rx_bytes || 0);
  7753. const rawTx = formatBytes(t.tx_bytes || 0);
  7754. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7755. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7756. const rate = aeroLiveRates.get(t.id);
  7757. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7758. tr.innerHTML = `
  7759. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7760. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7761. <span>${escapeHtml(t.name)}</span>
  7762. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7763. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7764. </td>
  7765. <td class="py-2.5 px-3">${modeBadge}</td>
  7766. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7767. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7768. <td class="py-2.5 px-3">${compBadge}</td>
  7769. <td class="py-2.5 px-3">${activePeer}</td>
  7770. <td class="py-2.5 px-3 font-mono text-[11px]">
  7771. <span class="text-emerald-400">↓ ${rawRx}</span>
  7772. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7773. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7774. </td>
  7775. <td class="py-2.5 px-3 font-mono text-[11px]">
  7776. <span class="text-slate-400">↓ ${wireRx}</span>
  7777. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7778. </td>
  7779. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7780. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7781. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7782. ${t.running
  7783. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7784. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7785. }
  7786. <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>
  7787. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7788. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7789. </td>
  7790. `;
  7791. tbody.appendChild(tr);
  7792. });
  7793. }
  7794. async function openAeroTUNHealth(encodedID) {
  7795. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7796. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7797. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7798. document.getElementById('aerotun-compare-host').value=underlay;
  7799. document.getElementById('aerotun-compare-result').textContent='';
  7800. document.getElementById('aerotun-health-result').textContent = '';
  7801. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7802. await refreshAeroTUNHealth();
  7803. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7804. }
  7805. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7806. async function refreshAeroTUNHealth() {
  7807. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7808. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7809. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7810. try {
  7811. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7812. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7813. const d=t.drop_breakdown;
  7814. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7815. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7816. if(!events.length){node.textContent='No events recorded yet.';return}
  7817. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7818. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7819. }
  7820. async function runAeroTUNHealthCheck() {
  7821. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7822. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7823. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7824. finally {button.disabled=false}
  7825. }
  7826. let aeroCompareRunning=false, aeroCompareCancel=false;
  7827. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7828. async function runAeroTUNComparison() {
  7829. if(aeroCompareRunning)return;
  7830. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7831. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7832. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7833. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7834. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7835. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7836. const results=[];
  7837. try {
  7838. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7839. if(aeroCompareCancel)break;
  7840. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7841. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7842. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7843. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7844. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7845. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7846. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7847. }
  7848. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7849. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7850. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7851. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7852. }
  7853. let aeroModalGeneration = 0;
  7854. let aeroIdentityDraft = '';
  7855. let aeroSaving = false;
  7856. let aeroPSKRequest = 0;
  7857. function discardAeroIdentityDraft(id) {
  7858. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7859. }
  7860. async function generateAeroTUNIdentity() {
  7861. const generation = aeroModalGeneration;
  7862. const retry = document.getElementById('aerotun-retry-identity');
  7863. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7864. retry.classList.add('hidden');
  7865. document.getElementById('aerotun-modal-public').value = '';
  7866. try {
  7867. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7868. if (!res.ok) throw new Error(await responseError(res));
  7869. const draft = await res.json();
  7870. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7871. aeroIdentityDraft = draft.draft_id;
  7872. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7873. updateAeroTUNSetupHint();
  7874. } catch (err) {
  7875. if (generation !== aeroModalGeneration) return;
  7876. retry.classList.remove('hidden');
  7877. updateAeroTUNSetupHint();
  7878. showToast('Identity Generation Failed', err.message, 'error');
  7879. }
  7880. }
  7881. function onAeroTUNModeChange() {
  7882. const mode = document.getElementById('aerotun-modal-mode').value;
  7883. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7884. const portInput = document.getElementById('aerotun-modal-port');
  7885. if (mode === 'server') {
  7886. if (!portInput.value) portInput.value = '51830';
  7887. endpointInput.placeholder = 'Optional / learned roaming peer';
  7888. } else {
  7889. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7890. if (!portInput.value) portInput.value = '';
  7891. }
  7892. }
  7893. function onAeroTUNPeerChange() {
  7894. const peer = document.getElementById('aerotun-modal-peer');
  7895. const allowed = document.getElementById('aerotun-modal-allowed');
  7896. const previous = peer.dataset.allowedDefault || '';
  7897. const host = peer.value.trim().split('/')[0];
  7898. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7899. if (allowed.value.trim() === previous) allowed.value = next;
  7900. peer.dataset.allowedDefault = next;
  7901. }
  7902. async function generateAeroTUNKey(automatic = false) {
  7903. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7904. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7905. try {
  7906. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7907. if (!res.ok) throw new Error(await responseError(res));
  7908. const data = await res.json();
  7909. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7910. input.value = data.key;
  7911. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7912. } catch (err) {
  7913. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7914. }
  7915. }
  7916. function updateAeroTUNSetupHint() {
  7917. const version = document.getElementById('aerotun-modal-protocol').value;
  7918. const key = document.getElementById('aerotun-modal-public').value;
  7919. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7920. const hint = document.getElementById('aerotun-setup-hint');
  7921. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7922. if (!hint) return;
  7923. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7924. }
  7925. async function copyAeroTUNPublicKey() {
  7926. const input = document.getElementById('aerotun-modal-public');
  7927. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7928. try {
  7929. await navigator.clipboard.writeText(input.value);
  7930. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7931. } catch {
  7932. input.focus(); input.select();
  7933. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7934. }
  7935. }
  7936. async function copyAeroTUNPSK() {
  7937. const input = document.getElementById('aerotun-modal-psk');
  7938. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7939. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7940. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7941. }
  7942. function openAddAeroTUNModal() {
  7943. if (aeroSaving) return;
  7944. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7945. const tunnels = state.aerotunTunnels || [];
  7946. const usedNames = new Set(tunnels.map(t => t.name));
  7947. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7948. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  7949. if (index >= 256) index = 0;
  7950. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7951. document.getElementById('aerotun-modal-id').value = '';
  7952. document.getElementById('aerotun-modal-protocol').value='3';
  7953. document.getElementById('aerotun-modal-public').value='';
  7954. document.getElementById('aerotun-modal-peerkey').value='';
  7955. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7956. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7957. document.getElementById('aerotun-modal-mode').value = 'server';
  7958. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7959. document.getElementById('aerotun-modal-endpoint').value = '';
  7960. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7961. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7962. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7963. document.getElementById('aerotun-modal-psk').value = '';
  7964. document.getElementById('aerotun-modal-mtu').value = '1420';
  7965. document.getElementById('aerotun-modal-comment').value = '';
  7966. document.getElementById('aerotun-modal-compression').checked = false;
  7967. document.getElementById('aerotun-modal-defroute').checked = false;
  7968. document.getElementById('aerotun-modal-disabled').checked = true;
  7969. document.getElementById('aerotun-modal-psk').type = 'password';
  7970. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  7971. onAeroTUNModeChange();
  7972. updateAeroTUNSetupHint();
  7973. document.getElementById('aerotun-modal').classList.remove('hidden');
  7974. generateAeroTUNKey(true);
  7975. generateAeroTUNIdentity();
  7976. }
  7977. function openEditAeroTUNModal(id) {
  7978. if (aeroSaving) return;
  7979. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7980. if (!t) return;
  7981. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7982. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  7983. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7984. document.getElementById('aerotun-modal-id').value = t.id;
  7985. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7986. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7987. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7988. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7989. document.getElementById('aerotun-modal-name').value = t.name;
  7990. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7991. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7992. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7993. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7994. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7995. const peerHost = (t.peer_address || '').split('/')[0];
  7996. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  7997. document.getElementById('aerotun-modal-psk').value = '';
  7998. document.getElementById('aerotun-modal-psk').type = 'password';
  7999. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8000. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8001. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8002. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8003. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8004. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8005. onAeroTUNModeChange();
  8006. updateAeroTUNSetupHint();
  8007. document.getElementById('aerotun-modal').classList.remove('hidden');
  8008. }
  8009. function closeAeroTUNModal() {
  8010. if (aeroSaving) return;
  8011. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8012. document.getElementById('aerotun-modal-psk').value = '';
  8013. document.getElementById('aerotun-modal').classList.add('hidden');
  8014. }
  8015. async function submitSaveAeroTUN(e) {
  8016. e.preventDefault();
  8017. if (aeroSaving) return;
  8018. const id = document.getElementById('aerotun-modal-id').value;
  8019. const name = document.getElementById('aerotun-modal-name').value.trim();
  8020. const mode = document.getElementById('aerotun-modal-mode').value;
  8021. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8022. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8023. const local = document.getElementById('aerotun-modal-local').value.trim();
  8024. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8025. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8026. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8027. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8028. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8029. const compression = document.getElementById('aerotun-modal-compression').checked;
  8030. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8031. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8032. if (mode === 'client' && !endpoint) {
  8033. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8034. return;
  8035. }
  8036. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8037. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8038. return;
  8039. }
  8040. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8041. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8042. return;
  8043. }
  8044. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8045. if (version === 3 && !id && !aeroIdentityDraft) {
  8046. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8047. return;
  8048. }
  8049. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8050. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8051. document.getElementById('aerotun-modal-allowed').focus();
  8052. return;
  8053. }
  8054. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8055. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8056. return;
  8057. }
  8058. if (!psk && !id) {
  8059. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8060. return;
  8061. }
  8062. aeroSaving = true;
  8063. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8064. if (submit) submit.disabled = true;
  8065. try {
  8066. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8067. method: 'POST',
  8068. headers: { 'Content-Type': 'application/json' },
  8069. body: JSON.stringify({
  8070. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8071. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8072. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8073. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8074. id,
  8075. name,
  8076. mode,
  8077. listen_port: port,
  8078. remote_endpoint: endpoint,
  8079. local_address: local,
  8080. peer_address: peer,
  8081. psk,
  8082. mtu,
  8083. compression,
  8084. default_route: defaultRoute,
  8085. comment,
  8086. disabled
  8087. })
  8088. });
  8089. if (res.ok) {
  8090. await res.json();
  8091. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8092. aeroIdentityDraft = '';
  8093. aeroSaving = false;
  8094. closeAeroTUNModal();
  8095. await loadAeroTUN(false);
  8096. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8097. fetchData(false);
  8098. } else {
  8099. const err = await responseError(res);
  8100. if (err.includes('configuration saved but tunnel failed to start')) {
  8101. aeroIdentityDraft = '';
  8102. aeroSaving = false;
  8103. closeAeroTUNModal();
  8104. await loadAeroTUN(false);
  8105. showToast('Saved, but not started', err, 'error');
  8106. } else showToast('Error Saving Tunnel', err, 'error');
  8107. }
  8108. } catch (err) {
  8109. showToast('Network Error', err.message, 'error');
  8110. } finally {
  8111. aeroSaving = false;
  8112. if (submit) submit.disabled = false;
  8113. }
  8114. }
  8115. async function startAeroTUNTunnel(id) {
  8116. try {
  8117. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8118. if (res.ok) {
  8119. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8120. loadAeroTUN(false);
  8121. fetchData(false);
  8122. } else {
  8123. const err = await res.text();
  8124. showToast('Failed to Start', err, 'error');
  8125. }
  8126. } catch (err) {
  8127. showToast('Error', err.message, 'error');
  8128. }
  8129. }
  8130. async function stopAeroTUNTunnel(id) {
  8131. try {
  8132. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8133. if (res.ok) {
  8134. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8135. loadAeroTUN(false);
  8136. fetchData(false);
  8137. } else {
  8138. const err = await res.text();
  8139. showToast('Failed to Stop', err, 'error');
  8140. }
  8141. } catch (err) {
  8142. showToast('Error', err.message, 'error');
  8143. }
  8144. }
  8145. async function toggleAeroTUNState(id, disabled) {
  8146. try {
  8147. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8148. method: 'POST',
  8149. headers: { 'Content-Type': 'application/json' },
  8150. body: JSON.stringify({ disabled })
  8151. });
  8152. if (res.ok) {
  8153. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8154. loadAeroTUN(false);
  8155. fetchData(false);
  8156. }
  8157. } catch (err) {
  8158. showToast('Error', err.message, 'error');
  8159. }
  8160. }
  8161. async function deleteAeroTUN(id) {
  8162. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8163. try {
  8164. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8165. if (res.ok) {
  8166. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8167. loadAeroTUN(false);
  8168. fetchData(false);
  8169. }
  8170. } catch (err) {
  8171. showToast('Error', err.message, 'error');
  8172. }
  8173. }
  8174. // ======================== PPP Central Hub & Servers ========================
  8175. function switchPPPSubTab(tab) {
  8176. state.pppSubTab = tab;
  8177. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8178. tabs.forEach(t => {
  8179. const panel = document.getElementById(`ppp-subtab-${t}`);
  8180. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8181. if (panel) {
  8182. if (t === tab) panel.classList.remove('hidden');
  8183. else panel.classList.add('hidden');
  8184. }
  8185. if (btn) {
  8186. if (t === tab) {
  8187. 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';
  8188. } else {
  8189. 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';
  8190. }
  8191. }
  8192. });
  8193. const addBtn = document.getElementById('ppp-primary-add-btn');
  8194. if (addBtn) {
  8195. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8196. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8197. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8198. else addBtn.innerHTML = '<span>Save Config</span>';
  8199. }
  8200. if (tab === 'active') loadPPPSessions();
  8201. }
  8202. function openCurrentPPPModal() {
  8203. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8204. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8205. else if (state.pppSubTab === 'active') loadPPPSessions();
  8206. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8207. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8208. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8209. }
  8210. async function loadPPP(populateDropdowns = true) {
  8211. await Promise.all([
  8212. loadPPPSecrets(),
  8213. loadPPPProfiles(),
  8214. loadPPPServers(),
  8215. loadPPPSessions()
  8216. ]);
  8217. }
  8218. async function loadPPPSecrets() {
  8219. try {
  8220. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8221. const data = await res.json();
  8222. state.pppSecrets = Array.isArray(data) ? data : [];
  8223. const b = document.getElementById('ppp-badge-secrets');
  8224. if (b) b.innerText = state.pppSecrets.length;
  8225. const b2 = document.getElementById('secrets-count-badge');
  8226. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8227. renderPPPSecrets();
  8228. } catch (err) {
  8229. console.error('Failed to load PPP secrets:', err);
  8230. }
  8231. }
  8232. function renderPPPSecrets() {
  8233. const tbody = document.getElementById('secrets-table-body');
  8234. const empty = document.getElementById('secrets-empty');
  8235. if (!tbody) return;
  8236. tbody.innerHTML = '';
  8237. const secrets = state.pppSecrets || [];
  8238. if (secrets.length === 0) {
  8239. empty?.classList.remove('hidden');
  8240. return;
  8241. }
  8242. empty?.classList.add('hidden');
  8243. secrets.forEach(s => {
  8244. const tr = document.createElement('tr');
  8245. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8246. tr.innerHTML = `
  8247. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8248. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8249. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8250. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8251. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8252. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8253. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8254. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8255. <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>
  8256. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8257. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8258. </td>
  8259. `;
  8260. tbody.appendChild(tr);
  8261. });
  8262. }
  8263. async function loadPPPProfiles() {
  8264. try {
  8265. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8266. const data = await res.json();
  8267. state.pppProfiles = Array.isArray(data) ? data : [];
  8268. const b = document.getElementById('ppp-badge-profiles');
  8269. if (b) b.innerText = state.pppProfiles.length;
  8270. const b2 = document.getElementById('profiles-count-badge');
  8271. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8272. // Populate profile selects across modals
  8273. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8274. selects.forEach(sid => {
  8275. const el = document.getElementById(sid);
  8276. if (!el) return;
  8277. const cur = el.value;
  8278. el.innerHTML = '';
  8279. state.pppProfiles.forEach(p => {
  8280. const opt = document.createElement('option');
  8281. opt.value = p.name;
  8282. opt.innerText = `${p.name} (${p.remote_address})`;
  8283. if (p.name === cur) opt.selected = true;
  8284. el.appendChild(opt);
  8285. });
  8286. });
  8287. renderPPPProfiles();
  8288. } catch (err) {
  8289. console.error('Failed to load PPP profiles:', err);
  8290. }
  8291. }
  8292. function renderPPPProfiles() {
  8293. const tbody = document.getElementById('profiles-table-body');
  8294. if (!tbody) return;
  8295. tbody.innerHTML = '';
  8296. (state.pppProfiles || []).forEach(p => {
  8297. const isDefault = p.name.startsWith('default');
  8298. const tr = document.createElement('tr');
  8299. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8300. tr.innerHTML = `
  8301. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8302. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8303. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8304. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8305. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8306. <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>
  8307. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8308. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8309. ${!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>`}
  8310. </td>
  8311. `;
  8312. tbody.appendChild(tr);
  8313. });
  8314. }
  8315. async function loadPPPServers() {
  8316. try {
  8317. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8318. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8319. fetch(`${API_BASE}/vpn/servers/pptp`),
  8320. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8321. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8322. ]);
  8323. if (pppoeRes.ok) {
  8324. state.pppoeServer = await pppoeRes.json();
  8325. const s = state.pppoeServer;
  8326. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8327. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8328. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8329. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8330. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8331. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8332. const pill = document.getElementById('pppoe-server-status-pill');
  8333. if (pill) {
  8334. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8335. 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';
  8336. }
  8337. setDotBadge('ppp-badge-pppoe-state', s.running);
  8338. }
  8339. if (pptpRes.ok) {
  8340. state.pptpServer = await pptpRes.json();
  8341. const s = state.pptpServer;
  8342. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8343. document.getElementById('pptp-server-port').value = s.port || 1723;
  8344. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8345. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8346. const pill = document.getElementById('pptp-server-status-pill');
  8347. if (pill) {
  8348. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8349. 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';
  8350. }
  8351. setDotBadge('ppp-badge-pptp-state', s.running);
  8352. }
  8353. if (l2tpRes.ok) {
  8354. state.l2tpServer = await l2tpRes.json();
  8355. const s = state.l2tpServer;
  8356. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8357. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8358. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8359. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8360. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8361. const pill = document.getElementById('l2tp-server-status-pill');
  8362. if (pill) {
  8363. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8364. 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';
  8365. }
  8366. setDotBadge('ppp-badge-l2tp-state', s.running);
  8367. }
  8368. if (ipsecRes.ok) {
  8369. state.ipsecServer = await ipsecRes.json();
  8370. const s = state.ipsecServer;
  8371. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8372. if (modalEn) modalEn.checked = !!s.enabled;
  8373. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8374. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8375. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8376. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8377. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8378. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8379. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8380. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8381. const pill = document.getElementById('modal-ipsec-server-status');
  8382. if (pill) {
  8383. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8384. 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';
  8385. }
  8386. }
  8387. } catch (err) {
  8388. console.error('Failed to load VPN servers:', err);
  8389. }
  8390. }
  8391. async function loadPPPSessions() {
  8392. try {
  8393. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8394. const data = await res.json();
  8395. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8396. const b = document.getElementById('ppp-badge-active');
  8397. if (b) b.innerText = state.pppActiveSessions.length;
  8398. const sideB = document.getElementById('badge-ppp-sessions');
  8399. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8400. renderPPPSessions();
  8401. } catch (err) {
  8402. console.error('Failed to load active PPP sessions:', err);
  8403. }
  8404. }
  8405. function renderPPPSessions() {
  8406. const tbody = document.getElementById('active-ppp-table-body');
  8407. const empty = document.getElementById('active-ppp-empty');
  8408. if (!tbody) return;
  8409. tbody.innerHTML = '';
  8410. const list = state.pppActiveSessions || [];
  8411. if (list.length === 0) {
  8412. empty?.classList.remove('hidden');
  8413. return;
  8414. }
  8415. empty?.classList.add('hidden');
  8416. list.forEach(s => {
  8417. const tr = document.createElement('tr');
  8418. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8419. tr.innerHTML = `
  8420. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8421. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8422. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8423. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8424. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8425. <td class="py-2.5 px-3 text-[11px]">
  8426. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8427. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8428. </td>
  8429. <td class="py-2.5 px-3 text-right font-sans">
  8430. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8431. </td>
  8432. `;
  8433. tbody.appendChild(tr);
  8434. });
  8435. }
  8436. async function disconnectPPPSession(iface) {
  8437. if (!confirm(`Disconnect session ${iface}?`)) return;
  8438. try {
  8439. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8440. if (res.ok) {
  8441. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8442. loadPPPSessions();
  8443. }
  8444. } catch (err) {
  8445. showToast('Error', err.message, 'error');
  8446. }
  8447. }
  8448. // PPP Secret Modal handlers
  8449. function openAddPPPSecretModal() {
  8450. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8451. document.getElementById('secret-modal-id').value = '';
  8452. document.getElementById('secret-modal-name').value = '';
  8453. document.getElementById('secret-modal-password').value = '';
  8454. document.getElementById('secret-modal-service').value = 'any';
  8455. document.getElementById('secret-modal-profile').value = 'default';
  8456. document.getElementById('secret-modal-local').value = '';
  8457. document.getElementById('secret-modal-remote').value = '';
  8458. document.getElementById('secret-modal-comment').value = '';
  8459. document.getElementById('secret-modal-disabled').checked = false;
  8460. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8461. }
  8462. function openEditPPPSecretModal(id) {
  8463. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8464. if (!s) return;
  8465. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8466. document.getElementById('secret-modal-id').value = s.id;
  8467. document.getElementById('secret-modal-name').value = s.name;
  8468. document.getElementById('secret-modal-password').value = s.password;
  8469. document.getElementById('secret-modal-service').value = s.service || 'any';
  8470. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8471. document.getElementById('secret-modal-local').value = s.local_address || '';
  8472. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8473. document.getElementById('secret-modal-comment').value = s.comment || '';
  8474. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8475. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8476. }
  8477. function closePPPSecretModal() {
  8478. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8479. }
  8480. async function submitSavePPPSecret(e) {
  8481. e.preventDefault();
  8482. const id = document.getElementById('secret-modal-id').value;
  8483. const name = document.getElementById('secret-modal-name').value.trim();
  8484. const password = document.getElementById('secret-modal-password').value.trim();
  8485. const service = document.getElementById('secret-modal-service').value;
  8486. const profile = document.getElementById('secret-modal-profile').value;
  8487. const local = document.getElementById('secret-modal-local').value.trim();
  8488. const remote = document.getElementById('secret-modal-remote').value.trim();
  8489. const comment = document.getElementById('secret-modal-comment').value.trim();
  8490. const disabled = document.getElementById('secret-modal-disabled').checked;
  8491. try {
  8492. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8493. method: 'POST',
  8494. headers: { 'Content-Type': 'application/json' },
  8495. body: JSON.stringify({
  8496. id,
  8497. name,
  8498. password,
  8499. service,
  8500. profile,
  8501. local_address: local,
  8502. remote_address: remote,
  8503. comment,
  8504. disabled
  8505. })
  8506. });
  8507. if (res.ok) {
  8508. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8509. closePPPSecretModal();
  8510. loadPPPSecrets();
  8511. } else {
  8512. const err = await res.json();
  8513. showToast('Error', err.message, 'error');
  8514. }
  8515. } catch (err) {
  8516. showToast('Error', err.message, 'error');
  8517. }
  8518. }
  8519. async function togglePPPSecretState(id, disabled) {
  8520. try {
  8521. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8522. method: 'POST',
  8523. headers: { 'Content-Type': 'application/json' },
  8524. body: JSON.stringify({ disabled })
  8525. });
  8526. if (res.ok) {
  8527. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8528. loadPPPSecrets();
  8529. }
  8530. } catch (err) {
  8531. showToast('Error', err.message, 'error');
  8532. }
  8533. }
  8534. async function deletePPPSecret(id) {
  8535. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8536. try {
  8537. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8538. if (res.ok) {
  8539. showToast('Deleted', 'Secret account removed', 'success');
  8540. loadPPPSecrets();
  8541. }
  8542. } catch (err) {
  8543. showToast('Error', err.message, 'error');
  8544. }
  8545. }
  8546. // PPP Profile Modal handlers
  8547. function openAddPPPProfileModal() {
  8548. document.getElementById('profile-modal-name').value = '';
  8549. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8550. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8551. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8552. document.getElementById('profile-modal-encryption').value = 'required';
  8553. document.getElementById('profile-modal-onlyone').checked = true;
  8554. document.getElementById('profile-modal-comment').value = '';
  8555. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8556. }
  8557. function closePPPProfileModal() {
  8558. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8559. }
  8560. async function submitSavePPPProfile(e) {
  8561. e.preventDefault();
  8562. const name = document.getElementById('profile-modal-name').value.trim();
  8563. const local = document.getElementById('profile-modal-local').value.trim();
  8564. const remote = document.getElementById('profile-modal-remote').value.trim();
  8565. const dns = document.getElementById('profile-modal-dns').value.trim();
  8566. const enc = document.getElementById('profile-modal-encryption').value;
  8567. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8568. const comment = document.getElementById('profile-modal-comment').value.trim();
  8569. try {
  8570. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8571. method: 'POST',
  8572. headers: { 'Content-Type': 'application/json' },
  8573. body: JSON.stringify({
  8574. id: name,
  8575. name,
  8576. local_address: local,
  8577. remote_address: remote,
  8578. dns_servers: dns,
  8579. use_encryption: enc,
  8580. only_one: onlyone,
  8581. comment
  8582. })
  8583. });
  8584. if (res.ok) {
  8585. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8586. closePPPProfileModal();
  8587. loadPPPProfiles();
  8588. } else {
  8589. const err = await res.json();
  8590. showToast('Error', err.message, 'error');
  8591. }
  8592. } catch (err) {
  8593. showToast('Error', err.message, 'error');
  8594. }
  8595. }
  8596. async function deletePPPProfile(name) {
  8597. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8598. try {
  8599. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8600. if (res.ok) {
  8601. showToast('Deleted', 'Profile removed', 'success');
  8602. loadPPPProfiles();
  8603. } else {
  8604. const err = await res.json();
  8605. showToast('Error', err.message, 'error');
  8606. }
  8607. } catch (err) {
  8608. showToast('Error', err.message, 'error');
  8609. }
  8610. }
  8611. // Server Config submissions
  8612. async function savePPPoEServerConfig(e) {
  8613. e.preventDefault();
  8614. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8615. const name = document.getElementById('pppoe-server-name').value.trim();
  8616. const iface = document.getElementById('pppoe-server-iface').value;
  8617. const profile = document.getElementById('pppoe-server-profile').value;
  8618. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8619. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8620. try {
  8621. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8622. method: 'POST',
  8623. headers: { 'Content-Type': 'application/json' },
  8624. body: JSON.stringify({
  8625. enabled,
  8626. service_name: name,
  8627. interface: iface,
  8628. default_profile: profile,
  8629. max_mtu: mtu,
  8630. max_mru: mtu,
  8631. one_session_per_host: onesession
  8632. })
  8633. });
  8634. if (res.ok) {
  8635. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8636. loadPPPServers();
  8637. fetchData(false);
  8638. } else {
  8639. const err = await res.json();
  8640. showToast('Error', err.message, 'error');
  8641. }
  8642. } catch (err) {
  8643. showToast('Error', err.message, 'error');
  8644. }
  8645. }
  8646. async function savePPTPServerConfig(e) {
  8647. e.preventDefault();
  8648. const enabled = document.getElementById('pptp-server-enabled').checked;
  8649. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8650. const profile = document.getElementById('pptp-server-profile').value;
  8651. const mppe = document.getElementById('pptp-server-mppe').checked;
  8652. try {
  8653. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8654. method: 'POST',
  8655. headers: { 'Content-Type': 'application/json' },
  8656. body: JSON.stringify({
  8657. enabled,
  8658. port,
  8659. default_profile: profile,
  8660. require_mppe: mppe
  8661. })
  8662. });
  8663. if (res.ok) {
  8664. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8665. loadPPPServers();
  8666. fetchData(false);
  8667. } else {
  8668. const err = await res.json();
  8669. showToast('Error', err.message, 'error');
  8670. }
  8671. } catch (err) {
  8672. showToast('Error', err.message, 'error');
  8673. }
  8674. }
  8675. async function saveL2TPServerConfig(e) {
  8676. e.preventDefault();
  8677. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8678. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8679. const profile = document.getElementById('l2tp-server-profile').value;
  8680. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8681. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8682. try {
  8683. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8684. method: 'POST',
  8685. headers: { 'Content-Type': 'application/json' },
  8686. body: JSON.stringify({
  8687. enabled,
  8688. port,
  8689. default_profile: profile,
  8690. use_ipsec: useipsec,
  8691. ipsec_secret: psk
  8692. })
  8693. });
  8694. if (res.ok) {
  8695. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8696. loadPPPServers();
  8697. fetchData(false);
  8698. } else {
  8699. const err = await res.json();
  8700. showToast('Error', err.message, 'error');
  8701. }
  8702. } catch (err) {
  8703. showToast('Error', err.message, 'error');
  8704. }
  8705. }
  8706. // IPSec Server Modal
  8707. function openIPSecServerModal() {
  8708. loadPPPServers();
  8709. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8710. }
  8711. function closeIPSecServerModal() {
  8712. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8713. }
  8714. async function submitSaveIPSecServer(e) {
  8715. e.preventDefault();
  8716. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8717. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8718. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8719. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8720. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8721. try {
  8722. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8723. method: 'POST',
  8724. headers: { 'Content-Type': 'application/json' },
  8725. body: JSON.stringify({
  8726. enabled,
  8727. preshared_key: psk,
  8728. pool_address: pool,
  8729. dns_servers: dns,
  8730. local_subnet: subnet
  8731. })
  8732. });
  8733. if (res.ok) {
  8734. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8735. closeIPSecServerModal();
  8736. loadPPPServers();
  8737. fetchData(false);
  8738. } else {
  8739. const err = await res.json();
  8740. showToast('Error', err.message, 'error');
  8741. }
  8742. } catch (err) {
  8743. showToast('Error', err.message, 'error');
  8744. }
  8745. }
  8746. // WireGuard Client Config Viewer
  8747. let currentWGClientConf = '';
  8748. async function openWGClientConfModal(iface, clientIP) {
  8749. try {
  8750. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8751. method: 'POST',
  8752. headers: { 'Content-Type': 'application/json' },
  8753. body: JSON.stringify({
  8754. interface: iface,
  8755. address: clientIP || '10.10.0.2/32',
  8756. dns: '1.1.1.1, 8.8.8.8'
  8757. })
  8758. });
  8759. if (res.ok) {
  8760. const data = await res.json();
  8761. currentWGClientConf = data.config;
  8762. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8763. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8764. } else {
  8765. const err = await res.json();
  8766. showToast('Error', err.message, 'error');
  8767. }
  8768. } catch (err) {
  8769. showToast('Error', err.message, 'error');
  8770. }
  8771. }
  8772. function closeWGClientConfModal() {
  8773. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8774. }
  8775. function copyWGClientConf() {
  8776. if (!currentWGClientConf) return;
  8777. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8778. }
  8779. function downloadWGClientConf() {
  8780. if (!currentWGClientConf) return;
  8781. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8782. const a = document.createElement('a');
  8783. a.href = URL.createObjectURL(blob);
  8784. a.download = 'wireguard-client.conf';
  8785. document.body.appendChild(a);
  8786. a.click();
  8787. document.body.removeChild(a);
  8788. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8789. }
  8790. // =========================================================================
  8791. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8792. // =========================================================================
  8793. state.activeDynSubTab = 'bgp-peers';
  8794. state.activeBgpSubTab = 'bgp-peers';
  8795. state.activeOspfTab = 'instances';
  8796. state.bgpInstance = null;
  8797. state.bgpPeers = [];
  8798. state.bgpNets = [];
  8799. state.bgpRoutes = [];
  8800. state.ospfInstance = null;
  8801. state.ospfInstances = [];
  8802. state.ospfAreas = [];
  8803. state.ospfAreaRanges = [];
  8804. state.ospfTemplates = [];
  8805. state.ospfLiveInterfaces = [];
  8806. state.ospfStaticNbrs = [];
  8807. state.ospfNeighbors = [];
  8808. state.ospfLSA = [];
  8809. state.ospfRoutes = [];
  8810. state.selectedOspfRow = {
  8811. instances: null,
  8812. areas: null,
  8813. 'area-ranges': null,
  8814. templates: null,
  8815. interfaces: null,
  8816. 'static-nbrs': null,
  8817. neighbors: null,
  8818. lsa: null,
  8819. };
  8820. state.ospfSort = {
  8821. instances: { col: 'name', asc: true },
  8822. areas: { col: 'name', asc: true },
  8823. ranges: { col: 'area', asc: true },
  8824. templates: { col: 'interfaces', asc: true },
  8825. live_ifaces: { col: 'interface', asc: true },
  8826. snbrs: { col: 'address', asc: true },
  8827. neighbors: { col: 'address', asc: true },
  8828. lsa: { col: 'instance', asc: true },
  8829. };
  8830. function switchBgpSubTab(subTab) {
  8831. state.activeBgpSubTab = subTab;
  8832. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8833. tabs.forEach(t => {
  8834. const el = document.getElementById(`dyn-subtab-${t}`);
  8835. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8836. if (el) el.classList.toggle('hidden', t !== subTab);
  8837. if (btn) {
  8838. if (t === subTab) {
  8839. 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';
  8840. } else {
  8841. 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';
  8842. }
  8843. }
  8844. });
  8845. }
  8846. function switchOspfTab(tabName) {
  8847. state.activeOspfTab = tabName;
  8848. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8849. tabs.forEach(t => {
  8850. const pane = document.getElementById(`ospf-pane-${t}`);
  8851. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8852. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8853. if (btn) {
  8854. if (t === tabName) {
  8855. 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';
  8856. } else {
  8857. 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';
  8858. }
  8859. }
  8860. });
  8861. }
  8862. function switchOspfSubTab(tab) {
  8863. // Legacy alias
  8864. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8865. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8866. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8867. else switchOspfTab('instances');
  8868. }
  8869. function switchDynSubTab(subTab) {
  8870. if (subTab.startsWith('bgp')) {
  8871. if (state.activeTab !== 'bgp') navigate('bgp');
  8872. switchBgpSubTab(subTab);
  8873. } else if (subTab.startsWith('ospf')) {
  8874. if (state.activeTab !== 'ospf') navigate('ospf');
  8875. switchOspfTab('instances');
  8876. }
  8877. }
  8878. async function loadDynamicRouting(showToastMsg = false) {
  8879. try {
  8880. const fetchSafeJson = async (url) => {
  8881. try {
  8882. const r = await fetch(url);
  8883. return r.ok ? await r.json() : null;
  8884. } catch (e) {
  8885. return null;
  8886. }
  8887. };
  8888. const [
  8889. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8890. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8891. selectRules, commLists, asLists
  8892. ] = await Promise.all([
  8893. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8894. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8895. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8896. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8897. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8898. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8899. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8900. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8901. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8902. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8903. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8904. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8905. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8906. fetchSafeJson(`${API_BASE}/routing/filters`),
  8907. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8908. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  8909. ]);
  8910. if (sum) state.dynSummary = sum;
  8911. if (bgpInst) state.bgpInstance = bgpInst;
  8912. if (bgpPeers) state.bgpPeers = bgpPeers;
  8913. if (bgpNets) state.bgpNets = bgpNets;
  8914. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8915. if (ospfInsts) state.ospfInstances = ospfInsts;
  8916. if (ospfAreas) state.ospfAreas = ospfAreas;
  8917. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8918. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8919. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8920. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8921. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8922. if (ospfLsa) state.ospfLSA = ospfLsa;
  8923. if (filters) state.routingFilters = filters;
  8924. if (commLists) state.routingCommunityLists = commLists;
  8925. if (asLists) state.routingASLists = asLists;
  8926. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8927. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8928. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8929. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8930. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8931. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8932. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8933. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  8934. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  8935. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  8936. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  8937. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  8938. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  8939. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  8940. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  8941. } catch (err) {
  8942. console.error('Failed to load dynamic routing:', err);
  8943. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  8944. }
  8945. }
  8946. async function loadOspfAll() {
  8947. await loadDynamicRouting(true);
  8948. }
  8949. function renderBgpStatusPill() {
  8950. const pills = document.querySelectorAll('.bgp-live-status-pill');
  8951. pills.forEach(pill => {
  8952. const inst = state.bgpInstance;
  8953. if (!inst || !inst.enabled) {
  8954. 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';
  8955. pill.innerText = 'BGP DISABLED';
  8956. } else if (inst.running) {
  8957. 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';
  8958. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  8959. } else {
  8960. 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';
  8961. pill.innerText = 'BGP STARTING...';
  8962. }
  8963. });
  8964. }
  8965. function renderBgpPeers() {
  8966. const tbody = document.getElementById('bgp-peers-table-body');
  8967. if (!tbody) return;
  8968. const empty = document.getElementById('bgp-peers-empty');
  8969. const countBadge = document.getElementById('bgp-peers-count-badge');
  8970. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8971. const peers = state.bgpPeers || [];
  8972. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8973. if (navBadge) navBadge.innerText = peers.length;
  8974. if (peers.length === 0) {
  8975. tbody.innerHTML = '';
  8976. if (empty) empty.classList.remove('hidden');
  8977. return;
  8978. }
  8979. if (empty) empty.classList.add('hidden');
  8980. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8981. if (tbody.dataset.sig === sig) return;
  8982. tbody.dataset.sig = sig;
  8983. tbody.innerHTML = peers.map(p => {
  8984. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8985. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8986. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8987. let stateBadge = '';
  8988. if (p.disabled) {
  8989. 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>';
  8990. } else if (p.state === 'Established') {
  8991. 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>';
  8992. } else if (p.state === 'Connect' || p.state === 'Active') {
  8993. 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>`;
  8994. } else {
  8995. 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>`;
  8996. }
  8997. return `
  8998. <tr class="hover:bg-slate-800/40 transition">
  8999. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9000. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9001. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9002. <td class="py-2.5 px-3">
  9003. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9004. ${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>`}
  9005. </td>
  9006. <td class="py-2.5 px-3">${stateBadge}</td>
  9007. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9008. <td class="py-2.5 px-3 text-slate-300">
  9009. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9010. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9011. </td>
  9012. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9013. ${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> ` : ''}
  9014. ${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>` : ''}
  9015. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9016. </td>
  9017. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9018. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9019. <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'}">
  9020. ${p.disabled ? 'Enable' : 'Disable'}
  9021. </button>
  9022. <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">
  9023. Edit
  9024. </button>
  9025. <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">
  9026. Delete
  9027. </button>
  9028. </td>
  9029. </tr>
  9030. `;
  9031. }).join('');
  9032. }
  9033. function renderBgpNetworks() {
  9034. const tbody = document.getElementById('bgp-nets-table-body');
  9035. if (!tbody) return;
  9036. const empty = document.getElementById('bgp-nets-empty');
  9037. const countBadge = document.getElementById('bgp-nets-count-badge');
  9038. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9039. const nets = state.bgpNets || [];
  9040. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9041. if (navBadge) navBadge.innerText = nets.length;
  9042. if (nets.length === 0) {
  9043. tbody.innerHTML = '';
  9044. if (empty) empty.classList.remove('hidden');
  9045. return;
  9046. }
  9047. if (empty) empty.classList.add('hidden');
  9048. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9049. if (tbody.dataset.sig === sig) return;
  9050. tbody.dataset.sig = sig;
  9051. tbody.innerHTML = nets.map(n => `
  9052. <tr class="hover:bg-slate-800/40 transition">
  9053. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9054. <td class="py-2.5 px-3">
  9055. ${n.disabled
  9056. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9057. : '<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>'}
  9058. </td>
  9059. <td class="py-2.5 px-3">
  9060. ${n.disabled
  9061. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9062. : '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-cyan-800/40 font-mono">blackhole (dist 255)</span>'}
  9063. </td>
  9064. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9065. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9066. <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">
  9067. Delete
  9068. </button>
  9069. </td>
  9070. </tr>
  9071. `).join('');
  9072. }
  9073. function renderBgpRoutes() {
  9074. const tbody = document.getElementById('bgp-routes-table-body');
  9075. if (!tbody) return;
  9076. const empty = document.getElementById('bgp-routes-empty');
  9077. const countBadge = document.getElementById('bgp-routes-count-badge');
  9078. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9079. const routes = state.bgpRoutes || [];
  9080. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9081. if (navBadge) navBadge.innerText = routes.length;
  9082. if (routes.length === 0) {
  9083. tbody.innerHTML = '';
  9084. if (empty) empty.classList.remove('hidden');
  9085. return;
  9086. }
  9087. if (empty) empty.classList.add('hidden');
  9088. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9089. if (tbody.dataset.sig === sig) return;
  9090. tbody.dataset.sig = sig;
  9091. tbody.innerHTML = routes.map(r => `
  9092. <tr class="hover:bg-slate-800/40 transition">
  9093. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9094. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9095. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9096. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9097. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9098. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9099. </tr>
  9100. `).join('');
  9101. }
  9102. // =========================================================================
  9103. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9104. // =========================================================================
  9105. function sortOspfTable(tab, col) {
  9106. if (!state.ospfSort) state.ospfSort = {};
  9107. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9108. if (state.ospfSort[tab].col === col) {
  9109. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9110. } else {
  9111. state.ospfSort[tab].col = col;
  9112. state.ospfSort[tab].asc = true;
  9113. }
  9114. const asc = state.ospfSort[tab].asc;
  9115. let list = [];
  9116. if (tab === 'instances') list = state.ospfInstances || [];
  9117. else if (tab === 'areas') list = state.ospfAreas || [];
  9118. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9119. else if (tab === 'templates') list = state.ospfTemplates || [];
  9120. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9121. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9122. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9123. else if (tab === 'lsa') list = state.ospfLSA || [];
  9124. list.sort((a, b) => {
  9125. let valA = a[col] ?? '';
  9126. let valB = b[col] ?? '';
  9127. if (typeof valA === 'number' && typeof valB === 'number') {
  9128. return asc ? valA - valB : valB - valA;
  9129. }
  9130. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9131. });
  9132. if (tab === 'instances') renderOspfInstances();
  9133. else if (tab === 'areas') renderOspfAreas();
  9134. else if (tab === 'ranges') renderOspfAreaRanges();
  9135. else if (tab === 'templates') renderOspfTemplates();
  9136. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9137. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9138. else if (tab === 'neighbors') renderOspfNeighbors();
  9139. else if (tab === 'lsa') renderOspfLSA();
  9140. }
  9141. function selectOspfRow(tab, id) {
  9142. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9143. state.selectedOspfRow[tab] = id;
  9144. if (tab === 'instances') {
  9145. renderOspfInstances();
  9146. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9147. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9148. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9149. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9150. if (btnEn) btnEn.disabled = false;
  9151. if (btnDis) btnDis.disabled = false;
  9152. if (btnRem) btnRem.disabled = false;
  9153. if (btnCom) btnCom.disabled = false;
  9154. } else if (tab === 'areas') {
  9155. renderOspfAreas();
  9156. const btnEn = document.getElementById('btn-ospf-area-enable');
  9157. const btnDis = document.getElementById('btn-ospf-area-disable');
  9158. const btnRem = document.getElementById('btn-ospf-area-remove');
  9159. const btnCom = document.getElementById('btn-ospf-area-comment');
  9160. if (btnEn) btnEn.disabled = false;
  9161. if (btnDis) btnDis.disabled = false;
  9162. if (btnRem) btnRem.disabled = false;
  9163. if (btnCom) btnCom.disabled = false;
  9164. } else if (tab === 'ranges') {
  9165. renderOspfAreaRanges();
  9166. const btnEn = document.getElementById('btn-ospf-range-enable');
  9167. const btnDis = document.getElementById('btn-ospf-range-disable');
  9168. const btnRem = document.getElementById('btn-ospf-range-remove');
  9169. const btnCom = document.getElementById('btn-ospf-range-comment');
  9170. if (btnEn) btnEn.disabled = false;
  9171. if (btnDis) btnDis.disabled = false;
  9172. if (btnRem) btnRem.disabled = false;
  9173. if (btnCom) btnCom.disabled = false;
  9174. } else if (tab === 'templates') {
  9175. renderOspfTemplates();
  9176. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9177. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9178. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9179. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9180. if (btnEn) btnEn.disabled = false;
  9181. if (btnDis) btnDis.disabled = false;
  9182. if (btnRem) btnRem.disabled = false;
  9183. if (btnCom) btnCom.disabled = false;
  9184. } else if (tab === 'snbrs') {
  9185. renderOspfStaticNbrs();
  9186. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9187. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9188. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9189. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9190. if (btnEn) btnEn.disabled = false;
  9191. if (btnDis) btnDis.disabled = false;
  9192. if (btnRem) btnRem.disabled = false;
  9193. if (btnCom) btnCom.disabled = false;
  9194. }
  9195. }
  9196. // TAB 1: INSTANCES
  9197. function renderOspfInstances() {
  9198. const tbody = document.getElementById('ospf-instances-table-body');
  9199. if (!tbody) return;
  9200. const countEl = document.getElementById('ospf-instances-footer-count');
  9201. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9202. let list = state.ospfInstances || [];
  9203. if (filter) {
  9204. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9205. }
  9206. if (countEl) countEl.innerText = list.length;
  9207. const selId = state.selectedOspfRow?.instances;
  9208. tbody.innerHTML = list.map((inst, idx) => {
  9209. const isSel = inst.id === selId;
  9210. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9211. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9212. return `
  9213. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9214. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9215. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9216. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9217. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9218. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9219. </td>
  9220. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9221. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9222. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9223. </tr>
  9224. `;
  9225. }).join('');
  9226. }
  9227. // TAB 2: AREAS
  9228. function renderOspfAreas() {
  9229. const tbody = document.getElementById('ospf-areas-table-body');
  9230. if (!tbody) return;
  9231. const countEl = document.getElementById('ospf-areas-footer-count');
  9232. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9233. let list = state.ospfAreas || [];
  9234. if (filter) {
  9235. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9236. }
  9237. if (countEl) countEl.innerText = list.length;
  9238. const selId = state.selectedOspfRow?.areas;
  9239. tbody.innerHTML = list.map((a, idx) => {
  9240. const isSel = a.id === selId;
  9241. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9242. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9243. return `
  9244. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9245. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9246. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9247. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9248. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9249. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9250. </td>
  9251. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9252. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9253. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9254. </tr>
  9255. `;
  9256. }).join('');
  9257. }
  9258. // TAB 3: AREA RANGES
  9259. function renderOspfAreaRanges() {
  9260. const tbody = document.getElementById('ospf-ranges-table-body');
  9261. if (!tbody) return;
  9262. const countEl = document.getElementById('ospf-ranges-footer-count');
  9263. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9264. let list = state.ospfAreaRanges || [];
  9265. if (filter) {
  9266. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9267. }
  9268. if (countEl) countEl.innerText = list.length;
  9269. const selId = state.selectedOspfRow?.['area-ranges'];
  9270. tbody.innerHTML = list.map((r, idx) => {
  9271. const isSel = r.id === selId;
  9272. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9273. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9274. return `
  9275. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9276. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9277. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9278. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9279. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9280. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9281. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9282. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9283. </tr>
  9284. `;
  9285. }).join('');
  9286. }
  9287. // TAB 4: INTERFACE TEMPLATES
  9288. function renderOspfTemplates() {
  9289. const tbody = document.getElementById('ospf-templates-table-body');
  9290. if (!tbody) return;
  9291. const countEl = document.getElementById('ospf-templates-footer-count');
  9292. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9293. let list = state.ospfTemplates || [];
  9294. if (filter) {
  9295. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9296. }
  9297. if (countEl) countEl.innerText = list.length;
  9298. const selId = state.selectedOspfRow?.templates;
  9299. tbody.innerHTML = list.map((t, idx) => {
  9300. const isSel = t.id === selId;
  9301. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9302. const ifaces = t.interfaces || t.interface || 'all';
  9303. const nets = t.networks || t.network || '';
  9304. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9305. return `
  9306. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9307. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9308. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9309. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9310. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9311. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9312. </td>
  9313. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9314. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9315. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9316. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9317. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9318. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9319. </tr>
  9320. `;
  9321. }).join('');
  9322. }
  9323. // TAB 5: LIVE INTERFACES
  9324. function renderOspfLiveInterfaces() {
  9325. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9326. if (!tbody) return;
  9327. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9328. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9329. let list = state.ospfLiveInterfaces || [];
  9330. if (filter) {
  9331. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9332. }
  9333. if (countEl) countEl.innerText = list.length;
  9334. tbody.innerHTML = list.map(i => `
  9335. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9336. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9337. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9338. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9339. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9340. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9341. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9342. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9343. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9344. </tr>
  9345. `).join('');
  9346. }
  9347. // TAB 6: STATIC NEIGHBORS
  9348. function renderOspfStaticNbrs() {
  9349. const tbody = document.getElementById('ospf-snbrs-table-body');
  9350. if (!tbody) return;
  9351. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9352. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9353. let list = state.ospfStaticNbrs || [];
  9354. if (filter) {
  9355. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9356. }
  9357. if (countEl) countEl.innerText = list.length;
  9358. const selId = state.selectedOspfRow?.['static-nbrs'];
  9359. tbody.innerHTML = list.map((n, idx) => {
  9360. const isSel = n.id === selId;
  9361. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9362. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9363. return `
  9364. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9365. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9366. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9367. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9368. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9369. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9370. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9371. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9372. </tr>
  9373. `;
  9374. }).join('');
  9375. }
  9376. // TAB 7: LIVE NEIGHBORS
  9377. function renderOspfNeighbors() {
  9378. const tbody = document.getElementById('ospf-neighbors-table-body');
  9379. if (!tbody) return;
  9380. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9381. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9382. let list = state.ospfNeighbors || [];
  9383. if (filter) {
  9384. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9385. }
  9386. if (countEl) countEl.innerText = list.length;
  9387. tbody.innerHTML = list.map(n => `
  9388. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9389. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9390. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9391. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9392. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9393. </td>
  9394. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9395. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9396. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9397. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9398. </tr>
  9399. `).join('');
  9400. }
  9401. // TAB 8: LINK-STATE DATABASE (LSA)
  9402. function renderOspfLSA() {
  9403. const tbody = document.getElementById('ospf-lsa-table-body');
  9404. if (!tbody) return;
  9405. const countEl = document.getElementById('ospf-lsa-footer-count');
  9406. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9407. let list = state.ospfLSA || [];
  9408. if (filter) {
  9409. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9410. }
  9411. if (countEl) countEl.innerText = list.length;
  9412. tbody.innerHTML = list.map(l => `
  9413. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9414. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9415. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9416. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9417. </td>
  9418. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9419. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9420. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9421. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9422. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9423. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9424. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9425. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9426. </tr>
  9427. `).join('');
  9428. }
  9429. function renderOspfStatusPill() {
  9430. // Maintained for backward compatibility
  9431. const pill = document.getElementById('ospf-live-status-pill');
  9432. if (!pill) return;
  9433. 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';
  9434. pill.innerText = 'OSPF ACTIVE';
  9435. }
  9436. function renderOspfInterfaces() {
  9437. renderOspfTemplates();
  9438. }
  9439. function renderOspfRoutes() {
  9440. // Routes retained in background
  9441. }
  9442. // BGP Modals & Actions
  9443. function openBgpInstanceModal() {
  9444. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9445. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9446. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9447. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9448. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9449. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9450. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9451. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9452. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9453. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9454. }
  9455. function closeBgpInstanceModal() {
  9456. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9457. }
  9458. async function submitBgpInstance(e) {
  9459. e.preventDefault();
  9460. const payload = {
  9461. enabled: document.getElementById('modal-bgp-enabled').checked,
  9462. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9463. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9464. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9465. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9466. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9467. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9468. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9469. };
  9470. try {
  9471. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9472. method: 'POST',
  9473. headers: { 'Content-Type': 'application/json' },
  9474. body: JSON.stringify(payload)
  9475. });
  9476. if (res.ok) {
  9477. closeBgpInstanceModal();
  9478. showToast('Success', 'BGP instance configuration updated', 'success');
  9479. loadDynamicRouting();
  9480. } else {
  9481. const err = await res.json();
  9482. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9483. }
  9484. } catch (err) {
  9485. showToast('Error', err.message, 'error');
  9486. }
  9487. }
  9488. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9489. function switchBgpPeerModalTab(tab) {
  9490. // Normalize legacy tab names
  9491. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9492. if (tab === 'attributes') tab = 'networks';
  9493. const tabs = ['general', 'filters', 'networks'];
  9494. tabs.forEach(t => {
  9495. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9496. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9497. if (t === tab) {
  9498. if (pane) pane.classList.remove('hidden');
  9499. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9500. } else {
  9501. if (pane) pane.classList.add('hidden');
  9502. 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';
  9503. }
  9504. });
  9505. }
  9506. function addOutputNetworkRow(val = '') {
  9507. const container = document.getElementById('modal-bgp-output-networks-container');
  9508. if (!container) return;
  9509. const row = document.createElement('div');
  9510. row.className = 'flex items-center gap-2 output-net-row';
  9511. row.innerHTML = `
  9512. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.100.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  9513. <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>
  9514. `;
  9515. container.appendChild(row);
  9516. }
  9517. function parseBgpTime(val) {
  9518. if (!val) return 0;
  9519. val = String(val).trim();
  9520. if (val.includes(':')) {
  9521. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9522. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9523. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9524. }
  9525. return parseInt(val, 10) || 0;
  9526. }
  9527. function formatBgpTime(secs) {
  9528. if (!secs || secs <= 0) return '30';
  9529. return String(secs);
  9530. }
  9531. function populateBgpRoutingTables() {
  9532. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9533. if (!sel) return;
  9534. const cur = sel.value || 'main';
  9535. sel.innerHTML = '<option value="main">main</option>';
  9536. (state.routingTables || []).forEach(t => {
  9537. if (t.name !== 'main') {
  9538. const opt = document.createElement('option');
  9539. opt.value = t.name;
  9540. opt.innerText = t.name;
  9541. sel.appendChild(opt);
  9542. }
  9543. });
  9544. sel.value = cur;
  9545. }
  9546. function openAddBgpPeerModal() {
  9547. document.getElementById('bgp-peer-form').reset();
  9548. document.getElementById('modal-bgp-peer-id').value = '';
  9549. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9550. // General Tab
  9551. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9552. document.getElementById('modal-bgp-peer-name').value = '';
  9553. document.getElementById('modal-bgp-peer-comment').value = '';
  9554. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9555. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9556. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9557. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9558. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9559. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9560. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9561. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9562. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9563. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9564. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9565. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9566. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9567. // Filters Tab
  9568. populateFilterChainsDatalist();
  9569. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9570. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9571. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9572. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9573. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9574. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9575. // Advertised Networks Tab
  9576. const container = document.getElementById('modal-bgp-output-networks-container');
  9577. if (container) {
  9578. container.innerHTML = '';
  9579. addOutputNetworkRow('');
  9580. }
  9581. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9582. if (removeBtn) removeBtn.classList.add('hidden');
  9583. switchBgpPeerModalTab('general');
  9584. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9585. }
  9586. function populateFilterChainsDatalist() {
  9587. const dl = document.getElementById('filter-chains-list');
  9588. if (!dl) return;
  9589. const chains = new Set();
  9590. (state.routingFilters || []).forEach(f => {
  9591. if (f.chain) chains.add(f.chain);
  9592. });
  9593. if (chains.size === 0) {
  9594. chains.add('awmn');
  9595. chains.add('Internal');
  9596. chains.add('bgp-in');
  9597. chains.add('bgp-out');
  9598. }
  9599. dl.innerHTML = '';
  9600. chains.forEach(c => {
  9601. const opt = document.createElement('option');
  9602. opt.value = c;
  9603. dl.appendChild(opt);
  9604. });
  9605. }
  9606. function openEditBgpPeerModal(id) {
  9607. const p = (state.bgpPeers || []).find(item => item.id === id);
  9608. if (!p) return;
  9609. populateFilterChainsDatalist();
  9610. document.getElementById('modal-bgp-peer-id').value = p.id;
  9611. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9612. // General Tab
  9613. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9614. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9615. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9616. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9617. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9618. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9619. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9620. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9621. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9622. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9623. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9624. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9625. // Passive mode
  9626. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9627. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9628. // Next-hop self
  9629. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9630. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9631. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9632. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9633. // Filters Tab
  9634. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9635. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9636. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9637. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9638. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9639. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9640. // Advertised Networks Tab
  9641. const container = document.getElementById('modal-bgp-output-networks-container');
  9642. if (container) {
  9643. container.innerHTML = '';
  9644. if (p.output_networks && p.output_networks.length > 0) {
  9645. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9646. } else {
  9647. addOutputNetworkRow('');
  9648. }
  9649. }
  9650. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9651. if (removeBtn) removeBtn.classList.remove('hidden');
  9652. switchBgpPeerModalTab('general');
  9653. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9654. }
  9655. function copyCurrentBgpPeer() {
  9656. document.getElementById('modal-bgp-peer-id').value = '';
  9657. const nameEl = document.getElementById('modal-bgp-peer-name');
  9658. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9659. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9660. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9661. if (removeBtn) removeBtn.classList.add('hidden');
  9662. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9663. }
  9664. function removeCurrentBgpPeer() {
  9665. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9666. if (!id) return;
  9667. deleteBgpPeer(id);
  9668. closeBgpPeerModal();
  9669. }
  9670. function closeBgpPeerModal() {
  9671. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9672. }
  9673. function getBgpPeerFormData() {
  9674. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9675. const outputNetworks = [];
  9676. netInputs.forEach(inp => {
  9677. const v = inp.value.trim();
  9678. if (v) outputNetworks.push(v);
  9679. });
  9680. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9681. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9682. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9683. return {
  9684. id: document.getElementById('modal-bgp-peer-id').value,
  9685. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9686. enabled: enabled,
  9687. disabled: !enabled,
  9688. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9689. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9690. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9691. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9692. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9693. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9694. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9695. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9696. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9697. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9698. passive: isPassive,
  9699. connect: !isPassive,
  9700. listen: true,
  9701. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9702. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9703. nexthop_self: isNexthopSelf,
  9704. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9705. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9706. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9707. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9708. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9709. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9710. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9711. output_networks: outputNetworks
  9712. };
  9713. }
  9714. async function submitBgpPeer(e) {
  9715. if (e) e.preventDefault();
  9716. const payload = getBgpPeerFormData();
  9717. try {
  9718. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9719. method: 'POST',
  9720. headers: { 'Content-Type': 'application/json' },
  9721. body: JSON.stringify(payload)
  9722. });
  9723. if (res.ok) {
  9724. closeBgpPeerModal();
  9725. showToast('Success', 'BGP Connection saved', 'success');
  9726. loadDynamicRouting();
  9727. } else {
  9728. const err = await res.json();
  9729. showToast('Error', err.error || 'Failed to save peer', 'error');
  9730. }
  9731. } catch (err) {
  9732. showToast('Error', err.message, 'error');
  9733. }
  9734. }
  9735. async function applyBgpPeerModal(e) {
  9736. if (e) e.preventDefault();
  9737. const payload = getBgpPeerFormData();
  9738. try {
  9739. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9740. method: 'POST',
  9741. headers: { 'Content-Type': 'application/json' },
  9742. body: JSON.stringify(payload)
  9743. });
  9744. if (res.ok) {
  9745. const data = await res.json();
  9746. if (data.peer && data.peer.id) {
  9747. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9748. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9749. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9750. }
  9751. showToast('Applied', 'BGP Connection applied', 'success');
  9752. loadDynamicRouting();
  9753. } else {
  9754. const err = await res.json();
  9755. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9756. }
  9757. } catch (err) {
  9758. showToast('Error', err.message, 'error');
  9759. }
  9760. }
  9761. async function deleteBgpPeer(id) {
  9762. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9763. try {
  9764. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9765. if (res.ok) {
  9766. showToast('Deleted', 'BGP peer removed', 'success');
  9767. loadDynamicRouting();
  9768. }
  9769. } catch (err) {
  9770. showToast('Error', err.message, 'error');
  9771. }
  9772. }
  9773. async function toggleBgpPeerState(id, disabled) {
  9774. try {
  9775. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9776. method: 'POST',
  9777. headers: { 'Content-Type': 'application/json' },
  9778. body: JSON.stringify({ disabled })
  9779. });
  9780. if (res.ok) {
  9781. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9782. loadDynamicRouting();
  9783. }
  9784. } catch (err) {
  9785. showToast('Error', err.message, 'error');
  9786. }
  9787. }
  9788. function openAddBgpNetworkModal() {
  9789. document.getElementById('bgp-network-form').reset();
  9790. document.getElementById('modal-bgp-net-id').value = '';
  9791. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9792. }
  9793. function closeBgpNetworkModal() {
  9794. document.getElementById('bgp-network-modal').classList.add('hidden');
  9795. }
  9796. async function submitBgpNetwork(e) {
  9797. e.preventDefault();
  9798. const payload = {
  9799. id: document.getElementById('modal-bgp-net-id').value,
  9800. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9801. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9802. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9803. };
  9804. try {
  9805. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9806. method: 'POST',
  9807. headers: { 'Content-Type': 'application/json' },
  9808. body: JSON.stringify(payload)
  9809. });
  9810. if (res.ok) {
  9811. closeBgpNetworkModal();
  9812. showToast('Success', 'BGP network advertisement saved', 'success');
  9813. loadDynamicRouting();
  9814. } else {
  9815. const err = await res.json();
  9816. showToast('Error', err.error || 'Failed to save network', 'error');
  9817. }
  9818. } catch (err) {
  9819. showToast('Error', err.message, 'error');
  9820. }
  9821. }
  9822. async function deleteBgpNetwork(id) {
  9823. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9824. try {
  9825. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9826. if (res.ok) {
  9827. showToast('Deleted', 'Network advertisement removed', 'success');
  9828. loadDynamicRouting();
  9829. }
  9830. } catch (err) {
  9831. showToast('Error', err.message, 'error');
  9832. }
  9833. }
  9834. // =========================================================================
  9835. // DEBTIK v7 OSPF MODALS & ACTIONS
  9836. // =========================================================================
  9837. // --- 1. OSPF INSTANCE ---
  9838. function openOspfInstanceModal(id = null) {
  9839. const isEdit = !!id;
  9840. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9841. id: '',
  9842. name: 'Default',
  9843. version: 2,
  9844. vrf: 'main',
  9845. router_id: '192.168.131.56',
  9846. routing_table: 'main',
  9847. enabled: true,
  9848. redistribute_connected: false,
  9849. redistribute_static: true,
  9850. redistribute_bgp: false,
  9851. comment: ''
  9852. };
  9853. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9854. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9855. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9856. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9857. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9858. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9859. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9860. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9861. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9862. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9863. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9864. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9865. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9866. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9867. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9868. }
  9869. function openEditOspfInstanceModal(id) {
  9870. openOspfInstanceModal(id);
  9871. }
  9872. function closeOspfInstanceModal() {
  9873. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9874. }
  9875. async function submitOspfInstance(e) {
  9876. if (e) e.preventDefault();
  9877. const payload = {
  9878. id: document.getElementById('modal-ospf-inst-id').value,
  9879. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9880. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9881. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9882. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9883. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9884. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9885. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9886. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9887. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9888. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9889. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9890. };
  9891. try {
  9892. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9893. method: 'POST',
  9894. headers: { 'Content-Type': 'application/json' },
  9895. body: JSON.stringify(payload)
  9896. });
  9897. if (res.ok) {
  9898. closeOspfInstanceModal();
  9899. showToast('Saved', 'OSPF instance updated', 'success');
  9900. loadDynamicRouting();
  9901. } else {
  9902. const err = await res.json();
  9903. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9904. }
  9905. } catch (err) {
  9906. showToast('Error', err.message, 'error');
  9907. }
  9908. }
  9909. function applyOspfInstanceForm() {
  9910. submitOspfInstance(null);
  9911. }
  9912. function copyOspfInstance() {
  9913. document.getElementById('modal-ospf-inst-id').value = '';
  9914. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9915. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9916. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9917. }
  9918. async function deleteCurrentOspfInstance() {
  9919. const id = document.getElementById('modal-ospf-inst-id').value;
  9920. if (!id) return;
  9921. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9922. try {
  9923. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9924. if (res.ok) {
  9925. closeOspfInstanceModal();
  9926. showToast('Removed', 'OSPF instance deleted', 'success');
  9927. loadDynamicRouting();
  9928. }
  9929. } catch (err) {
  9930. showToast('Error', err.message, 'error');
  9931. }
  9932. }
  9933. async function enableSelectedOspfInstance() {
  9934. const id = state.selectedOspfRow?.instances;
  9935. if (!id) return;
  9936. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9937. method: 'POST',
  9938. headers: { 'Content-Type': 'application/json' },
  9939. body: JSON.stringify({ disabled: false })
  9940. });
  9941. loadDynamicRouting();
  9942. }
  9943. async function disableSelectedOspfInstance() {
  9944. const id = state.selectedOspfRow?.instances;
  9945. if (!id) return;
  9946. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9947. method: 'POST',
  9948. headers: { 'Content-Type': 'application/json' },
  9949. body: JSON.stringify({ disabled: true })
  9950. });
  9951. loadDynamicRouting();
  9952. }
  9953. async function removeSelectedOspfInstance() {
  9954. const id = state.selectedOspfRow?.instances;
  9955. if (!id) return;
  9956. if (!confirm('Delete selected OSPF instance?')) return;
  9957. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9958. loadDynamicRouting();
  9959. }
  9960. async function promptCommentOspfInstance() {
  9961. const id = state.selectedOspfRow?.instances;
  9962. if (!id) return;
  9963. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9964. if (!inst) return;
  9965. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9966. if (comment === null) return;
  9967. inst.comment = comment;
  9968. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9969. method: 'POST',
  9970. headers: { 'Content-Type': 'application/json' },
  9971. body: JSON.stringify(inst)
  9972. });
  9973. loadDynamicRouting();
  9974. }
  9975. // --- 2. OSPF AREA ---
  9976. function populateOspfAreaDropdowns() {
  9977. const instSelect = document.getElementById('modal-ospf-area-instance');
  9978. if (instSelect) {
  9979. const cur = instSelect.value;
  9980. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9981. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9982. if (cur) instSelect.value = cur;
  9983. }
  9984. }
  9985. function openOspfAreaModal(id = null) {
  9986. const isEdit = !!id;
  9987. populateOspfAreaDropdowns();
  9988. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9989. id: '',
  9990. name: 'Default',
  9991. instance: 'Default',
  9992. area_id: '0.0.0.0',
  9993. area_type: 'default',
  9994. default_cost: 1,
  9995. no_summaries: false,
  9996. disabled: false,
  9997. comment: ''
  9998. };
  9999. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10000. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10001. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10002. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10003. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10004. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10005. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10006. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10007. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10008. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10009. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10010. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10011. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10012. }
  10013. function openEditOspfAreaModal(id) {
  10014. openOspfAreaModal(id);
  10015. }
  10016. function closeOspfAreaModal() {
  10017. document.getElementById('ospf-area-modal').classList.add('hidden');
  10018. }
  10019. async function submitOspfArea(e) {
  10020. if (e) e.preventDefault();
  10021. const payload = {
  10022. id: document.getElementById('modal-ospf-area-id').value,
  10023. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10024. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10025. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10026. area_type: document.getElementById('modal-ospf-area-type').value,
  10027. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10028. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10029. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10030. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10031. };
  10032. try {
  10033. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10034. method: 'POST',
  10035. headers: { 'Content-Type': 'application/json' },
  10036. body: JSON.stringify(payload)
  10037. });
  10038. if (res.ok) {
  10039. closeOspfAreaModal();
  10040. showToast('Saved', 'OSPF area saved', 'success');
  10041. loadDynamicRouting();
  10042. } else {
  10043. const err = await res.json();
  10044. showToast('Error', err.error || 'Failed to save area', 'error');
  10045. }
  10046. } catch (err) {
  10047. showToast('Error', err.message, 'error');
  10048. }
  10049. }
  10050. function applyOspfAreaForm() {
  10051. submitOspfArea(null);
  10052. }
  10053. function copyOspfArea() {
  10054. document.getElementById('modal-ospf-area-id').value = '';
  10055. document.getElementById('modal-ospf-area-name').value += '-copy';
  10056. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10057. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10058. }
  10059. async function deleteCurrentOspfArea() {
  10060. const id = document.getElementById('modal-ospf-area-id').value;
  10061. if (!id) return;
  10062. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10063. try {
  10064. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10065. if (res.ok) {
  10066. closeOspfAreaModal();
  10067. showToast('Removed', 'OSPF area deleted', 'success');
  10068. loadDynamicRouting();
  10069. }
  10070. } catch (err) {
  10071. showToast('Error', err.message, 'error');
  10072. }
  10073. }
  10074. async function enableSelectedOspfArea() {
  10075. const id = state.selectedOspfRow?.areas;
  10076. if (!id) return;
  10077. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10078. method: 'POST',
  10079. headers: { 'Content-Type': 'application/json' },
  10080. body: JSON.stringify({ disabled: false })
  10081. });
  10082. loadDynamicRouting();
  10083. }
  10084. async function disableSelectedOspfArea() {
  10085. const id = state.selectedOspfRow?.areas;
  10086. if (!id) return;
  10087. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10088. method: 'POST',
  10089. headers: { 'Content-Type': 'application/json' },
  10090. body: JSON.stringify({ disabled: true })
  10091. });
  10092. loadDynamicRouting();
  10093. }
  10094. async function removeSelectedOspfArea() {
  10095. const id = state.selectedOspfRow?.areas;
  10096. if (!id) return;
  10097. if (!confirm('Delete selected OSPF area?')) return;
  10098. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10099. loadDynamicRouting();
  10100. }
  10101. async function promptCommentOspfArea() {
  10102. const id = state.selectedOspfRow?.areas;
  10103. if (!id) return;
  10104. const area = (state.ospfAreas || []).find(a => a.id === id);
  10105. if (!area) return;
  10106. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10107. if (comment === null) return;
  10108. area.comment = comment;
  10109. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10110. method: 'POST',
  10111. headers: { 'Content-Type': 'application/json' },
  10112. body: JSON.stringify(area)
  10113. });
  10114. loadDynamicRouting();
  10115. }
  10116. // --- 3. OSPF AREA RANGE ---
  10117. function populateAreaRangeDropdowns() {
  10118. const select = document.getElementById('modal-ospf-range-area');
  10119. if (select) {
  10120. const cur = select.value;
  10121. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10122. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10123. if (cur) select.value = cur;
  10124. }
  10125. }
  10126. function openOspfAreaRangeModal(id = null) {
  10127. const isEdit = !!id;
  10128. populateAreaRangeDropdowns();
  10129. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10130. id: '',
  10131. area: 'Default',
  10132. prefix: '',
  10133. cost: 1,
  10134. advertise: true,
  10135. disabled: false,
  10136. comment: ''
  10137. };
  10138. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10139. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10140. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10141. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10142. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10143. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10144. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10145. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10146. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10147. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10148. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10149. }
  10150. function openEditOspfAreaRangeModal(id) {
  10151. openOspfAreaRangeModal(id);
  10152. }
  10153. function closeOspfAreaRangeModal() {
  10154. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10155. }
  10156. async function submitOspfAreaRange(e) {
  10157. if (e) e.preventDefault();
  10158. const payload = {
  10159. id: document.getElementById('modal-ospf-range-id').value,
  10160. area: document.getElementById('modal-ospf-range-area').value,
  10161. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10162. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10163. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10164. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10165. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10166. };
  10167. try {
  10168. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10169. method: 'POST',
  10170. headers: { 'Content-Type': 'application/json' },
  10171. body: JSON.stringify(payload)
  10172. });
  10173. if (res.ok) {
  10174. closeOspfAreaRangeModal();
  10175. showToast('Saved', 'Area range saved', 'success');
  10176. loadDynamicRouting();
  10177. } else {
  10178. const err = await res.json();
  10179. showToast('Error', err.error || 'Failed to save area range', 'error');
  10180. }
  10181. } catch (err) {
  10182. showToast('Error', err.message, 'error');
  10183. }
  10184. }
  10185. function applyOspfAreaRangeForm() {
  10186. submitOspfAreaRange(null);
  10187. }
  10188. async function deleteCurrentOspfAreaRange() {
  10189. const id = document.getElementById('modal-ospf-range-id').value;
  10190. if (!id) return;
  10191. if (!confirm('Delete this area range?')) return;
  10192. try {
  10193. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10194. closeOspfAreaRangeModal();
  10195. showToast('Removed', 'Area range removed', 'success');
  10196. loadDynamicRouting();
  10197. } catch (err) {
  10198. showToast('Error', err.message, 'error');
  10199. }
  10200. }
  10201. async function enableSelectedOspfAreaRange() {
  10202. const id = state.selectedOspfRow?.['area-ranges'];
  10203. if (!id) return;
  10204. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10205. if (!r) return;
  10206. r.disabled = false;
  10207. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10208. loadDynamicRouting();
  10209. }
  10210. async function disableSelectedOspfAreaRange() {
  10211. const id = state.selectedOspfRow?.['area-ranges'];
  10212. if (!id) return;
  10213. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10214. if (!r) return;
  10215. r.disabled = true;
  10216. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10217. loadDynamicRouting();
  10218. }
  10219. async function removeSelectedOspfAreaRange() {
  10220. const id = state.selectedOspfRow?.['area-ranges'];
  10221. if (!id) return;
  10222. if (!confirm('Delete selected area range?')) return;
  10223. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10224. loadDynamicRouting();
  10225. }
  10226. async function promptCommentOspfAreaRange() {
  10227. const id = state.selectedOspfRow?.['area-ranges'];
  10228. if (!id) return;
  10229. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10230. if (!r) return;
  10231. const comment = prompt('Enter comment for area range:', r.comment || '');
  10232. if (comment === null) return;
  10233. r.comment = comment;
  10234. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10235. loadDynamicRouting();
  10236. }
  10237. // --- 4. OSPF INTERFACE TEMPLATE ---
  10238. function switchOspfTemplateTab(tab) {
  10239. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10240. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10241. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10242. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10243. if (tab === 'general') {
  10244. if (tabGen) tabGen.classList.remove('hidden');
  10245. if (tabAuth) tabAuth.classList.add('hidden');
  10246. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10247. 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';
  10248. } else {
  10249. if (tabGen) tabGen.classList.add('hidden');
  10250. if (tabAuth) tabAuth.classList.remove('hidden');
  10251. 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';
  10252. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10253. }
  10254. }
  10255. function populateTemplateAreaDropdowns() {
  10256. const select = document.getElementById('modal-ospf-tmpl-area');
  10257. if (select) {
  10258. const cur = select.value;
  10259. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10260. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10261. if (cur) select.value = cur;
  10262. }
  10263. }
  10264. function openOspfTemplateModal(id = null) {
  10265. const isEdit = !!id;
  10266. populateTemplateAreaDropdowns();
  10267. switchOspfTemplateTab('general');
  10268. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10269. id: '',
  10270. interfaces: '',
  10271. area: 'Default',
  10272. networks: '',
  10273. network_type: 'broadcast',
  10274. cost: 1,
  10275. priority: 128,
  10276. passive: false,
  10277. hello_interval: 10,
  10278. dead_interval: 40,
  10279. auth: 'none',
  10280. auth_key: '',
  10281. disabled: false,
  10282. comment: ''
  10283. };
  10284. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10285. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10286. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10287. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10288. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10289. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10290. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10291. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10292. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10293. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10294. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10295. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10296. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10297. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10298. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10299. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10300. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10301. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10302. }
  10303. function openEditOspfTemplateModal(id) {
  10304. openOspfTemplateModal(id);
  10305. }
  10306. function closeOspfTemplateModal() {
  10307. document.getElementById('ospf-template-modal').classList.add('hidden');
  10308. }
  10309. async function submitOspfTemplate(e) {
  10310. if (e) e.preventDefault();
  10311. const payload = {
  10312. id: document.getElementById('modal-ospf-tmpl-id').value,
  10313. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10314. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10315. area: document.getElementById('modal-ospf-tmpl-area').value,
  10316. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10317. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10318. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10319. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10320. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10321. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10322. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10323. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10324. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10325. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10326. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10327. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10328. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10329. };
  10330. try {
  10331. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10332. method: 'POST',
  10333. headers: { 'Content-Type': 'application/json' },
  10334. body: JSON.stringify(payload)
  10335. });
  10336. if (res.ok) {
  10337. closeOspfTemplateModal();
  10338. showToast('Saved', 'Interface template saved', 'success');
  10339. loadDynamicRouting();
  10340. } else {
  10341. const err = await res.json();
  10342. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10343. }
  10344. } catch (err) {
  10345. showToast('Error', err.message, 'error');
  10346. }
  10347. }
  10348. function applyOspfTemplateForm() {
  10349. submitOspfTemplate(null);
  10350. }
  10351. function copyOspfTemplate() {
  10352. document.getElementById('modal-ospf-tmpl-id').value = '';
  10353. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10354. showToast('Copied', 'Duplicated as new template', 'info');
  10355. }
  10356. async function deleteCurrentOspfTemplate() {
  10357. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10358. if (!id) return;
  10359. if (!confirm('Delete this interface template?')) return;
  10360. try {
  10361. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10362. closeOspfTemplateModal();
  10363. showToast('Removed', 'Interface template deleted', 'success');
  10364. loadDynamicRouting();
  10365. } catch (err) {
  10366. showToast('Error', err.message, 'error');
  10367. }
  10368. }
  10369. async function enableSelectedOspfTemplate() {
  10370. const id = state.selectedOspfRow?.templates;
  10371. if (!id) return;
  10372. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10373. method: 'POST',
  10374. headers: { 'Content-Type': 'application/json' },
  10375. body: JSON.stringify({ disabled: false })
  10376. });
  10377. loadDynamicRouting();
  10378. }
  10379. async function disableSelectedOspfTemplate() {
  10380. const id = state.selectedOspfRow?.templates;
  10381. if (!id) return;
  10382. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10383. method: 'POST',
  10384. headers: { 'Content-Type': 'application/json' },
  10385. body: JSON.stringify({ disabled: true })
  10386. });
  10387. loadDynamicRouting();
  10388. }
  10389. async function removeSelectedOspfTemplate() {
  10390. const id = state.selectedOspfRow?.templates;
  10391. if (!id) return;
  10392. if (!confirm('Delete selected interface template?')) return;
  10393. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10394. loadDynamicRouting();
  10395. }
  10396. async function promptCommentOspfTemplate() {
  10397. const id = state.selectedOspfRow?.templates;
  10398. if (!id) return;
  10399. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10400. if (!tmpl) return;
  10401. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10402. if (comment === null) return;
  10403. tmpl.comment = comment;
  10404. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10405. method: 'POST',
  10406. headers: { 'Content-Type': 'application/json' },
  10407. body: JSON.stringify(tmpl)
  10408. });
  10409. loadDynamicRouting();
  10410. }
  10411. // --- 5. OSPF STATIC NEIGHBOR ---
  10412. function populateStaticNbrAreaDropdowns() {
  10413. const select = document.getElementById('modal-ospf-snbr-area');
  10414. if (select) {
  10415. const cur = select.value;
  10416. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10417. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10418. if (cur) select.value = cur;
  10419. }
  10420. }
  10421. function openOspfStaticNbrModal(id = null) {
  10422. const isEdit = !!id;
  10423. populateStaticNbrAreaDropdowns();
  10424. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10425. id: '',
  10426. address: '',
  10427. area: 'Default',
  10428. poll_interval: 120,
  10429. cost: 1,
  10430. disabled: false,
  10431. comment: ''
  10432. };
  10433. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10434. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10435. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10436. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10437. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10438. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10439. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10440. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10441. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10442. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10443. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10444. }
  10445. function openEditOspfStaticNbrModal(id) {
  10446. openOspfStaticNbrModal(id);
  10447. }
  10448. function closeOspfStaticNbrModal() {
  10449. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10450. }
  10451. async function submitOspfStaticNbr(e) {
  10452. if (e) e.preventDefault();
  10453. const payload = {
  10454. id: document.getElementById('modal-ospf-snbr-id').value,
  10455. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10456. area: document.getElementById('modal-ospf-snbr-area').value,
  10457. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10458. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10459. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10460. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10461. };
  10462. try {
  10463. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10464. method: 'POST',
  10465. headers: { 'Content-Type': 'application/json' },
  10466. body: JSON.stringify(payload)
  10467. });
  10468. if (res.ok) {
  10469. closeOspfStaticNbrModal();
  10470. showToast('Saved', 'Static neighbor saved', 'success');
  10471. loadDynamicRouting();
  10472. } else {
  10473. const err = await res.json();
  10474. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10475. }
  10476. } catch (err) {
  10477. showToast('Error', err.message, 'error');
  10478. }
  10479. }
  10480. function applyOspfStaticNbrForm() {
  10481. submitOspfStaticNbr(null);
  10482. }
  10483. async function deleteCurrentOspfStaticNbr() {
  10484. const id = document.getElementById('modal-ospf-snbr-id').value;
  10485. if (!id) return;
  10486. if (!confirm('Delete this static neighbor?')) return;
  10487. try {
  10488. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10489. closeOspfStaticNbrModal();
  10490. showToast('Removed', 'Static neighbor removed', 'success');
  10491. loadDynamicRouting();
  10492. } catch (err) {
  10493. showToast('Error', err.message, 'error');
  10494. }
  10495. }
  10496. async function enableSelectedOspfStaticNbr() {
  10497. const id = state.selectedOspfRow?.['static-nbrs'];
  10498. if (!id) return;
  10499. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10500. if (!n) return;
  10501. n.disabled = false;
  10502. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10503. loadDynamicRouting();
  10504. }
  10505. async function disableSelectedOspfStaticNbr() {
  10506. const id = state.selectedOspfRow?.['static-nbrs'];
  10507. if (!id) return;
  10508. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10509. if (!n) return;
  10510. n.disabled = true;
  10511. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10512. loadDynamicRouting();
  10513. }
  10514. async function removeSelectedOspfStaticNbr() {
  10515. const id = state.selectedOspfRow?.['static-nbrs'];
  10516. if (!id) return;
  10517. if (!confirm('Delete selected static neighbor?')) return;
  10518. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10519. loadDynamicRouting();
  10520. }
  10521. async function promptCommentOspfStaticNbr() {
  10522. const id = state.selectedOspfRow?.['static-nbrs'];
  10523. if (!id) return;
  10524. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10525. if (!n) return;
  10526. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10527. if (comment === null) return;
  10528. n.comment = comment;
  10529. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10530. loadDynamicRouting();
  10531. }
  10532. // Backward-compat aliases
  10533. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10534. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10535. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10536. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10537. function deleteOspfInterface(id) {
  10538. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10539. }
  10540. function toggleOspfInterfaceState(id, disabled) {
  10541. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10542. method: 'POST',
  10543. headers: { 'Content-Type': 'application/json' },
  10544. body: JSON.stringify({ disabled })
  10545. }).then(() => loadDynamicRouting());
  10546. }
  10547. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10548. function deleteOspfArea(id) {
  10549. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10550. }
  10551. // ============================================================================
  10552. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10553. // ============================================================================
  10554. function switchBridgeSubTab(tab) {
  10555. state.bridgeSubTab = tab;
  10556. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10557. tabs.forEach(t => {
  10558. const panel = document.getElementById(`bridge-subtab-${t}`);
  10559. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10560. if (panel) {
  10561. if (t === tab) panel.classList.remove('hidden');
  10562. else panel.classList.add('hidden');
  10563. }
  10564. if (btn) {
  10565. if (t === tab) {
  10566. 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';
  10567. } else {
  10568. 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';
  10569. }
  10570. }
  10571. });
  10572. const addBtn = document.getElementById('bridge-top-action-btn');
  10573. if (addBtn) {
  10574. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10575. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10576. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10577. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10578. }
  10579. if (tab === 'hosts') loadBridgeHosts();
  10580. setTimeout(initTableSorting, 50);
  10581. }
  10582. function openCurrentBridgeModal() {
  10583. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10584. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10585. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10586. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10587. }
  10588. async function loadBridge() {
  10589. try {
  10590. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10591. fetch(`${API_BASE}/bridge/bridges`),
  10592. fetch(`${API_BASE}/bridge/ports`),
  10593. fetch(`${API_BASE}/bridge/vlans`),
  10594. fetch(`${API_BASE}/bridge/summary`),
  10595. fetch(`${API_BASE}/vpn/eoip`),
  10596. fetch(`${API_BASE}/vpn/vxlan`),
  10597. fetch(`${API_BASE}/vlans`)
  10598. ]);
  10599. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10600. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10601. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10602. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10603. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10604. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10605. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10606. // Badges & Stats
  10607. const bBridges = document.getElementById('bridge-badge-bridges');
  10608. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10609. const bPorts = document.getElementById('bridge-badge-ports');
  10610. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10611. const bVlans = document.getElementById('bridge-badge-vlans');
  10612. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10613. const bHosts = document.getElementById('bridge-badge-hosts');
  10614. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10615. const sBr = document.getElementById('bridge-stat-bridges');
  10616. if (sBr) sBr.innerText = (state.bridges || []).length;
  10617. const sPorts = document.getElementById('bridge-stat-ports');
  10618. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10619. const sHosts = document.getElementById('bridge-stat-hosts');
  10620. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10621. renderBridges();
  10622. renderBridgePorts();
  10623. renderBridgeVLANs();
  10624. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10625. } catch (err) {
  10626. console.error('Failed to load bridge subsystem:', err);
  10627. }
  10628. }
  10629. // ----------------- Bridges -----------------
  10630. function renderBridges() {
  10631. const tbody = document.getElementById('bridge-table-body');
  10632. const empty = document.getElementById('bridge-empty-bridges');
  10633. const countBadge = document.getElementById('bridge-count-badge');
  10634. if (!tbody) return;
  10635. tbody.innerHTML = '';
  10636. const bridges = state.bridges || [];
  10637. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10638. if (bridges.length === 0) {
  10639. empty?.classList.remove('hidden');
  10640. return;
  10641. }
  10642. empty?.classList.add('hidden');
  10643. bridges.forEach((b, idx) => {
  10644. const tr = document.createElement('tr');
  10645. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10646. // Format IP addresses pill list
  10647. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10648. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10649. ipsHtml = b.ip_addresses.map(ip => `
  10650. <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">
  10651. <span>${ip}</span>
  10652. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10653. </span>
  10654. `).join(' ');
  10655. }
  10656. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10657. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10658. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10659. tr.innerHTML = `
  10660. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10661. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10662. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10663. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10664. </td>
  10665. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10666. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10667. <td class="py-2.5 px-3">
  10668. <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>
  10669. </td>
  10670. <td class="py-2.5 px-3 text-center">
  10671. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10672. </td>
  10673. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10674. <td class="py-2.5 px-3">
  10675. <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>
  10676. </td>
  10677. <td class="py-2.5 px-3">
  10678. <div class="flex items-center gap-1.5 flex-wrap">
  10679. ${ipsHtml}
  10680. <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>
  10681. </div>
  10682. </td>
  10683. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10684. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10685. </td>
  10686. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10687. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10688. <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>
  10689. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10690. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10691. </td>
  10692. `;
  10693. tbody.appendChild(tr);
  10694. });
  10695. }
  10696. function openAddBridgeModal() {
  10697. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10698. document.getElementById('bridge-modal-id').value = '';
  10699. document.getElementById('bridge-modal-name').value = 'bridge1';
  10700. document.getElementById('bridge-modal-name').disabled = false;
  10701. document.getElementById('bridge-modal-mtu').value = '1500';
  10702. document.getElementById('bridge-modal-mac').value = '';
  10703. document.getElementById('bridge-modal-stp').value = 'stp';
  10704. document.getElementById('bridge-modal-priority').value = '32768';
  10705. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10706. document.getElementById('bridge-modal-pvid').value = '1';
  10707. document.getElementById('bridge-modal-fastforward').checked = true;
  10708. document.getElementById('bridge-modal-comment').value = '';
  10709. document.getElementById('bridge-modal-disabled').checked = false;
  10710. toggleBridgeModalVlanFiltering();
  10711. document.getElementById('bridge-modal').classList.remove('hidden');
  10712. }
  10713. function openEditBridgeModal(id) {
  10714. const b = (state.bridges || []).find(x => x.id === id);
  10715. if (!b) return;
  10716. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10717. document.getElementById('bridge-modal-id').value = b.id;
  10718. document.getElementById('bridge-modal-name').value = b.name;
  10719. document.getElementById('bridge-modal-name').disabled = true;
  10720. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10721. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10722. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10723. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10724. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10725. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10726. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10727. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10728. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10729. toggleBridgeModalVlanFiltering();
  10730. document.getElementById('bridge-modal').classList.remove('hidden');
  10731. }
  10732. function closeBridgeModal() {
  10733. document.getElementById('bridge-modal').classList.add('hidden');
  10734. }
  10735. function toggleBridgeModalVlanFiltering() {
  10736. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10737. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10738. if (pvidBox) {
  10739. if (chk) pvidBox.classList.remove('opacity-40');
  10740. else pvidBox.classList.add('opacity-40');
  10741. }
  10742. }
  10743. async function submitSaveBridge(e) {
  10744. e.preventDefault();
  10745. const id = document.getElementById('bridge-modal-id').value;
  10746. const name = document.getElementById('bridge-modal-name').value.trim();
  10747. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10748. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10749. const stp = document.getElementById('bridge-modal-stp').value;
  10750. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10751. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10752. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10753. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10754. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10755. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10756. try {
  10757. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10758. method: 'POST',
  10759. headers: { 'Content-Type': 'application/json' },
  10760. body: JSON.stringify({
  10761. id,
  10762. name,
  10763. mtu,
  10764. mac_address: mac,
  10765. stp,
  10766. priority,
  10767. vlan_filtering: vlanFiltering,
  10768. pvid,
  10769. fast_forward: fastForward,
  10770. comment,
  10771. disabled
  10772. })
  10773. });
  10774. if (res.ok) {
  10775. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10776. closeBridgeModal();
  10777. loadBridge();
  10778. fetchData(false);
  10779. } else {
  10780. const err = await res.json();
  10781. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10782. }
  10783. } catch (err) {
  10784. showToast('Error', err.message, 'error');
  10785. }
  10786. }
  10787. async function toggleBridgeState(id, disabled) {
  10788. try {
  10789. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10790. method: 'POST',
  10791. headers: { 'Content-Type': 'application/json' },
  10792. body: JSON.stringify({ disabled })
  10793. });
  10794. if (res.ok) {
  10795. loadBridge();
  10796. fetchData(false);
  10797. }
  10798. } catch (err) {
  10799. showToast('Error', err.message, 'error');
  10800. }
  10801. }
  10802. async function deleteBridge(id) {
  10803. const b = (state.bridges || []).find(x => x.id === id);
  10804. const name = b ? b.name : id;
  10805. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10806. try {
  10807. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10808. if (res.ok) {
  10809. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10810. loadBridge();
  10811. fetchData(false);
  10812. } else {
  10813. const err = await res.json();
  10814. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10815. }
  10816. } catch (err) {
  10817. showToast('Error', err.message, 'error');
  10818. }
  10819. }
  10820. // ----------------- Bridge IP Assignments -----------------
  10821. function openAddBridgeIPModal(id, name) {
  10822. document.getElementById('bridge-ip-modal-id').value = id;
  10823. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10824. document.getElementById('bridge-ip-modal-cidr').value = '';
  10825. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10826. }
  10827. function closeBridgeIPModal() {
  10828. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10829. }
  10830. async function submitAddBridgeIP(e) {
  10831. e.preventDefault();
  10832. const id = document.getElementById('bridge-ip-modal-id').value;
  10833. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10834. try {
  10835. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10836. method: 'POST',
  10837. headers: { 'Content-Type': 'application/json' },
  10838. body: JSON.stringify({ ip })
  10839. });
  10840. if (res.ok) {
  10841. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10842. closeBridgeIPModal();
  10843. loadBridge();
  10844. fetchData(false);
  10845. } else {
  10846. const err = await res.json();
  10847. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10848. }
  10849. } catch (err) {
  10850. showToast('Error', err.message, 'error');
  10851. }
  10852. }
  10853. async function deleteBridgeIP(id, ip) {
  10854. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10855. try {
  10856. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10857. method: 'DELETE',
  10858. headers: { 'Content-Type': 'application/json' },
  10859. body: JSON.stringify({ ip })
  10860. });
  10861. if (res.ok) {
  10862. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10863. loadBridge();
  10864. fetchData(false);
  10865. }
  10866. } catch (err) {
  10867. showToast('Error', err.message, 'error');
  10868. }
  10869. }
  10870. // ----------------- Bridge Ports -----------------
  10871. function renderBridgePorts() {
  10872. const tbody = document.getElementById('bridge-ports-table-body');
  10873. const empty = document.getElementById('bridge-empty-ports');
  10874. const countBadge = document.getElementById('bridge-ports-count-badge');
  10875. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10876. if (!tbody) return;
  10877. tbody.innerHTML = '';
  10878. // Update filter select
  10879. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10880. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10881. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10882. if (ports.length === 0) {
  10883. empty?.classList.remove('hidden');
  10884. return;
  10885. }
  10886. empty?.classList.add('hidden');
  10887. ports.forEach((p, idx) => {
  10888. const tr = document.createElement('tr');
  10889. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10890. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10891. tr.innerHTML = `
  10892. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10893. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10894. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10895. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10896. </td>
  10897. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10898. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10899. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10900. <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>
  10901. <td class="py-2.5 px-3">
  10902. ${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>'}
  10903. </td>
  10904. <td class="py-2.5 px-3">
  10905. <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>
  10906. </td>
  10907. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10908. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10909. <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>
  10910. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10911. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10912. </td>
  10913. `;
  10914. tbody.appendChild(tr);
  10915. });
  10916. }
  10917. function openAddBridgePortModal() {
  10918. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10919. document.getElementById('bridge-port-modal-id').value = '';
  10920. populateBridgeSelect('bridge-port-modal-bridge');
  10921. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10922. document.getElementById('bridge-port-modal-pvid').value = '1';
  10923. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10924. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10925. document.getElementById('bridge-port-modal-horizon').value = '0';
  10926. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10927. document.getElementById('bridge-port-modal-priority').value = '128';
  10928. document.getElementById('bridge-port-modal-learn').checked = true;
  10929. document.getElementById('bridge-port-modal-comment').value = '';
  10930. document.getElementById('bridge-port-modal-disabled').checked = false;
  10931. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10932. }
  10933. function openEditBridgePortModal(id) {
  10934. const p = (state.bridgePorts || []).find(x => x.id === id);
  10935. if (!p) return;
  10936. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10937. document.getElementById('bridge-port-modal-id').value = p.id;
  10938. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10939. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10940. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10941. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10942. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10943. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10944. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10945. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10946. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10947. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10948. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10949. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10950. }
  10951. function closeBridgePortModal() {
  10952. document.getElementById('bridge-port-modal').classList.add('hidden');
  10953. }
  10954. async function submitSaveBridgePort(e) {
  10955. e.preventDefault();
  10956. const id = document.getElementById('bridge-port-modal-id').value;
  10957. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10958. const iface = document.getElementById('bridge-port-modal-interface').value;
  10959. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10960. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10961. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10962. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10963. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10964. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10965. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10966. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10967. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10968. try {
  10969. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10970. method: 'POST',
  10971. headers: { 'Content-Type': 'application/json' },
  10972. body: JSON.stringify({
  10973. id,
  10974. bridge,
  10975. interface: iface,
  10976. pvid,
  10977. frame_types: frameTypes,
  10978. ingress_filtering: ingressFiltering,
  10979. horizon,
  10980. path_cost: pathCost,
  10981. priority,
  10982. learn,
  10983. comment,
  10984. disabled
  10985. })
  10986. });
  10987. if (res.ok) {
  10988. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10989. closeBridgePortModal();
  10990. loadBridge();
  10991. fetchData(false);
  10992. } else {
  10993. const err = await res.json();
  10994. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10995. }
  10996. } catch (err) {
  10997. showToast('Error', err.message, 'error');
  10998. }
  10999. }
  11000. async function toggleBridgePortState(id, disabled) {
  11001. try {
  11002. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11003. method: 'POST',
  11004. headers: { 'Content-Type': 'application/json' },
  11005. body: JSON.stringify({ disabled })
  11006. });
  11007. if (res.ok) {
  11008. loadBridge();
  11009. fetchData(false);
  11010. }
  11011. } catch (err) {
  11012. showToast('Error', err.message, 'error');
  11013. }
  11014. }
  11015. async function deleteBridgePort(id) {
  11016. const p = (state.bridgePorts || []).find(x => x.id === id);
  11017. const iface = p ? p.interface : id;
  11018. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11019. try {
  11020. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11021. if (res.ok) {
  11022. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11023. loadBridge();
  11024. fetchData(false);
  11025. }
  11026. } catch (err) {
  11027. showToast('Error', err.message, 'error');
  11028. }
  11029. }
  11030. // ----------------- Bridge VLANs -----------------
  11031. function renderBridgeVLANs() {
  11032. const tbody = document.getElementById('bridge-vlans-table-body');
  11033. const empty = document.getElementById('bridge-empty-vlans');
  11034. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11035. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11036. if (!tbody) return;
  11037. tbody.innerHTML = '';
  11038. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11039. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11040. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11041. if (vlans.length === 0) {
  11042. empty?.classList.remove('hidden');
  11043. return;
  11044. }
  11045. empty?.classList.add('hidden');
  11046. vlans.forEach((v, idx) => {
  11047. const tr = document.createElement('tr');
  11048. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11049. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11050. ? 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(' ')
  11051. : '<span class="text-slate-600">none</span>';
  11052. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11053. ? 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(' ')
  11054. : '<span class="text-slate-600">none</span>';
  11055. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11056. tr.innerHTML = `
  11057. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11058. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11059. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11060. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11061. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11062. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11063. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11064. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11065. <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>
  11066. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11067. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11068. </td>
  11069. `;
  11070. tbody.appendChild(tr);
  11071. });
  11072. }
  11073. function openAddBridgeVLANModal() {
  11074. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11075. document.getElementById('bridge-vlan-modal-id').value = '';
  11076. populateBridgeSelect('bridge-vlan-modal-bridge');
  11077. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11078. document.getElementById('bridge-vlan-modal-comment').value = '';
  11079. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11080. updateBridgeVlanPortCheckboxes();
  11081. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11082. }
  11083. function openEditBridgeVLANModal(id) {
  11084. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11085. if (!v) return;
  11086. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11087. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11088. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11089. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11090. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11091. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11092. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11093. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11094. }
  11095. function closeBridgeVlanModal() {
  11096. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11097. }
  11098. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11099. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11100. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11101. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11102. if (!taggedBox || !untaggedBox) return;
  11103. // Ports belonging to the selected bridge
  11104. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11105. if (memberPorts.length === 0) {
  11106. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11107. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11108. return;
  11109. }
  11110. taggedBox.innerHTML = memberPorts.map(p => `
  11111. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11112. <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">
  11113. <span>${p.interface}</span>
  11114. </label>
  11115. `).join('');
  11116. untaggedBox.innerHTML = memberPorts.map(p => `
  11117. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11118. <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">
  11119. <span>${p.interface}</span>
  11120. </label>
  11121. `).join('');
  11122. }
  11123. async function submitSaveBridgeVLAN(e) {
  11124. e.preventDefault();
  11125. const id = document.getElementById('bridge-vlan-modal-id').value;
  11126. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11127. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11128. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11129. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11130. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11131. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11132. try {
  11133. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11134. method: 'POST',
  11135. headers: { 'Content-Type': 'application/json' },
  11136. body: JSON.stringify({
  11137. id,
  11138. bridge,
  11139. vlan_ids: vlanIDs,
  11140. tagged,
  11141. untagged,
  11142. comment,
  11143. disabled
  11144. })
  11145. });
  11146. if (res.ok) {
  11147. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11148. closeBridgeVlanModal();
  11149. loadBridge();
  11150. } else {
  11151. const err = await res.json();
  11152. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11153. }
  11154. } catch (err) {
  11155. showToast('Error', err.message, 'error');
  11156. }
  11157. }
  11158. async function toggleBridgeVLANState(id, disabled) {
  11159. try {
  11160. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11161. method: 'POST',
  11162. headers: { 'Content-Type': 'application/json' },
  11163. body: JSON.stringify({ disabled })
  11164. });
  11165. if (res.ok) loadBridge();
  11166. } catch (err) {
  11167. showToast('Error', err.message, 'error');
  11168. }
  11169. }
  11170. async function deleteBridgeVLAN(id) {
  11171. if (!confirm('Delete this bridge VLAN entry?')) return;
  11172. try {
  11173. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11174. if (res.ok) {
  11175. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11176. loadBridge();
  11177. }
  11178. } catch (err) {
  11179. showToast('Error', err.message, 'error');
  11180. }
  11181. }
  11182. // ----------------- Hosts / MAC Table -----------------
  11183. async function loadBridgeHosts() {
  11184. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11185. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11186. try {
  11187. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11188. const res = await fetch(url);
  11189. if (res.ok) {
  11190. state.bridgeHosts = await res.json();
  11191. renderBridgeHosts();
  11192. }
  11193. } catch (err) {
  11194. console.error('Failed to load bridge hosts:', err);
  11195. }
  11196. }
  11197. function renderBridgeHosts() {
  11198. const tbody = document.getElementById('bridge-hosts-table-body');
  11199. const empty = document.getElementById('bridge-empty-hosts');
  11200. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11201. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11202. if (!tbody) return;
  11203. tbody.innerHTML = '';
  11204. const hosts = (state.bridgeHosts || []).filter(h => {
  11205. if (!search) return true;
  11206. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11207. });
  11208. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11209. if (hosts.length === 0) {
  11210. empty?.classList.remove('hidden');
  11211. return;
  11212. }
  11213. empty?.classList.add('hidden');
  11214. hosts.forEach(h => {
  11215. const tr = document.createElement('tr');
  11216. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11217. let flagBadges = '';
  11218. 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>';
  11219. 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>';
  11220. 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>';
  11221. tr.innerHTML = `
  11222. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11223. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11224. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11225. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11226. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11227. <td class="py-2.5 px-3">${flagBadges}</td>
  11228. `;
  11229. tbody.appendChild(tr);
  11230. });
  11231. }
  11232. async function flushBridgeHosts() {
  11233. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11234. if (!selBridge) {
  11235. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11236. return;
  11237. }
  11238. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11239. try {
  11240. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11241. method: 'POST',
  11242. headers: { 'Content-Type': 'application/json' },
  11243. body: JSON.stringify({ bridge: selBridge })
  11244. });
  11245. if (res.ok) {
  11246. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11247. loadBridgeHosts();
  11248. }
  11249. } catch (err) {
  11250. showToast('Error', err.message, 'error');
  11251. }
  11252. }
  11253. // ----------------- Helpers -----------------
  11254. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11255. const sel = document.getElementById(selectId);
  11256. if (!sel) return;
  11257. const prevVal = currentVal || sel.value;
  11258. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11259. (state.bridges || []).forEach(b => {
  11260. const opt = document.createElement('option');
  11261. opt.value = b.name;
  11262. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11263. if (b.name === prevVal) opt.selected = true;
  11264. sel.appendChild(opt);
  11265. });
  11266. }
  11267. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11268. const sel = document.getElementById(selectId);
  11269. if (!sel) return;
  11270. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11271. // 1. Physical Interfaces
  11272. const grpPhys = document.createElement('optgroup');
  11273. grpPhys.label = 'Physical Interfaces';
  11274. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11275. const opt = document.createElement('option');
  11276. opt.value = i.name;
  11277. opt.innerText = `${i.name} (${i.role || i.type})`;
  11278. if (i.name === currentVal) opt.selected = true;
  11279. grpPhys.appendChild(opt);
  11280. });
  11281. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11282. // 2. VLAN Sub-interfaces
  11283. const grpVlans = document.createElement('optgroup');
  11284. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11285. (state.vlans || []).forEach(v => {
  11286. const opt = document.createElement('option');
  11287. opt.value = v.name;
  11288. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11289. if (v.name === currentVal) opt.selected = true;
  11290. grpVlans.appendChild(opt);
  11291. });
  11292. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11293. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11294. const grpEoip = document.createElement('optgroup');
  11295. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11296. (state.eoipTunnels || []).forEach(t => {
  11297. const opt = document.createElement('option');
  11298. opt.value = t.name;
  11299. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11300. if (t.name === currentVal) opt.selected = true;
  11301. grpEoip.appendChild(opt);
  11302. });
  11303. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11304. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11305. const grpVxlan = document.createElement('optgroup');
  11306. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11307. (state.vxlanTunnels || []).forEach(t => {
  11308. const opt = document.createElement('option');
  11309. opt.value = t.name;
  11310. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11311. if (t.name === currentVal) opt.selected = true;
  11312. grpVxlan.appendChild(opt);
  11313. });
  11314. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11315. }
  11316. // -------------------------------------------------------------
  11317. // DebTik Routing Filters Management (/routing filter)
  11318. // -------------------------------------------------------------
  11319. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11320. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11321. if (!state.rfSort) state.rfSort = {};
  11322. function switchRoutingFilterTab(tab) {
  11323. state.activeRoutingFilterTab = tab;
  11324. const tabs = ['rules', 'community-lists', 'as-lists'];
  11325. tabs.forEach(t => {
  11326. const btn = document.getElementById(`tab-rf-${t}`);
  11327. const content = document.getElementById(`tab-content-rf-${t}`);
  11328. if (btn) {
  11329. if (t === tab) {
  11330. 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';
  11331. } else {
  11332. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11333. }
  11334. }
  11335. if (content) {
  11336. if (t === tab) content.classList.remove('hidden');
  11337. else content.classList.add('hidden');
  11338. }
  11339. });
  11340. const chainContainer = document.getElementById('rf-chain-filter-container');
  11341. if (chainContainer) {
  11342. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11343. else chainContainer.classList.add('hidden');
  11344. }
  11345. renderRoutingFilters();
  11346. }
  11347. function selectFilterRow(tab, id) {
  11348. if (state.selectedFilterRow[tab] === id) {
  11349. delete state.selectedFilterRow[tab];
  11350. } else {
  11351. state.selectedFilterRow[tab] = id;
  11352. }
  11353. if (tab === 'rules') renderRoutingFilterRules();
  11354. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11355. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11356. }
  11357. function openRoutingFilterNewModal() {
  11358. const tab = state.activeRoutingFilterTab || 'rules';
  11359. if (tab === 'rules') openAddRoutingFilterModal();
  11360. else if (tab === 'community-lists') openAddCommunityListModal();
  11361. else if (tab === 'as-lists') openAddASListModal();
  11362. }
  11363. function toggleSelectedRoutingFilter(disabled) {
  11364. const tab = state.activeRoutingFilterTab || 'rules';
  11365. const id = state.selectedFilterRow[tab];
  11366. if (!id) {
  11367. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11368. return;
  11369. }
  11370. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11371. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11372. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11373. }
  11374. function removeSelectedRoutingFilter() {
  11375. const tab = state.activeRoutingFilterTab || 'rules';
  11376. const id = state.selectedFilterRow[tab];
  11377. if (!id) {
  11378. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11379. return;
  11380. }
  11381. if (tab === 'rules') deleteRoutingFilter(id);
  11382. else if (tab === 'community-lists') deleteCommunityList(id);
  11383. else if (tab === 'as-lists') deleteASList(id);
  11384. }
  11385. function searchRoutingFilters(q) {
  11386. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11387. renderRoutingFilters();
  11388. }
  11389. function sortFilterTable(tab, col) {
  11390. if (!state.rfSort) state.rfSort = {};
  11391. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11392. if (state.rfSort[tab].col === col) {
  11393. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11394. } else {
  11395. state.rfSort[tab].col = col;
  11396. state.rfSort[tab].asc = true;
  11397. }
  11398. const asc = state.rfSort[tab].asc;
  11399. let list = [];
  11400. if (tab === 'rules') list = state.routingFilters || [];
  11401. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11402. else if (tab === 'as-lists') list = state.routingASLists || [];
  11403. list.sort((a, b) => {
  11404. let valA = a[col] ?? '';
  11405. let valB = b[col] ?? '';
  11406. if (col === 'flags') {
  11407. valA = a.disabled ? 'X' : 'A';
  11408. valB = b.disabled ? 'X' : 'A';
  11409. }
  11410. if (typeof valA === 'number' && typeof valB === 'number') {
  11411. return asc ? valA - valB : valB - valA;
  11412. }
  11413. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11414. });
  11415. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11416. allCols.forEach(c => {
  11417. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11418. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11419. });
  11420. if (tab === 'rules') renderRoutingFilterRules();
  11421. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11422. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11423. }
  11424. function renderRoutingFilters() {
  11425. const navBadge = document.getElementById('badge-filters-count');
  11426. const allRules = state.routingFilters || [];
  11427. if (navBadge) navBadge.innerText = allRules.length;
  11428. // Populate chain filter select options and datalist
  11429. const chainSelect = document.getElementById('routing-filter-chain-select');
  11430. const chainDatalist = document.getElementById('dl-routing-chains');
  11431. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11432. if (chainSelect) {
  11433. const currentVal = state.filterChainSelected || 'all';
  11434. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11435. uniqueChains.map(ch => {
  11436. const count = allRules.filter(r => r.chain === ch).length;
  11437. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11438. }).join('');
  11439. chainSelect.value = currentVal;
  11440. }
  11441. if (chainDatalist) {
  11442. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11443. }
  11444. renderRoutingFilterRules();
  11445. renderRoutingFilterCommunityLists();
  11446. renderRoutingFilterASLists();
  11447. }
  11448. function filterRoutingFiltersByChain(chain) {
  11449. state.filterChainSelected = chain;
  11450. renderRoutingFilters();
  11451. }
  11452. // -------------------------------------------------------------
  11453. // TAB 1: RULES (/routing filter rule)
  11454. // -------------------------------------------------------------
  11455. function renderRoutingFilterRules() {
  11456. const tbody = document.getElementById('routing-filter-rules-tbody');
  11457. if (!tbody) return;
  11458. const empty = document.getElementById('rf-rules-empty');
  11459. const statusCount = document.getElementById('rf-status-count');
  11460. let list = (state.routingFilters || []).slice();
  11461. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11462. list = list.filter(r => r.chain === state.filterChainSelected);
  11463. }
  11464. const q = state.rfSearchQuery;
  11465. if (q) {
  11466. list = list.filter(r =>
  11467. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11468. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11469. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11470. (r.comment && r.comment.toLowerCase().includes(q))
  11471. );
  11472. }
  11473. if (!state.rfSort?.['rules']) {
  11474. list.sort((a, b) => {
  11475. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11476. return (a.rule_order || 0) - (b.rule_order || 0);
  11477. });
  11478. }
  11479. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11480. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11481. }
  11482. if (list.length === 0) {
  11483. tbody.innerHTML = '';
  11484. if (empty) empty.classList.remove('hidden');
  11485. return;
  11486. }
  11487. if (empty) empty.classList.add('hidden');
  11488. tbody.innerHTML = list.map(r => {
  11489. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11490. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11491. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11492. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11493. let ruleDisplay = '';
  11494. if (r.rule && r.rule.trim() !== '') {
  11495. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11496. } else {
  11497. let conds = [];
  11498. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11499. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11500. let act = r.action || 'accept';
  11501. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11502. }
  11503. return `
  11504. <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'}">
  11505. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11506. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11507. <td class="py-2 px-3">
  11508. <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>
  11509. </td>
  11510. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11511. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11512. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11513. <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>
  11514. <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>
  11515. <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'}">
  11516. ${r.disabled ? 'Enable' : 'Disable'}
  11517. </button>
  11518. <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">
  11519. Edit
  11520. </button>
  11521. <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">
  11522. ✕
  11523. </button>
  11524. </td>
  11525. </tr>
  11526. `;
  11527. }).join('');
  11528. }
  11529. // -------------------------------------------------------------
  11530. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11531. // -------------------------------------------------------------
  11532. function renderRoutingFilterCommunityLists() {
  11533. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11534. if (!tbody) return;
  11535. const empty = document.getElementById('rf-comm-lists-empty');
  11536. const statusCount = document.getElementById('rf-status-count');
  11537. let list = (state.routingCommunityLists || []).slice();
  11538. const q = state.rfSearchQuery;
  11539. if (q) {
  11540. list = list.filter(cl =>
  11541. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11542. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11543. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11544. );
  11545. }
  11546. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11547. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11548. }
  11549. if (list.length === 0) {
  11550. tbody.innerHTML = '';
  11551. if (empty) empty.classList.remove('hidden');
  11552. return;
  11553. }
  11554. if (empty) empty.classList.add('hidden');
  11555. tbody.innerHTML = list.map(cl => {
  11556. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11557. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11558. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11559. const commBadges = (cl.communities || []).map(c =>
  11560. `<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>`
  11561. ).join(' ');
  11562. return `
  11563. <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'}">
  11564. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11565. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11566. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11567. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11568. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11569. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11570. <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'}">
  11571. ${cl.disabled ? 'Enable' : 'Disable'}
  11572. </button>
  11573. <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">
  11574. Edit
  11575. </button>
  11576. <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">
  11577. ✕
  11578. </button>
  11579. </td>
  11580. </tr>
  11581. `;
  11582. }).join('');
  11583. }
  11584. // -------------------------------------------------------------
  11585. // TAB 4: AS LISTS (/routing filter num-list)
  11586. // -------------------------------------------------------------
  11587. function renderRoutingFilterASLists() {
  11588. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11589. if (!tbody) return;
  11590. const empty = document.getElementById('rf-as-lists-empty');
  11591. const statusCount = document.getElementById('rf-status-count');
  11592. let list = (state.routingASLists || []).slice();
  11593. const q = state.rfSearchQuery;
  11594. if (q) {
  11595. list = list.filter(al =>
  11596. (al.name && al.name.toLowerCase().includes(q)) ||
  11597. (al.range && al.range.toLowerCase().includes(q)) ||
  11598. (al.comment && al.comment.toLowerCase().includes(q))
  11599. );
  11600. }
  11601. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11602. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11603. }
  11604. if (list.length === 0) {
  11605. tbody.innerHTML = '';
  11606. if (empty) empty.classList.remove('hidden');
  11607. return;
  11608. }
  11609. if (empty) empty.classList.add('hidden');
  11610. tbody.innerHTML = list.map(al => {
  11611. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11612. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11613. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11614. return `
  11615. <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'}">
  11616. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11617. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11618. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11619. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11620. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11621. <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'}">
  11622. ${al.disabled ? 'Enable' : 'Disable'}
  11623. </button>
  11624. <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">
  11625. Edit
  11626. </button>
  11627. <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">
  11628. ✕
  11629. </button>
  11630. </td>
  11631. </tr>
  11632. `;
  11633. }).join('');
  11634. }
  11635. // -------------------------------------------------------------
  11636. // SNIPPETS & WIZARD HELPERS
  11637. // -------------------------------------------------------------
  11638. function insertRuleSnippet(type) {
  11639. const textarea = document.getElementById('modal-rf-rule');
  11640. if (!textarea) return;
  11641. let snippet = '';
  11642. switch (type) {
  11643. case 'accept-default':
  11644. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11645. break;
  11646. case 'drop-rfc1918':
  11647. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11648. break;
  11649. case 'len-24':
  11650. snippet = 'if (dst-len > 24) { reject; }';
  11651. break;
  11652. case 'local-pref-150':
  11653. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11654. break;
  11655. case 'as-prepend-2':
  11656. snippet = 'set bgp-path-prepend 2; accept;';
  11657. break;
  11658. case 'set-comm':
  11659. snippet = 'set bgp-communities.add 65000:100; accept;';
  11660. break;
  11661. case 'match-comm':
  11662. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11663. break;
  11664. case 'reject-all':
  11665. snippet = 'reject;';
  11666. break;
  11667. }
  11668. if (!snippet) return;
  11669. if (!textarea.value.trim()) {
  11670. textarea.value = snippet;
  11671. } else {
  11672. textarea.value = textarea.value.trim() + '\n' + snippet;
  11673. }
  11674. }
  11675. function generateScriptFromWizard() {
  11676. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11677. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11678. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11679. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11680. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11681. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11682. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11683. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11684. const conds = [];
  11685. if (pfx) {
  11686. if (pfxLen) {
  11687. if (pfxLen.includes('-')) {
  11688. const parts = pfxLen.split('-');
  11689. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11690. } else {
  11691. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11692. }
  11693. } else {
  11694. conds.push(`dst in ${pfx}`);
  11695. }
  11696. }
  11697. if (proto && proto !== 'any') {
  11698. conds.push(`protocol ${proto}`);
  11699. }
  11700. if (asp) {
  11701. conds.push(`bgp-as-path "${asp}"`);
  11702. }
  11703. if (comm) {
  11704. conds.push(`bgp-communities includes ${comm}`);
  11705. }
  11706. const actions = [];
  11707. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11708. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11709. if (act && act !== 'passthrough') {
  11710. actions.push(`${act};`);
  11711. }
  11712. let code = '';
  11713. if (conds.length > 0) {
  11714. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11715. } else {
  11716. code = actions.join(' ');
  11717. }
  11718. const textarea = document.getElementById('modal-rf-rule');
  11719. if (textarea) textarea.value = code;
  11720. }
  11721. // -------------------------------------------------------------
  11722. // MODAL CRUD: RULES (/routing filter rule)
  11723. // -------------------------------------------------------------
  11724. function openAddRoutingFilterModal(defaultChain = '') {
  11725. const form = document.getElementById('routing-filter-form');
  11726. if (form) form.reset();
  11727. const idEl = document.getElementById('modal-rf-id');
  11728. if (idEl) idEl.value = '';
  11729. const titleEl = document.getElementById('modal-rf-title');
  11730. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11731. const chainEl = document.getElementById('modal-rf-chain');
  11732. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11733. const orderEl = document.getElementById('modal-rf-order');
  11734. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11735. const ruleEl = document.getElementById('modal-rf-rule');
  11736. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11737. const disEl = document.getElementById('modal-rf-disabled');
  11738. if (disEl) disEl.checked = false;
  11739. const modal = document.getElementById('modal-routing-filter');
  11740. if (modal) modal.classList.remove('hidden');
  11741. }
  11742. function openEditRoutingFilterModal(id) {
  11743. const r = (state.routingFilters || []).find(item => item.id === id);
  11744. if (!r) return;
  11745. const idEl = document.getElementById('modal-rf-id');
  11746. if (idEl) idEl.value = r.id;
  11747. const titleEl = document.getElementById('modal-rf-title');
  11748. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11749. const chainEl = document.getElementById('modal-rf-chain');
  11750. if (chainEl) chainEl.value = r.chain || '';
  11751. const orderEl = document.getElementById('modal-rf-order');
  11752. if (orderEl) orderEl.value = r.rule_order || 10;
  11753. const ruleEl = document.getElementById('modal-rf-rule');
  11754. if (ruleEl) {
  11755. if (r.rule) {
  11756. ruleEl.value = r.rule;
  11757. } else {
  11758. let conds = [];
  11759. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11760. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11761. let act = r.action || 'accept';
  11762. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11763. }
  11764. }
  11765. const comEl = document.getElementById('modal-rf-comment');
  11766. if (comEl) comEl.value = r.comment || '';
  11767. const disEl = document.getElementById('modal-rf-disabled');
  11768. if (disEl) disEl.checked = !!r.disabled;
  11769. const modal = document.getElementById('modal-routing-filter');
  11770. if (modal) modal.classList.remove('hidden');
  11771. }
  11772. function closeRoutingFilterModal() {
  11773. const modal = document.getElementById('modal-routing-filter');
  11774. if (modal) modal.classList.add('hidden');
  11775. }
  11776. async function submitRoutingFilter(e) {
  11777. if (e) e.preventDefault();
  11778. const payload = {
  11779. id: document.getElementById('modal-rf-id').value,
  11780. chain: document.getElementById('modal-rf-chain').value.trim(),
  11781. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11782. rule: document.getElementById('modal-rf-rule').value.trim(),
  11783. comment: document.getElementById('modal-rf-comment').value.trim(),
  11784. disabled: document.getElementById('modal-rf-disabled').checked
  11785. };
  11786. try {
  11787. const res = await fetch(`${API_BASE}/routing/filters`, {
  11788. method: 'POST',
  11789. headers: { 'Content-Type': 'application/json' },
  11790. body: JSON.stringify(payload)
  11791. });
  11792. if (res.ok) {
  11793. closeRoutingFilterModal();
  11794. showToast('Success', 'Routing filter rule saved', 'success');
  11795. loadDynamicRouting();
  11796. } else {
  11797. const err = await res.json();
  11798. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11799. }
  11800. } catch (err) {
  11801. showToast('Error', err.message, 'error');
  11802. }
  11803. }
  11804. async function applyRoutingFilterForm() {
  11805. const payload = {
  11806. id: document.getElementById('modal-rf-id').value,
  11807. chain: document.getElementById('modal-rf-chain').value.trim(),
  11808. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11809. rule: document.getElementById('modal-rf-rule').value.trim(),
  11810. comment: document.getElementById('modal-rf-comment').value.trim(),
  11811. disabled: document.getElementById('modal-rf-disabled').checked
  11812. };
  11813. try {
  11814. const res = await fetch(`${API_BASE}/routing/filters`, {
  11815. method: 'POST',
  11816. headers: { 'Content-Type': 'application/json' },
  11817. body: JSON.stringify(payload)
  11818. });
  11819. if (res.ok) {
  11820. const data = await res.json();
  11821. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11822. showToast('Applied', 'Routing filter configuration applied', 'success');
  11823. loadDynamicRouting();
  11824. } else {
  11825. const err = await res.json();
  11826. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11827. }
  11828. } catch (err) {
  11829. showToast('Error', err.message, 'error');
  11830. }
  11831. }
  11832. async function moveRoutingFilterOrder(id, delta) {
  11833. const list = state.routingFilters || [];
  11834. const idx = list.findIndex(r => r.id === id);
  11835. if (idx < 0) return;
  11836. const targetIdx = idx + delta;
  11837. if (targetIdx < 0 || targetIdx >= list.length) return;
  11838. const currentOrder = list[idx].rule_order || 10;
  11839. const targetOrder = list[targetIdx].rule_order || 20;
  11840. list[idx].rule_order = targetOrder;
  11841. list[targetIdx].rule_order = currentOrder;
  11842. try {
  11843. await fetch(`${API_BASE}/routing/filters`, {
  11844. method: 'POST',
  11845. headers: { 'Content-Type': 'application/json' },
  11846. body: JSON.stringify(list[idx])
  11847. });
  11848. await fetch(`${API_BASE}/routing/filters`, {
  11849. method: 'POST',
  11850. headers: { 'Content-Type': 'application/json' },
  11851. body: JSON.stringify(list[targetIdx])
  11852. });
  11853. loadDynamicRouting();
  11854. } catch (e) {
  11855. console.error('Reorder error:', e);
  11856. }
  11857. }
  11858. async function deleteRoutingFilter(id) {
  11859. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11860. try {
  11861. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11862. if (res.ok) {
  11863. showToast('Deleted', 'Routing filter rule removed', 'info');
  11864. loadDynamicRouting();
  11865. } else {
  11866. const err = await res.json();
  11867. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11868. }
  11869. } catch (err) {
  11870. showToast('Error', err.message, 'error');
  11871. }
  11872. }
  11873. async function toggleRoutingFilterState(id, disabled) {
  11874. try {
  11875. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11876. method: 'POST',
  11877. headers: { 'Content-Type': 'application/json' },
  11878. body: JSON.stringify({ disabled })
  11879. });
  11880. if (res.ok) {
  11881. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11882. loadDynamicRouting();
  11883. } else {
  11884. const err = await res.json();
  11885. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11886. }
  11887. } catch (err) {
  11888. showToast('Error', err.message, 'error');
  11889. }
  11890. }
  11891. // -------------------------------------------------------------
  11892. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11893. // -------------------------------------------------------------
  11894. function openAddCommunityListModal() {
  11895. document.getElementById('modal-rf-cl-id').value = '';
  11896. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11897. document.getElementById('modal-rf-cl-name').value = '';
  11898. document.getElementById('modal-rf-cl-communities').value = '';
  11899. document.getElementById('modal-rf-cl-regexp').value = '';
  11900. document.getElementById('modal-rf-cl-comment').value = '';
  11901. document.getElementById('modal-rf-cl-disabled').checked = false;
  11902. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11903. }
  11904. function openEditCommunityListModal(id) {
  11905. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11906. if (!cl) return;
  11907. document.getElementById('modal-rf-cl-id').value = cl.id;
  11908. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11909. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11910. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11911. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11912. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11913. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11914. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11915. }
  11916. function closeCommunityListModal() {
  11917. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11918. }
  11919. async function submitCommunityList(e) {
  11920. e.preventDefault();
  11921. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11922. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11923. const payload = {
  11924. id: document.getElementById('modal-rf-cl-id').value,
  11925. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11926. communities: comms,
  11927. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11928. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11929. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11930. };
  11931. try {
  11932. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11933. method: 'POST',
  11934. headers: { 'Content-Type': 'application/json' },
  11935. body: JSON.stringify(payload)
  11936. });
  11937. if (res.ok) {
  11938. closeCommunityListModal();
  11939. showToast('Success', 'Community list saved', 'success');
  11940. loadDynamicRouting();
  11941. } else {
  11942. const err = await res.json();
  11943. showToast('Error', err.error || 'Failed to save community list', 'error');
  11944. }
  11945. } catch (err) {
  11946. showToast('Error', err.message, 'error');
  11947. }
  11948. }
  11949. async function deleteCommunityList(id) {
  11950. if (!confirm('Are you sure you want to delete this community list?')) return;
  11951. try {
  11952. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11953. if (res.ok) {
  11954. showToast('Deleted', 'Community list removed', 'info');
  11955. loadDynamicRouting();
  11956. } else {
  11957. const err = await res.json();
  11958. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11959. }
  11960. } catch (err) {
  11961. showToast('Error', err.message, 'error');
  11962. }
  11963. }
  11964. async function toggleCommunityListState(id, disabled) {
  11965. try {
  11966. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11967. method: 'POST',
  11968. headers: { 'Content-Type': 'application/json' },
  11969. body: JSON.stringify({ disabled })
  11970. });
  11971. if (res.ok) {
  11972. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11973. loadDynamicRouting();
  11974. } else {
  11975. const err = await res.json();
  11976. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11977. }
  11978. } catch (err) {
  11979. showToast('Error', err.message, 'error');
  11980. }
  11981. }
  11982. // -------------------------------------------------------------
  11983. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11984. // -------------------------------------------------------------
  11985. function openAddASListModal() {
  11986. document.getElementById('modal-rf-al-id').value = '';
  11987. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11988. document.getElementById('modal-rf-al-name').value = '';
  11989. document.getElementById('modal-rf-al-range').value = '';
  11990. document.getElementById('modal-rf-al-comment').value = '';
  11991. document.getElementById('modal-rf-al-disabled').checked = false;
  11992. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11993. }
  11994. function openEditASListModal(id) {
  11995. const al = (state.routingASLists || []).find(item => item.id === id);
  11996. if (!al) return;
  11997. document.getElementById('modal-rf-al-id').value = al.id;
  11998. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11999. document.getElementById('modal-rf-al-name').value = al.name || '';
  12000. document.getElementById('modal-rf-al-range').value = al.range || '';
  12001. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12002. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12003. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12004. }
  12005. function closeASListModal() {
  12006. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12007. }
  12008. async function submitASList(e) {
  12009. e.preventDefault();
  12010. const payload = {
  12011. id: document.getElementById('modal-rf-al-id').value,
  12012. name: document.getElementById('modal-rf-al-name').value.trim(),
  12013. range: document.getElementById('modal-rf-al-range').value.trim(),
  12014. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12015. disabled: document.getElementById('modal-rf-al-disabled').checked
  12016. };
  12017. try {
  12018. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12019. method: 'POST',
  12020. headers: { 'Content-Type': 'application/json' },
  12021. body: JSON.stringify(payload)
  12022. });
  12023. if (res.ok) {
  12024. closeASListModal();
  12025. showToast('Success', 'AS number list saved', 'success');
  12026. loadDynamicRouting();
  12027. } else {
  12028. const err = await res.json();
  12029. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12030. }
  12031. } catch (err) {
  12032. showToast('Error', err.message, 'error');
  12033. }
  12034. }
  12035. async function deleteASList(id) {
  12036. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12037. try {
  12038. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12039. if (res.ok) {
  12040. showToast('Deleted', 'AS list removed', 'info');
  12041. loadDynamicRouting();
  12042. } else {
  12043. const err = await res.json();
  12044. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12045. }
  12046. } catch (err) {
  12047. showToast('Error', err.message, 'error');
  12048. }
  12049. }
  12050. async function toggleASListState(id, disabled) {
  12051. try {
  12052. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12053. method: 'POST',
  12054. headers: { 'Content-Type': 'application/json' },
  12055. body: JSON.stringify({ disabled })
  12056. });
  12057. if (res.ok) {
  12058. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12059. loadDynamicRouting();
  12060. } else {
  12061. const err = await res.json();
  12062. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12063. }
  12064. } catch (err) {
  12065. showToast('Error', err.message, 'error');
  12066. }
  12067. }
  12068. // ==========================================
  12069. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12070. // ==========================================
  12071. function loadToolsView() {
  12072. populateToolsInterfaces();
  12073. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12074. }
  12075. function populateToolsInterfaces() {
  12076. const pingSel = document.getElementById('tools-ping-iface');
  12077. const traceSel = document.getElementById('tools-tr-iface');
  12078. let opts = '<option value="">Auto (Default Route)</option>';
  12079. if (Array.isArray(state.interfaces)) {
  12080. state.interfaces.forEach(iface => {
  12081. if (iface.name) {
  12082. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12083. }
  12084. });
  12085. }
  12086. if (pingSel) {
  12087. const cur = pingSel.value;
  12088. pingSel.innerHTML = opts;
  12089. if (cur) pingSel.value = cur;
  12090. }
  12091. if (traceSel) {
  12092. const cur = traceSel.value;
  12093. traceSel.innerHTML = opts;
  12094. if (cur) traceSel.value = cur;
  12095. }
  12096. }
  12097. function switchToolsSubTab(subTab) {
  12098. state.activeToolsSubTab = subTab;
  12099. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12100. tabs.forEach(t => {
  12101. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12102. const view = document.getElementById(`tools-view-${t}`);
  12103. if (btn) {
  12104. if (t === subTab) {
  12105. 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';
  12106. } else {
  12107. 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';
  12108. }
  12109. }
  12110. if (view) {
  12111. if (t === subTab) {
  12112. view.classList.remove('hidden');
  12113. } else {
  12114. view.classList.add('hidden');
  12115. }
  12116. }
  12117. });
  12118. }
  12119. function setPortPreset(port) {
  12120. const input = document.getElementById('tools-port-num');
  12121. if (input) input.value = port;
  12122. }
  12123. let pingAbortController = null;
  12124. let tracerouteAbortController = null;
  12125. function clearPingTable() {
  12126. const tbody = document.getElementById('tools-ping-tbody');
  12127. if (tbody) tbody.innerHTML = '';
  12128. const rawEl = document.getElementById('tools-ping-raw');
  12129. if (rawEl) rawEl.innerText = '';
  12130. const sentEl = document.getElementById('tools-ping-stat-sent');
  12131. if (sentEl) sentEl.innerText = '0';
  12132. const recvEl = document.getElementById('tools-ping-stat-recv');
  12133. if (recvEl) recvEl.innerText = '0';
  12134. const lossEl = document.getElementById('tools-ping-stat-loss');
  12135. if (lossEl) lossEl.innerText = '0%';
  12136. const avgEl = document.getElementById('tools-ping-stat-avg');
  12137. if (avgEl) avgEl.innerText = '0 ms';
  12138. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12139. if (minMaxEl) minMaxEl.innerText = '-';
  12140. const badge = document.getElementById('tools-ping-status-badge');
  12141. if (badge) {
  12142. badge.className = '';
  12143. badge.innerText = '';
  12144. }
  12145. }
  12146. function clearTracerouteTable() {
  12147. const tbody = document.getElementById('tools-tr-tbody');
  12148. if (tbody) tbody.innerHTML = '';
  12149. const rawEl = document.getElementById('tools-tr-raw');
  12150. if (rawEl) rawEl.innerText = '';
  12151. const statHops = document.getElementById('tools-tr-hops-count');
  12152. if (statHops) statHops.innerText = '0 Hops';
  12153. }
  12154. function resetPingButton() {
  12155. const btn = document.getElementById('tools-ping-btn');
  12156. const btnText = document.getElementById('tools-ping-btn-text');
  12157. const spinner = document.getElementById('tools-ping-spinner');
  12158. if (btn) {
  12159. btn.disabled = false;
  12160. 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';
  12161. }
  12162. if (btnText) btnText.innerText = 'Start Ping';
  12163. if (spinner) spinner.classList.add('hidden');
  12164. }
  12165. function setPingRunningButton() {
  12166. const btn = document.getElementById('tools-ping-btn');
  12167. const btnText = document.getElementById('tools-ping-btn-text');
  12168. const spinner = document.getElementById('tools-ping-spinner');
  12169. if (btn) {
  12170. btn.disabled = false;
  12171. 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';
  12172. }
  12173. if (btnText) btnText.innerText = 'Stop Ping';
  12174. if (spinner) spinner.classList.remove('hidden');
  12175. }
  12176. function resetTracerouteButton() {
  12177. const btn = document.getElementById('tools-tr-btn');
  12178. const btnText = document.getElementById('tools-tr-btn-text');
  12179. const spinner = document.getElementById('tools-tr-spinner');
  12180. if (btn) {
  12181. btn.disabled = false;
  12182. 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';
  12183. }
  12184. if (btnText) btnText.innerText = 'Start Traceroute';
  12185. if (spinner) spinner.classList.add('hidden');
  12186. }
  12187. function setTracerouteRunningButton() {
  12188. const btn = document.getElementById('tools-tr-btn');
  12189. const btnText = document.getElementById('tools-tr-btn-text');
  12190. const spinner = document.getElementById('tools-tr-spinner');
  12191. if (btn) {
  12192. btn.disabled = false;
  12193. 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';
  12194. }
  12195. if (btnText) btnText.innerText = 'Stop Traceroute';
  12196. if (spinner) spinner.classList.remove('hidden');
  12197. }
  12198. async function executePing(e) {
  12199. if (e) e.preventDefault();
  12200. // If already running, clicking the button stops the stream!
  12201. if (pingAbortController) {
  12202. pingAbortController.abort();
  12203. pingAbortController = null;
  12204. resetPingButton();
  12205. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12206. return;
  12207. }
  12208. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12209. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12210. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12211. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12212. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12213. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12214. if (!target) {
  12215. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12216. return;
  12217. }
  12218. clearPingTable();
  12219. const resCard = document.getElementById('tools-ping-results');
  12220. if (resCard) resCard.classList.remove('hidden');
  12221. pingAbortController = new AbortController();
  12222. setPingRunningButton();
  12223. try {
  12224. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12225. method: 'POST',
  12226. headers: { 'Content-Type': 'application/json' },
  12227. body: JSON.stringify({
  12228. target,
  12229. count,
  12230. size,
  12231. timeout,
  12232. interface: iface,
  12233. dont_frag: dontFrag
  12234. }),
  12235. signal: pingAbortController.signal
  12236. });
  12237. if (!res.ok) {
  12238. const errText = await res.text();
  12239. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12240. resetPingButton();
  12241. pingAbortController = null;
  12242. return;
  12243. }
  12244. const reader = res.body.getReader();
  12245. const decoder = new TextDecoder('utf-8');
  12246. let buffer = '';
  12247. while (true) {
  12248. const { done, value } = await reader.read();
  12249. if (done) break;
  12250. buffer += decoder.decode(value, { stream: true });
  12251. const blocks = buffer.split('\n\n');
  12252. buffer = blocks.pop() || '';
  12253. for (const block of blocks) {
  12254. const trimmed = block.trim();
  12255. if (!trimmed) continue;
  12256. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12257. try {
  12258. const evt = JSON.parse(line);
  12259. handleLivePingEvent(evt);
  12260. } catch (parseErr) {
  12261. console.warn('Ping SSE parse error:', parseErr, line);
  12262. }
  12263. }
  12264. }
  12265. } catch (err) {
  12266. if (err.name === 'AbortError') {
  12267. // User aborted normally
  12268. } else {
  12269. showToast('Ping Error', err.message, 'error');
  12270. }
  12271. } finally {
  12272. pingAbortController = null;
  12273. resetPingButton();
  12274. }
  12275. }
  12276. function handleLivePingEvent(evt) {
  12277. const sentEl = document.getElementById('tools-ping-stat-sent');
  12278. const recvEl = document.getElementById('tools-ping-stat-recv');
  12279. const lossEl = document.getElementById('tools-ping-stat-loss');
  12280. const avgEl = document.getElementById('tools-ping-stat-avg');
  12281. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12282. const badge = document.getElementById('tools-ping-status-badge');
  12283. const tbody = document.getElementById('tools-ping-tbody');
  12284. const rawEl = document.getElementById('tools-ping-raw');
  12285. if (evt.raw && rawEl) {
  12286. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12287. rawEl.scrollTop = rawEl.scrollHeight;
  12288. }
  12289. if (evt.type === 'reply') {
  12290. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12291. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12292. if (lossEl && evt.packet_loss_pct !== undefined) {
  12293. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12294. lossEl.className = evt.packet_loss_pct === 0
  12295. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12296. : (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');
  12297. }
  12298. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12299. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12300. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12301. }
  12302. if (badge) {
  12303. if (evt.packet_loss_pct === 0) {
  12304. 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';
  12305. badge.innerText = '100% OK';
  12306. } else {
  12307. 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';
  12308. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12309. }
  12310. }
  12311. if (tbody) {
  12312. const tr = document.createElement('tr');
  12313. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12314. tr.innerHTML = `
  12315. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12316. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12317. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12318. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12319. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12320. <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>
  12321. `;
  12322. tbody.appendChild(tr);
  12323. }
  12324. } else if (evt.type === 'timeout') {
  12325. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12326. if (lossEl && evt.packet_loss_pct !== undefined) {
  12327. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12328. 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';
  12329. }
  12330. if (badge) {
  12331. 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';
  12332. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12333. }
  12334. if (tbody) {
  12335. const tr = document.createElement('tr');
  12336. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12337. tr.innerHTML = `
  12338. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12339. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12340. <td class="py-2 px-3 text-slate-600">--</td>
  12341. <td class="py-2 px-3 text-slate-600">--</td>
  12342. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12343. <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>
  12344. `;
  12345. tbody.appendChild(tr);
  12346. }
  12347. } else if (evt.type === 'unreach') {
  12348. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12349. if (lossEl && evt.packet_loss_pct !== undefined) {
  12350. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12351. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12352. }
  12353. if (badge) {
  12354. 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';
  12355. badge.innerText = 'UNREACHABLE';
  12356. }
  12357. if (tbody) {
  12358. const tr = document.createElement('tr');
  12359. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12360. tr.innerHTML = `
  12361. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12362. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12363. <td class="py-2 px-3 text-slate-600">--</td>
  12364. <td class="py-2 px-3 text-slate-600">--</td>
  12365. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12366. <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>
  12367. `;
  12368. tbody.appendChild(tr);
  12369. }
  12370. } else if (evt.type === 'stats') {
  12371. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12372. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12373. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12374. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12375. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12376. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12377. }
  12378. } else if (evt.type === 'done') {
  12379. 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');
  12380. }
  12381. }
  12382. async function executeTraceroute(e) {
  12383. if (e) e.preventDefault();
  12384. if (tracerouteAbortController) {
  12385. tracerouteAbortController.abort();
  12386. tracerouteAbortController = null;
  12387. resetTracerouteButton();
  12388. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12389. return;
  12390. }
  12391. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12392. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12393. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12394. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12395. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12396. if (!target) {
  12397. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12398. return;
  12399. }
  12400. clearTracerouteTable();
  12401. const resCard = document.getElementById('tools-tr-results');
  12402. if (resCard) resCard.classList.remove('hidden');
  12403. tracerouteAbortController = new AbortController();
  12404. setTracerouteRunningButton();
  12405. try {
  12406. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12407. method: 'POST',
  12408. headers: { 'Content-Type': 'application/json' },
  12409. body: JSON.stringify({
  12410. target,
  12411. max_hops: maxHops,
  12412. protocol,
  12413. interface: iface,
  12414. resolve
  12415. }),
  12416. signal: tracerouteAbortController.signal
  12417. });
  12418. if (!res.ok) {
  12419. const errText = await res.text();
  12420. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12421. resetTracerouteButton();
  12422. tracerouteAbortController = null;
  12423. return;
  12424. }
  12425. const reader = res.body.getReader();
  12426. const decoder = new TextDecoder('utf-8');
  12427. let buffer = '';
  12428. while (true) {
  12429. const { done, value } = await reader.read();
  12430. if (done) break;
  12431. buffer += decoder.decode(value, { stream: true });
  12432. const blocks = buffer.split('\n\n');
  12433. buffer = blocks.pop() || '';
  12434. for (const block of blocks) {
  12435. const trimmed = block.trim();
  12436. if (!trimmed) continue;
  12437. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12438. try {
  12439. const evt = JSON.parse(line);
  12440. handleLiveTracerouteEvent(evt);
  12441. } catch (parseErr) {
  12442. console.warn('Traceroute SSE parse error:', parseErr, line);
  12443. }
  12444. }
  12445. }
  12446. } catch (err) {
  12447. if (err.name === 'AbortError') {
  12448. // User aborted normally
  12449. } else {
  12450. showToast('Traceroute Error', err.message, 'error');
  12451. }
  12452. } finally {
  12453. tracerouteAbortController = null;
  12454. resetTracerouteButton();
  12455. }
  12456. }
  12457. function handleLiveTracerouteEvent(evt) {
  12458. const statHops = document.getElementById('tools-tr-hops-count');
  12459. const tbody = document.getElementById('tools-tr-tbody');
  12460. const rawEl = document.getElementById('tools-tr-raw');
  12461. if (evt.raw && rawEl) {
  12462. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12463. rawEl.scrollTop = rawEl.scrollHeight;
  12464. }
  12465. if (evt.hops_count !== undefined && statHops) {
  12466. statHops.innerText = `${evt.hops_count} Hops`;
  12467. }
  12468. if (evt.type === 'hop' && evt.hop && tbody) {
  12469. const h = evt.hop;
  12470. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12471. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12472. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12473. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12474. const tr = document.createElement('tr');
  12475. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12476. tr.innerHTML = `
  12477. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12478. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12479. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12480. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12481. <td class="py-2.5 px-3 text-right">
  12482. ${isTimeout
  12483. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12484. : '<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>'}
  12485. </td>
  12486. `;
  12487. tbody.appendChild(tr);
  12488. } else if (evt.type === 'done') {
  12489. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12490. }
  12491. }
  12492. async function executeMTR(e) {
  12493. if (e) e.preventDefault();
  12494. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12495. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12496. if (!target) {
  12497. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12498. return;
  12499. }
  12500. const btn = document.getElementById('tools-mtr-btn');
  12501. const spinner = document.getElementById('tools-mtr-spinner');
  12502. if (btn) btn.disabled = true;
  12503. if (spinner) spinner.classList.remove('hidden');
  12504. try {
  12505. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12506. method: 'POST',
  12507. headers: { 'Content-Type': 'application/json' },
  12508. body: JSON.stringify({ target, count: cycles })
  12509. });
  12510. const data = await res.json();
  12511. if (!res.ok) {
  12512. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12513. return;
  12514. }
  12515. const resCard = document.getElementById('tools-mtr-results');
  12516. if (resCard) resCard.classList.remove('hidden');
  12517. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12518. const statHops = document.getElementById('tools-mtr-hops-count');
  12519. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12520. const tbody = document.getElementById('tools-mtr-tbody');
  12521. if (tbody) {
  12522. if (hopsCount > 0) {
  12523. tbody.innerHTML = data.hops.map(h => {
  12524. 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');
  12525. return `
  12526. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12527. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12528. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12529. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12530. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12531. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12532. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12533. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12534. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12535. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12536. </tr>
  12537. `;
  12538. }).join('');
  12539. } else {
  12540. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12541. }
  12542. }
  12543. const rawEl = document.getElementById('tools-mtr-raw');
  12544. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12545. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12546. } catch (err) {
  12547. showToast('MTR Error', err.message, 'error');
  12548. } finally {
  12549. if (btn) btn.disabled = false;
  12550. if (spinner) spinner.classList.add('hidden');
  12551. }
  12552. }
  12553. async function executeDNS(e) {
  12554. if (e) e.preventDefault();
  12555. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12556. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12557. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12558. if (!domain) {
  12559. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12560. return;
  12561. }
  12562. const btn = document.getElementById('tools-dns-btn');
  12563. const spinner = document.getElementById('tools-dns-spinner');
  12564. if (btn) btn.disabled = true;
  12565. if (spinner) spinner.classList.remove('hidden');
  12566. try {
  12567. const res = await fetch(`${API_BASE}/tools/dns`, {
  12568. method: 'POST',
  12569. headers: { 'Content-Type': 'application/json' },
  12570. body: JSON.stringify({ domain, type, server })
  12571. });
  12572. const data = await res.json();
  12573. if (!res.ok) {
  12574. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12575. return;
  12576. }
  12577. const resCard = document.getElementById('tools-dns-results');
  12578. if (resCard) resCard.classList.remove('hidden');
  12579. const metaEl = document.getElementById('tools-dns-meta');
  12580. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12581. const tbody = document.getElementById('tools-dns-tbody');
  12582. if (tbody) {
  12583. if (Array.isArray(data.records) && data.records.length > 0) {
  12584. tbody.innerHTML = data.records.map(r => `
  12585. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12586. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12587. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12588. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12589. <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>
  12590. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12591. </tr>
  12592. `).join('');
  12593. } else {
  12594. 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>`;
  12595. }
  12596. }
  12597. const rawEl = document.getElementById('tools-dns-raw');
  12598. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12599. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12600. } catch (err) {
  12601. showToast('DNS Error', err.message, 'error');
  12602. } finally {
  12603. if (btn) btn.disabled = false;
  12604. if (spinner) spinner.classList.add('hidden');
  12605. }
  12606. }
  12607. async function executePortProbe(e) {
  12608. if (e) e.preventDefault();
  12609. const target = document.getElementById('tools-port-target')?.value?.trim();
  12610. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12611. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12612. if (!target || !port) {
  12613. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12614. return;
  12615. }
  12616. const btn = document.getElementById('tools-port-btn');
  12617. const spinner = document.getElementById('tools-port-spinner');
  12618. if (btn) btn.disabled = true;
  12619. if (spinner) spinner.classList.remove('hidden');
  12620. try {
  12621. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12622. method: 'POST',
  12623. headers: { 'Content-Type': 'application/json' },
  12624. body: JSON.stringify({ target, port, timeout })
  12625. });
  12626. const data = await res.json();
  12627. if (!res.ok) {
  12628. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12629. return;
  12630. }
  12631. const resCard = document.getElementById('tools-port-results');
  12632. if (resCard) resCard.classList.remove('hidden');
  12633. const banner = document.getElementById('tools-port-banner');
  12634. const icon = document.getElementById('tools-port-icon');
  12635. const title = document.getElementById('tools-port-title');
  12636. const sub = document.getElementById('tools-port-sub');
  12637. const latency = document.getElementById('tools-port-latency');
  12638. if (data.open) {
  12639. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12640. if (icon) {
  12641. 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';
  12642. icon.innerText = '✓';
  12643. }
  12644. if (title) {
  12645. title.className = 'text-sm font-bold text-emerald-300';
  12646. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12647. }
  12648. if (sub) {
  12649. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12650. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12651. }
  12652. if (latency) {
  12653. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12654. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12655. }
  12656. } else {
  12657. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12658. if (icon) {
  12659. 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';
  12660. icon.innerText = '✕';
  12661. }
  12662. if (title) {
  12663. title.className = 'text-sm font-bold text-rose-300';
  12664. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12665. }
  12666. if (sub) {
  12667. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12668. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12669. }
  12670. if (latency) {
  12671. latency.className = 'text-base font-bold font-mono text-slate-500';
  12672. latency.innerText = '--';
  12673. }
  12674. }
  12675. const rawEl = document.getElementById('tools-port-raw');
  12676. 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'}`);
  12677. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12678. } catch (err) {
  12679. showToast('Probe Error', err.message, 'error');
  12680. } finally {
  12681. if (btn) btn.disabled = false;
  12682. if (spinner) spinner.classList.add('hidden');
  12683. }
  12684. }
  12685. // ==========================================
  12686. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12687. // ==========================================
  12688. async function loadDHCPClients(showToastMsg = false) {
  12689. try {
  12690. const [clientsRes, sumRes] = await Promise.all([
  12691. fetch(`${API_BASE}/dhcp/clients`),
  12692. fetch(`${API_BASE}/dhcp/clients/summary`)
  12693. ]);
  12694. if (clientsRes.ok) {
  12695. state.dhcpClients = await clientsRes.json();
  12696. }
  12697. if (sumRes.ok) {
  12698. state.dhcpSummary = await sumRes.json();
  12699. }
  12700. renderDHCPClients();
  12701. updateDHCPSummaryCards();
  12702. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12703. if (bDhcp && state.dhcpSummary) {
  12704. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12705. }
  12706. if (showToastMsg) {
  12707. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12708. }
  12709. } catch (err) {
  12710. console.error('Failed to load DHCP clients:', err);
  12711. if (showToastMsg) {
  12712. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12713. }
  12714. }
  12715. }
  12716. function updateDHCPSummaryCards() {
  12717. const sum = state.dhcpSummary || {
  12718. total_clients: (state.dhcpClients || []).length,
  12719. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12720. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12721. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12722. };
  12723. const totalEl = document.getElementById('dhcp-stat-total');
  12724. const boundEl = document.getElementById('dhcp-stat-bound');
  12725. const searchEl = document.getElementById('dhcp-stat-searching');
  12726. const disEl = document.getElementById('dhcp-stat-disabled');
  12727. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12728. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12729. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12730. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12731. }
  12732. function renderDHCPClients() {
  12733. const tbody = document.getElementById('dhcp-clients-tbody');
  12734. const emptyState = document.getElementById('dhcp-clients-empty');
  12735. if (!tbody) return;
  12736. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12737. if (clients.length === 0) {
  12738. tbody.innerHTML = '';
  12739. if (emptyState) emptyState.classList.remove('hidden');
  12740. return;
  12741. }
  12742. if (emptyState) emptyState.classList.add('hidden');
  12743. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12744. if (tbody.dataset.sig === sig) return;
  12745. tbody.dataset.sig = sig;
  12746. tbody.innerHTML = clients.map(c => {
  12747. let statusBadge = '';
  12748. if (!c.enabled) {
  12749. 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>';
  12750. } else if (c.status === 'bound') {
  12751. 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>';
  12752. } else if (c.status === 'searching') {
  12753. 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>';
  12754. } else if (c.status === 'stopped') {
  12755. 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>';
  12756. } else {
  12757. 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>`;
  12758. }
  12759. 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>';
  12760. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12761. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12762. 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>';
  12763. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12764. // Option flags
  12765. const flags = [];
  12766. 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>');
  12767. 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>');
  12768. 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>');
  12769. 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>`);
  12770. return `
  12771. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12772. <td class="py-3 px-4">
  12773. <div class="flex items-center gap-2">
  12774. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12775. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12776. </div>
  12777. </td>
  12778. <td class="py-3 px-4">${statusBadge}</td>
  12779. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12780. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12781. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12782. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12783. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12784. <td class="py-3 px-4">
  12785. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12786. </td>
  12787. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12788. ${c.enabled ? `
  12789. <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>
  12790. <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>
  12791. <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>
  12792. ` : `
  12793. <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>
  12794. `}
  12795. <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>
  12796. <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>
  12797. </td>
  12798. </tr>
  12799. `;
  12800. }).join('');
  12801. }
  12802. function openDHCPClientModal(clientId = null) {
  12803. const modal = document.getElementById('modal-dhcp-client');
  12804. if (!modal) return;
  12805. const title = document.getElementById('modal-dhcp-title');
  12806. const idInput = document.getElementById('modal-dhcp-id');
  12807. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12808. const distInput = document.getElementById('modal-dhcp-distance');
  12809. const commentInput = document.getElementById('modal-dhcp-comment');
  12810. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12811. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12812. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12813. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12814. // Populate interfaces
  12815. if (ifaceSelect) {
  12816. let opts = '<option value="">Select interface...</option>';
  12817. const allIfaces = state.interfaces || [];
  12818. const allVlans = state.vlans || [];
  12819. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12820. // Group 1: Physical & Bridge Interfaces
  12821. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12822. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12823. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12824. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12825. });
  12826. opts += '</optgroup>';
  12827. // Group 2: VLAN Interfaces
  12828. if (allVlans.length > 0) {
  12829. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12830. allVlans.forEach(v => {
  12831. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12832. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12833. });
  12834. opts += '</optgroup>';
  12835. }
  12836. ifaceSelect.innerHTML = opts;
  12837. }
  12838. if (clientId) {
  12839. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12840. if (client) {
  12841. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12842. if (idInput) idInput.value = client.id;
  12843. if (ifaceSelect) {
  12844. ifaceSelect.value = client.interface;
  12845. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12846. }
  12847. if (distInput) distInput.value = client.default_route_distance || 1;
  12848. if (commentInput) commentInput.value = client.comment || '';
  12849. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12850. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12851. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12852. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12853. }
  12854. } else {
  12855. if (title) title.innerText = 'Add DHCP Client';
  12856. if (idInput) idInput.value = '';
  12857. if (ifaceSelect) {
  12858. ifaceSelect.value = '';
  12859. ifaceSelect.disabled = false;
  12860. }
  12861. if (distInput) distInput.value = 1;
  12862. if (commentInput) commentInput.value = '';
  12863. if (defRouteCheck) defRouteCheck.checked = true;
  12864. if (peerDnsCheck) peerDnsCheck.checked = true;
  12865. if (peerNtpCheck) peerNtpCheck.checked = true;
  12866. if (enabledCheck) enabledCheck.checked = true;
  12867. }
  12868. modal.classList.remove('hidden');
  12869. }
  12870. function openDHCPClientModalForIface(ifaceName) {
  12871. openDHCPClientModal();
  12872. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12873. if (ifaceSelect && ifaceName) {
  12874. ifaceSelect.value = ifaceName;
  12875. }
  12876. }
  12877. function closeDHCPClientModal() {
  12878. const modal = document.getElementById('modal-dhcp-client');
  12879. if (modal) modal.classList.add('hidden');
  12880. }
  12881. async function submitSaveDHCPClient(e) {
  12882. if (e) e.preventDefault();
  12883. const id = document.getElementById('modal-dhcp-id')?.value;
  12884. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12885. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12886. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12887. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12888. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12889. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12890. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12891. if (!id && !iface) {
  12892. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12893. return;
  12894. }
  12895. try {
  12896. let res;
  12897. if (id) {
  12898. // PUT update
  12899. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12900. method: 'PUT',
  12901. headers: { 'Content-Type': 'application/json' },
  12902. body: JSON.stringify({
  12903. enabled,
  12904. add_default_route: defRoute,
  12905. default_route_distance: distance,
  12906. use_peer_dns: peerDns,
  12907. use_peer_ntp: peerNtp,
  12908. comment
  12909. })
  12910. });
  12911. } else {
  12912. // POST create
  12913. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12914. method: 'POST',
  12915. headers: { 'Content-Type': 'application/json' },
  12916. body: JSON.stringify({
  12917. interface: iface,
  12918. enabled,
  12919. add_default_route: defRoute,
  12920. default_route_distance: distance,
  12921. use_peer_dns: peerDns,
  12922. use_peer_ntp: peerNtp,
  12923. comment
  12924. })
  12925. });
  12926. }
  12927. const data = await res.json();
  12928. if (!res.ok) {
  12929. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12930. return;
  12931. }
  12932. closeDHCPClientModal();
  12933. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12934. await loadDHCPClients();
  12935. fetchData(); // refresh interfaces list with new lease/status
  12936. } catch (err) {
  12937. showToast('Error', err.message, 'error');
  12938. }
  12939. }
  12940. async function toggleDHCPClientState(id, enabled) {
  12941. try {
  12942. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12943. method: 'POST',
  12944. headers: { 'Content-Type': 'application/json' },
  12945. body: JSON.stringify({ enabled })
  12946. });
  12947. const data = await res.json();
  12948. if (!res.ok) {
  12949. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12950. return;
  12951. }
  12952. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12953. await loadDHCPClients();
  12954. fetchData();
  12955. } catch (err) {
  12956. showToast('Error', err.message, 'error');
  12957. }
  12958. }
  12959. async function renewDHCPClient(id) {
  12960. try {
  12961. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12962. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12963. method: 'POST'
  12964. });
  12965. const data = await res.json();
  12966. if (!res.ok) {
  12967. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12968. return;
  12969. }
  12970. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12971. setTimeout(() => {
  12972. loadDHCPClients();
  12973. fetchData();
  12974. }, 1500);
  12975. } catch (err) {
  12976. showToast('Error', err.message, 'error');
  12977. }
  12978. }
  12979. async function releaseDHCPClient(id) {
  12980. try {
  12981. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12982. method: 'POST'
  12983. });
  12984. const data = await res.json();
  12985. if (!res.ok) {
  12986. showToast('Error', data.error || 'Failed to release lease', 'error');
  12987. return;
  12988. }
  12989. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12990. await loadDHCPClients();
  12991. fetchData();
  12992. } catch (err) {
  12993. showToast('Error', err.message, 'error');
  12994. }
  12995. }
  12996. async function deleteDHCPClient(id, ifaceName) {
  12997. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12998. return;
  12999. }
  13000. try {
  13001. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13002. method: 'DELETE'
  13003. });
  13004. const data = await res.json();
  13005. if (!res.ok) {
  13006. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13007. return;
  13008. }
  13009. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13010. await loadDHCPClients();
  13011. fetchData();
  13012. } catch (err) {
  13013. showToast('Error', err.message, 'error');
  13014. }
  13015. }
  13016. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13017. async function loadDHCPServer(populate = true) {
  13018. try {
  13019. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13020. fetch(`${API_BASE}/dhcp-server/summary`),
  13021. fetch(`${API_BASE}/dhcp-server/servers`),
  13022. fetch(`${API_BASE}/dhcp-server/networks`),
  13023. fetch(`${API_BASE}/dhcp-server/leases`),
  13024. fetch(`${API_BASE}/dhcp-server/options`)
  13025. ]);
  13026. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13027. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13028. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13029. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13030. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13031. const sum = state.dhcpServerSummary || {};
  13032. const srvs = state.dhcpServers || [];
  13033. const nets = state.dhcpNetworks || [];
  13034. const leases = state.dhcpLeases || [];
  13035. const opts = state.dhcpOptions || [];
  13036. // KPI Cards
  13037. const statActive = document.getElementById('dhcp-server-stat-active');
  13038. if (statActive) {
  13039. const activeCount = srvs.filter(s => s.running).length;
  13040. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13041. }
  13042. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13043. if (statLeases) {
  13044. statLeases.innerText = leases.length;
  13045. }
  13046. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13047. if (statLeasesSub) {
  13048. const dyn = leases.filter(l => l.dynamic).length;
  13049. const st = leases.filter(l => !l.dynamic).length;
  13050. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13051. }
  13052. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13053. if (statNetworks) {
  13054. statNetworks.innerText = nets.length;
  13055. }
  13056. // Subtab Badges
  13057. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13058. if (bSrv) bSrv.innerText = srvs.length;
  13059. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13060. if (bNet) bNet.innerText = nets.length;
  13061. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13062. if (bLease) bLease.innerText = leases.length;
  13063. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13064. if (bOpt) bOpt.innerText = opts.length;
  13065. // Sidebar Badge
  13066. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13067. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13068. renderCurrentDHCPServerTab();
  13069. } catch (err) {
  13070. console.error('Failed to load DHCP Server:', err);
  13071. }
  13072. }
  13073. function switchDHCPServerTab(tab) {
  13074. state.dhcpServerTab = tab;
  13075. const tabs = ['servers', 'networks', 'leases', 'options'];
  13076. tabs.forEach(t => {
  13077. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13078. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13079. if (panel) {
  13080. if (t === tab) panel.classList.remove('hidden');
  13081. else panel.classList.add('hidden');
  13082. }
  13083. if (btn) {
  13084. if (t === tab) {
  13085. 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';
  13086. } else {
  13087. 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';
  13088. }
  13089. }
  13090. });
  13091. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13092. if (addBtn) {
  13093. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13094. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13095. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13096. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13097. }
  13098. renderCurrentDHCPServerTab();
  13099. }
  13100. function handleDHCPServerPrimaryAdd() {
  13101. const tab = state.dhcpServerTab || 'servers';
  13102. if (tab === 'servers') openAddDHCPServerModal();
  13103. else if (tab === 'networks') openAddDHCPNetworkModal();
  13104. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13105. else if (tab === 'options') openAddDHCPOptionModal();
  13106. }
  13107. function renderCurrentDHCPServerTab() {
  13108. const tab = state.dhcpServerTab || 'servers';
  13109. if (tab === 'servers') renderDHCPServers();
  13110. else if (tab === 'networks') renderDHCPNetworks();
  13111. else if (tab === 'leases') renderDHCPLeases();
  13112. else if (tab === 'options') renderDHCPOptions();
  13113. }
  13114. function renderDHCPServers() {
  13115. const tbody = document.getElementById('dhcp-server-tbody');
  13116. const empty = document.getElementById('dhcp-server-empty');
  13117. if (!tbody) return;
  13118. const servers = state.dhcpServers || [];
  13119. if (servers.length === 0) {
  13120. tbody.innerHTML = '';
  13121. empty?.classList.remove('hidden');
  13122. return;
  13123. }
  13124. empty?.classList.add('hidden');
  13125. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13126. if (tbody.dataset.sig === sig) return;
  13127. tbody.dataset.sig = sig;
  13128. tbody.innerHTML = '';
  13129. servers.forEach(s => {
  13130. const tr = document.createElement('tr');
  13131. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13132. tr.innerHTML = `
  13133. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13134. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13135. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13136. <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>
  13137. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13138. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13139. <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>
  13140. <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>
  13141. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13142. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13143. <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>
  13144. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13145. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13146. </td>
  13147. `;
  13148. tbody.appendChild(tr);
  13149. });
  13150. }
  13151. function renderDHCPNetworks() {
  13152. const tbody = document.getElementById('dhcp-networks-tbody');
  13153. const empty = document.getElementById('dhcp-networks-empty');
  13154. if (!tbody) return;
  13155. tbody.innerHTML = '';
  13156. const networks = state.dhcpNetworks || [];
  13157. if (networks.length === 0) {
  13158. empty?.classList.remove('hidden');
  13159. return;
  13160. }
  13161. empty?.classList.add('hidden');
  13162. networks.forEach(n => {
  13163. const tr = document.createElement('tr');
  13164. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13165. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13166. const optionsChips = (n.dhcp_options || []).map(optId => {
  13167. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13168. if (!opt) return '';
  13169. 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>`;
  13170. }).filter(Boolean).join('');
  13171. tr.innerHTML = `
  13172. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13173. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13174. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13175. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13176. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13177. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13178. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13179. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13180. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13181. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13182. </td>
  13183. `;
  13184. tbody.appendChild(tr);
  13185. });
  13186. }
  13187. function renderDHCPLeases() {
  13188. const tbody = document.getElementById('dhcp-leases-tbody');
  13189. const empty = document.getElementById('dhcp-leases-empty');
  13190. if (!tbody) return;
  13191. tbody.innerHTML = '';
  13192. const leases = state.dhcpLeases || [];
  13193. if (leases.length === 0) {
  13194. empty?.classList.remove('hidden');
  13195. return;
  13196. }
  13197. empty?.classList.add('hidden');
  13198. leases.forEach(l => {
  13199. const tr = document.createElement('tr');
  13200. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13201. 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>';
  13202. const statusBadge = l.status === 'bound'
  13203. ? '<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>'
  13204. : l.status === 'static'
  13205. ? '<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>'
  13206. : '<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>';
  13207. const makeStaticBtn = l.dynamic
  13208. ? `<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>`
  13209. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13210. tr.innerHTML = `
  13211. <td class="py-2.5 px-3 text-center">${flag}</td>
  13212. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13213. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13214. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13215. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13216. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13217. <td class="py-2.5 px-3">${statusBadge}</td>
  13218. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13219. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13220. ${makeStaticBtn}
  13221. </td>
  13222. `;
  13223. tbody.appendChild(tr);
  13224. });
  13225. }
  13226. function renderDHCPOptions() {
  13227. const tbody = document.getElementById('dhcp-options-tbody');
  13228. const empty = document.getElementById('dhcp-options-empty');
  13229. if (!tbody) return;
  13230. tbody.innerHTML = '';
  13231. const options = state.dhcpOptions || [];
  13232. if (options.length === 0) {
  13233. empty?.classList.remove('hidden');
  13234. return;
  13235. }
  13236. empty?.classList.add('hidden');
  13237. options.forEach(o => {
  13238. const tr = document.createElement('tr');
  13239. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13240. tr.innerHTML = `
  13241. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13242. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13243. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13244. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13245. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13246. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13247. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13248. </td>
  13249. `;
  13250. tbody.appendChild(tr);
  13251. });
  13252. }
  13253. // ==================== MODALS & ACTIONS: SERVER ====================
  13254. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13255. const sel = document.getElementById(elemId);
  13256. if (!sel) return;
  13257. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13258. const networks = state.dhcpNetworks || [];
  13259. networks.forEach(n => {
  13260. const opt = document.createElement('option');
  13261. opt.value = n.address;
  13262. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13263. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13264. opt.selected = true;
  13265. }
  13266. sel.appendChild(opt);
  13267. });
  13268. }
  13269. function onDHCPServerNetworkChange() {
  13270. const netSel = document.getElementById('dhcp-server-modal-network');
  13271. if (!netSel) return;
  13272. const netVal = netSel.value;
  13273. if (!netVal) return;
  13274. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13275. if (!poolInput) return;
  13276. // Auto-calculate suggested address pool based on subnet CIDR
  13277. const parts = netVal.split('/');
  13278. const ip = parts[0];
  13279. const cidr = parseInt(parts[1] || '24', 10);
  13280. if (cidr === 24) {
  13281. const octets = ip.split('.');
  13282. if (octets.length === 4) {
  13283. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13284. poolInput.value = `${base}.10-${base}.254`;
  13285. }
  13286. }
  13287. }
  13288. function openAddDHCPServerModal() {
  13289. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13290. document.getElementById('dhcp-server-modal-id').value = '';
  13291. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13292. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13293. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13294. document.getElementById('dhcp-server-modal-comment').value = '';
  13295. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13296. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13297. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13298. const networks = state.dhcpNetworks || [];
  13299. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13300. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13301. if (defaultNet) {
  13302. onDHCPServerNetworkChange();
  13303. }
  13304. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13305. }
  13306. function openEditDHCPServerModal(id) {
  13307. const s = (state.dhcpServers || []).find(item => item.id === id);
  13308. if (!s) return;
  13309. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13310. document.getElementById('dhcp-server-modal-id').value = s.id;
  13311. document.getElementById('dhcp-server-modal-name').value = s.name;
  13312. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13313. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13314. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13315. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13316. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13317. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13318. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13319. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13320. }
  13321. function closeDHCPServerModal() {
  13322. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13323. }
  13324. async function submitSaveDHCPServer(e) {
  13325. e.preventDefault();
  13326. const id = document.getElementById('dhcp-server-modal-id').value;
  13327. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13328. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13329. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13330. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13331. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13332. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13333. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13334. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13335. try {
  13336. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13337. method: 'POST',
  13338. headers: { 'Content-Type': 'application/json' },
  13339. body: JSON.stringify({
  13340. id,
  13341. name,
  13342. interface: iface,
  13343. network,
  13344. address_pool: pool,
  13345. lease_time: leaseTime,
  13346. authoritative,
  13347. disabled,
  13348. comment
  13349. })
  13350. });
  13351. if (res.ok) {
  13352. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13353. closeDHCPServerModal();
  13354. loadDHCPServer(false);
  13355. fetchData(false);
  13356. } else {
  13357. const err = await res.text();
  13358. showToast('Error', err, 'error');
  13359. }
  13360. } catch (err) {
  13361. showToast('Error', err.message, 'error');
  13362. }
  13363. }
  13364. async function toggleDHCPServerState(id, disabled) {
  13365. try {
  13366. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13367. method: 'POST',
  13368. headers: { 'Content-Type': 'application/json' },
  13369. body: JSON.stringify({ disabled })
  13370. });
  13371. if (res.ok) {
  13372. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13373. loadDHCPServer(false);
  13374. fetchData(false);
  13375. }
  13376. } catch (err) {
  13377. showToast('Error', err.message, 'error');
  13378. }
  13379. }
  13380. async function deleteDHCPServer(id, name) {
  13381. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13382. try {
  13383. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13384. if (res.ok) {
  13385. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13386. loadDHCPServer(false);
  13387. fetchData(false);
  13388. }
  13389. } catch (err) {
  13390. showToast('Error', err.message, 'error');
  13391. }
  13392. }
  13393. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13394. function openAddDHCPNetworkModal() {
  13395. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13396. document.getElementById('dhcp-network-modal-id').value = '';
  13397. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13398. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13399. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13400. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13401. document.getElementById('dhcp-network-modal-netmask').value = '';
  13402. document.getElementById('dhcp-network-modal-comment').value = '';
  13403. renderDHCPNetworkOptionsCheckboxes([]);
  13404. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13405. }
  13406. function openEditDHCPNetworkModal(id) {
  13407. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13408. if (!n) return;
  13409. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13410. document.getElementById('dhcp-network-modal-id').value = n.id;
  13411. document.getElementById('dhcp-network-modal-address').value = n.address;
  13412. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13413. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13414. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13415. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13416. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13417. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13418. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13419. }
  13420. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13421. const container = document.getElementById('dhcp-network-modal-options-list');
  13422. if (!container) return;
  13423. container.innerHTML = '';
  13424. const opts = state.dhcpOptions || [];
  13425. if (opts.length === 0) {
  13426. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13427. return;
  13428. }
  13429. opts.forEach(o => {
  13430. const isChecked = selectedIds.includes(o.id);
  13431. const label = document.createElement('label');
  13432. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13433. label.innerHTML = `
  13434. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13435. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13436. `;
  13437. container.appendChild(label);
  13438. });
  13439. }
  13440. function closeDHCPNetworkModal() {
  13441. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13442. }
  13443. async function submitSaveDHCPNetwork(e) {
  13444. e.preventDefault();
  13445. const id = document.getElementById('dhcp-network-modal-id').value;
  13446. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13447. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13448. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13449. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13450. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13451. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13452. const selectedOpts = [];
  13453. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13454. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13455. try {
  13456. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13457. method: 'POST',
  13458. headers: { 'Content-Type': 'application/json' },
  13459. body: JSON.stringify({
  13460. id,
  13461. address,
  13462. gateway,
  13463. netmask,
  13464. dns_servers: dnsServers,
  13465. domain,
  13466. dhcp_options: selectedOpts,
  13467. comment
  13468. })
  13469. });
  13470. if (res.ok) {
  13471. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13472. closeDHCPNetworkModal();
  13473. loadDHCPServer(false);
  13474. fetchData(false);
  13475. } else {
  13476. const err = await res.text();
  13477. showToast('Error', err, 'error');
  13478. }
  13479. } catch (err) {
  13480. showToast('Error', err.message, 'error');
  13481. }
  13482. }
  13483. async function deleteDHCPNetwork(id, addr) {
  13484. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13485. try {
  13486. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13487. if (res.ok) {
  13488. showToast('Deleted', `Network ${addr} removed`, 'success');
  13489. loadDHCPServer(false);
  13490. fetchData(false);
  13491. }
  13492. } catch (err) {
  13493. showToast('Error', err.message, 'error');
  13494. }
  13495. }
  13496. // ==================== MODALS & ACTIONS: LEASES ====================
  13497. function openAddDHCPStaticLeaseModal() {
  13498. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13499. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13500. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13501. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13502. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13503. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13504. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13505. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13506. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13507. }
  13508. function closeDHCPStaticLeaseModal() {
  13509. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13510. }
  13511. async function submitSaveDHCPStaticLease(e) {
  13512. e.preventDefault();
  13513. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13514. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13515. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13516. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13517. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13518. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13519. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13520. try {
  13521. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13522. method: 'POST',
  13523. headers: { 'Content-Type': 'application/json' },
  13524. body: JSON.stringify({
  13525. id,
  13526. mac_address: mac,
  13527. address: ip,
  13528. hostname,
  13529. server,
  13530. comment,
  13531. disabled
  13532. })
  13533. });
  13534. if (res.ok) {
  13535. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13536. closeDHCPStaticLeaseModal();
  13537. loadDHCPServer(false);
  13538. fetchData(false);
  13539. } else {
  13540. const err = await res.text();
  13541. showToast('Error', err, 'error');
  13542. }
  13543. } catch (err) {
  13544. showToast('Error', err.message, 'error');
  13545. }
  13546. }
  13547. async function deleteDHCPStaticLease(id) {
  13548. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13549. try {
  13550. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13551. if (res.ok) {
  13552. showToast('Deleted', 'Static lease removed', 'success');
  13553. loadDHCPServer(false);
  13554. fetchData(false);
  13555. }
  13556. } catch (err) {
  13557. showToast('Error', err.message, 'error');
  13558. }
  13559. }
  13560. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13561. try {
  13562. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13563. method: 'POST',
  13564. headers: { 'Content-Type': 'application/json' },
  13565. body: JSON.stringify({
  13566. mac_address: mac,
  13567. address: ip,
  13568. hostname,
  13569. comment: comment || 'Converted to static'
  13570. })
  13571. });
  13572. if (res.ok) {
  13573. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13574. loadDHCPServer(false);
  13575. fetchData(false);
  13576. } else {
  13577. const err = await res.text();
  13578. showToast('Error', err, 'error');
  13579. }
  13580. } catch (err) {
  13581. showToast('Error', err.message, 'error');
  13582. }
  13583. }
  13584. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13585. function openAddDHCPOptionModal() {
  13586. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13587. document.getElementById('dhcp-option-modal-id').value = '';
  13588. document.getElementById('dhcp-option-modal-name').value = '';
  13589. document.getElementById('dhcp-option-modal-code').value = '';
  13590. document.getElementById('dhcp-option-modal-value').value = '';
  13591. document.getElementById('dhcp-option-modal-comment').value = '';
  13592. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13593. }
  13594. function openEditDHCPOptionModal(id) {
  13595. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13596. if (!o) return;
  13597. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13598. document.getElementById('dhcp-option-modal-id').value = o.id;
  13599. document.getElementById('dhcp-option-modal-name').value = o.name;
  13600. document.getElementById('dhcp-option-modal-code').value = o.code;
  13601. document.getElementById('dhcp-option-modal-value').value = o.value;
  13602. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13603. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13604. }
  13605. function closeDHCPOptionModal() {
  13606. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13607. }
  13608. async function submitSaveDHCPOption(e) {
  13609. e.preventDefault();
  13610. const id = document.getElementById('dhcp-option-modal-id').value;
  13611. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13612. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13613. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13614. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13615. try {
  13616. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13617. method: 'POST',
  13618. headers: { 'Content-Type': 'application/json' },
  13619. body: JSON.stringify({ id, name, code, value, comment })
  13620. });
  13621. if (res.ok) {
  13622. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13623. closeDHCPOptionModal();
  13624. loadDHCPServer(false);
  13625. fetchData(false);
  13626. } else {
  13627. const err = await res.text();
  13628. showToast('Error', err, 'error');
  13629. }
  13630. } catch (err) {
  13631. showToast('Error', err.message, 'error');
  13632. }
  13633. }
  13634. async function deleteDHCPOption(id, name) {
  13635. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13636. try {
  13637. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13638. if (res.ok) {
  13639. showToast('Deleted', `Option ${name} removed`, 'success');
  13640. loadDHCPServer(false);
  13641. fetchData(false);
  13642. }
  13643. } catch (err) {
  13644. showToast('Error', err.message, 'error');
  13645. }
  13646. }
  13647. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13648. function openDHCPServerSetupModal() {
  13649. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13650. onDHCPWizardIfaceChange();
  13651. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13652. }
  13653. function closeDHCPServerSetupModal() {
  13654. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13655. }
  13656. function onDHCPWizardIfaceChange() {
  13657. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13658. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13659. let ip = '192.168.88.1';
  13660. let prefix = '24';
  13661. if (iface && iface.ip_address) {
  13662. const parts = iface.ip_address.split('/');
  13663. ip = parts[0];
  13664. if (parts.length > 1) prefix = parts[1];
  13665. }
  13666. // Calculate subnet base (e.g. 192.168.88.0/24)
  13667. const ipParts = ip.split('.');
  13668. if (ipParts.length === 4) {
  13669. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13670. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13671. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13672. document.getElementById('dhcp-wizard-gateway').value = ip;
  13673. document.getElementById('dhcp-wizard-pool').value = pool;
  13674. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13675. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13676. }
  13677. }
  13678. async function submitDHCPServerSetupWizard(e) {
  13679. e.preventDefault();
  13680. const iface = document.getElementById('dhcp-wizard-iface').value;
  13681. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13682. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13683. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13684. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13685. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13686. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13687. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13688. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13689. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13690. try {
  13691. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13692. method: 'POST',
  13693. headers: { 'Content-Type': 'application/json' },
  13694. body: JSON.stringify({
  13695. interface: iface,
  13696. address_space: space,
  13697. gateway: gw,
  13698. address_pool: pool,
  13699. dns_servers: dnsServers,
  13700. lease_time: leaseTime,
  13701. ntp_servers: ntpServers,
  13702. next_server: tftp
  13703. })
  13704. });
  13705. if (res.ok) {
  13706. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13707. closeDHCPServerSetupModal();
  13708. loadDHCPServer(false);
  13709. fetchData(false);
  13710. } else {
  13711. const err = await res.text();
  13712. showToast('Error', err, 'error');
  13713. }
  13714. } catch (err) {
  13715. showToast('Error', err.message, 'error');
  13716. }
  13717. }
  13718. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13719. const sel = document.getElementById(elemId);
  13720. if (!sel) return;
  13721. sel.innerHTML = '<option value="">Select interface...</option>';
  13722. const ifaces = state.interfaces || [];
  13723. ifaces.forEach(i => {
  13724. if (i.name === 'lo') return;
  13725. const opt = document.createElement('option');
  13726. opt.value = i.name;
  13727. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13728. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13729. if (i.name === selectedVal) opt.selected = true;
  13730. sel.appendChild(opt);
  13731. });
  13732. }
  13733. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13734. function initTableSorting() {
  13735. document.querySelectorAll('table').forEach(setupSortableTable);
  13736. }
  13737. function setupSortableTable(table) {
  13738. const thead = table.querySelector('thead');
  13739. const tbody = table.querySelector('tbody');
  13740. if (!thead || !tbody) return;
  13741. const headerRows = thead.querySelectorAll('tr');
  13742. if (headerRows.length === 0) return;
  13743. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13744. ths.forEach((th, colIdx) => {
  13745. if (th._sortBound) return;
  13746. th._sortBound = true;
  13747. const rawText = th.innerText.trim().toLowerCase();
  13748. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13749. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13750. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13751. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13752. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13753. return;
  13754. }
  13755. th.classList.add('table-sortable', 'group');
  13756. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13757. let icon = th.querySelector('.table-sort-icon');
  13758. if (!icon) {
  13759. icon = document.createElement('span');
  13760. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13761. icon.innerHTML = '⇅';
  13762. th.appendChild(icon);
  13763. }
  13764. th.addEventListener('click', (e) => {
  13765. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13766. handleHeaderClick(table, th, colIdx);
  13767. });
  13768. });
  13769. if (!tbody._sortObserved) {
  13770. tbody._sortObserved = true;
  13771. let sortDebounceTimer = null;
  13772. const observer = new MutationObserver((mutations) => {
  13773. if (tbody._isSorting) return;
  13774. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13775. if (!hasChildChanges) return;
  13776. clearTimeout(sortDebounceTimer);
  13777. sortDebounceTimer = setTimeout(() => {
  13778. if (tbody._isSorting) return;
  13779. if (table._activeSort && table._activeSort.dir !== 'none') {
  13780. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13781. } else {
  13782. tagOriginalRowOrder(tbody);
  13783. }
  13784. }, 50);
  13785. });
  13786. tbody._sortObserver = observer;
  13787. observer.observe(tbody, { childList: true });
  13788. }
  13789. tagOriginalRowOrder(tbody);
  13790. }
  13791. function tagOriginalRowOrder(tbody) {
  13792. let idx = 0;
  13793. Array.from(tbody.children).forEach(tr => {
  13794. if (!tr.querySelector('td[colspan]')) {
  13795. if (!tr.hasAttribute('data-orig-idx')) {
  13796. tr.setAttribute('data-orig-idx', idx++);
  13797. }
  13798. }
  13799. });
  13800. }
  13801. function handleHeaderClick(table, th, colIdx) {
  13802. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13803. let newDir = 'asc';
  13804. if (currentSort.colIdx === colIdx) {
  13805. if (currentSort.dir === 'asc') newDir = 'desc';
  13806. else if (currentSort.dir === 'desc') newDir = 'none';
  13807. else newDir = 'asc';
  13808. } else {
  13809. newDir = 'asc';
  13810. }
  13811. table._activeSort = { colIdx, dir: newDir };
  13812. updateHeaderIcons(table, colIdx, newDir);
  13813. applyTableSort(table, colIdx, newDir, true);
  13814. }
  13815. function updateHeaderIcons(table, activeColIdx, dir) {
  13816. const thead = table.querySelector('thead');
  13817. if (!thead) return;
  13818. const ths = thead.querySelectorAll('th');
  13819. ths.forEach((th, idx) => {
  13820. const icon = th.querySelector('.table-sort-icon');
  13821. if (!icon) return;
  13822. if (idx === activeColIdx && dir !== 'none') {
  13823. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13824. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13825. th.classList.add('table-sorted-active');
  13826. } else {
  13827. icon.innerHTML = '⇅';
  13828. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13829. th.classList.remove('table-sorted-active');
  13830. }
  13831. });
  13832. }
  13833. function applyTableSort(table, colIdx, dir, userInitiated) {
  13834. const tbody = table.querySelector('tbody');
  13835. if (!tbody || tbody.children.length <= 1) return;
  13836. tbody._isSorting = true;
  13837. tagOriginalRowOrder(tbody);
  13838. // Group parent rows and any attached drawer/sub-rows
  13839. const groups = [];
  13840. let currentGroup = null;
  13841. Array.from(tbody.children).forEach(tr => {
  13842. if (tr.querySelector('td[colspan]')) {
  13843. if (currentGroup) {
  13844. currentGroup.subRows.push(tr);
  13845. } else {
  13846. groups.push({ mainRow: tr, subRows: [] });
  13847. }
  13848. } else {
  13849. currentGroup = { mainRow: tr, subRows: [] };
  13850. groups.push(currentGroup);
  13851. }
  13852. });
  13853. if (dir === 'none') {
  13854. groups.sort((a, b) => {
  13855. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13856. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13857. return idxA - idxB;
  13858. });
  13859. } else {
  13860. groups.sort((a, b) => {
  13861. const cellA = a.mainRow.children[colIdx];
  13862. const cellB = b.mainRow.children[colIdx];
  13863. const res = compareTableCells(cellA, cellB);
  13864. return dir === 'asc' ? res : -res;
  13865. });
  13866. }
  13867. // Check if rows are already in correct order to avoid modifying DOM
  13868. let alreadyOrdered = true;
  13869. let childIdx = 0;
  13870. for (const g of groups) {
  13871. if (tbody.children[childIdx] !== g.mainRow) {
  13872. alreadyOrdered = false;
  13873. break;
  13874. }
  13875. childIdx++;
  13876. for (const sub of g.subRows) {
  13877. if (tbody.children[childIdx] !== sub) {
  13878. alreadyOrdered = false;
  13879. break;
  13880. }
  13881. childIdx++;
  13882. }
  13883. }
  13884. if (alreadyOrdered) {
  13885. tbody._isSorting = false;
  13886. return;
  13887. }
  13888. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13889. if (tbody._sortObserver) {
  13890. tbody._sortObserver.disconnect();
  13891. }
  13892. // Re-append rows in sorted order
  13893. groups.forEach(g => {
  13894. tbody.appendChild(g.mainRow);
  13895. g.subRows.forEach(sub => tbody.appendChild(sub));
  13896. });
  13897. // Drain any queued mutations and re-connect observer
  13898. if (tbody._sortObserver) {
  13899. tbody._sortObserver.takeRecords();
  13900. tbody._sortObserver.observe(tbody, { childList: true });
  13901. }
  13902. tbody._isSorting = false;
  13903. }
  13904. function getCellRawText(cell) {
  13905. if (!cell) return '';
  13906. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13907. const input = cell.querySelector('input, select');
  13908. if (input) {
  13909. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13910. return input.value;
  13911. }
  13912. return cell.innerText.trim();
  13913. }
  13914. function parseTrafficToNumber(str) {
  13915. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13916. if (!m) return null;
  13917. const num = parseFloat(m[1].replace(/,/g, ''));
  13918. if (isNaN(num)) return null;
  13919. const unit = m[2].toUpperCase();
  13920. let mult = 1;
  13921. if (unit.startsWith('K')) mult = 1024;
  13922. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13923. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13924. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13925. return num * mult;
  13926. }
  13927. function parseIpToNumber(str) {
  13928. const clean = str.replace(/^[!~]/, '').trim();
  13929. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13930. if (!m) return null;
  13931. const o1 = parseInt(m[1], 10);
  13932. const o2 = parseInt(m[2], 10);
  13933. const o3 = parseInt(m[3], 10);
  13934. const o4 = parseInt(m[4], 10);
  13935. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13936. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13937. }
  13938. function parseCompoundPackets(str) {
  13939. const m = str.match(/^([\d,]+)p/);
  13940. if (!m) return null;
  13941. return parseInt(m[1].replace(/,/g, ''), 10);
  13942. }
  13943. function compareTableCells(cellA, cellB) {
  13944. const a = getCellRawText(cellA);
  13945. const b = getCellRawText(cellB);
  13946. if (a === '' && b !== '') return 1;
  13947. if (b === '' && a !== '') return -1;
  13948. if (a === b) return 0;
  13949. // 1. IP Addresses / CIDR
  13950. const ipA = parseIpToNumber(a);
  13951. const ipB = parseIpToNumber(b);
  13952. if (ipA !== null && ipB !== null) return ipA - ipB;
  13953. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13954. const pktA = parseCompoundPackets(a);
  13955. const pktB = parseCompoundPackets(b);
  13956. if (pktA !== null && pktB !== null) return pktA - pktB;
  13957. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13958. const trafA = parseTrafficToNumber(a);
  13959. const trafB = parseTrafficToNumber(b);
  13960. if (trafA !== null && trafB !== null) return trafA - trafB;
  13961. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13962. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13963. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13964. const numA = Number(cleanNumA);
  13965. const numB = Number(cleanNumB);
  13966. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13967. return numA - numB;
  13968. }
  13969. // 5. Natural case-insensitive string compare
  13970. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13971. }
  13972. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13973. async function loadVRRP(showToastNotification = false) {
  13974. try {
  13975. const [instRes, sumRes] = await Promise.all([
  13976. fetch(`${API_BASE}/vrrp/instances`),
  13977. fetch(`${API_BASE}/vrrp/summary`)
  13978. ]);
  13979. if (instRes.ok) {
  13980. state.vrrpInstances = await instRes.json();
  13981. renderVRRP();
  13982. }
  13983. if (sumRes.ok) {
  13984. state.vrrpSummary = await sumRes.json();
  13985. renderVRRPSummary();
  13986. }
  13987. if (showToastNotification) {
  13988. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13989. }
  13990. } catch (err) {
  13991. console.error('Failed to load VRRP:', err);
  13992. }
  13993. }
  13994. function renderVRRPSummary() {
  13995. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13996. const elTotal = document.getElementById('vrrp-stat-total');
  13997. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13998. const elMaster = document.getElementById('vrrp-stat-master');
  13999. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14000. const elBackup = document.getElementById('vrrp-stat-backup');
  14001. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14002. const bCount = document.getElementById('badge-vrrp-count');
  14003. if (bCount) bCount.innerText = s.total_instances || 0;
  14004. const dot = document.getElementById('badge-vrrp-dot');
  14005. if (dot) {
  14006. if (s.master_instances > 0) {
  14007. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14008. } else if (s.backup_instances > 0) {
  14009. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14010. } else {
  14011. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14012. }
  14013. }
  14014. }
  14015. function renderVRRP() {
  14016. const tbody = document.getElementById('vrrp-table-tbody');
  14017. const empty = document.getElementById('vrrp-table-empty');
  14018. if (!tbody) return;
  14019. tbody.innerHTML = '';
  14020. const instances = state.vrrpInstances || [];
  14021. if (instances.length === 0) {
  14022. empty?.classList.remove('hidden');
  14023. return;
  14024. }
  14025. empty?.classList.add('hidden');
  14026. instances.forEach(inst => {
  14027. const tr = document.createElement('tr');
  14028. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14029. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14030. 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>`;
  14031. if (inst.disabled) {
  14032. 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>`;
  14033. } else if (inst.state === 'MASTER') {
  14034. 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>`;
  14035. } else if (inst.state === 'BACKUP') {
  14036. 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>`;
  14037. } else if (inst.state === 'FAULT') {
  14038. 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>`;
  14039. }
  14040. // Render State Badge
  14041. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14042. if (!inst.disabled) {
  14043. if (inst.state === 'MASTER') {
  14044. 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>`;
  14045. } else if (inst.state === 'BACKUP') {
  14046. 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>`;
  14047. } else if (inst.state === 'FAULT') {
  14048. 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>`;
  14049. }
  14050. }
  14051. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14052. tr.innerHTML = `
  14053. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14054. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14055. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14056. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14057. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14058. <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>
  14059. <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>
  14060. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14061. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14062. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14063. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14064. <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>
  14065. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14066. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14067. </td>
  14068. `;
  14069. tbody.appendChild(tr);
  14070. });
  14071. }
  14072. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14073. const sel = document.getElementById(elemId);
  14074. if (!sel) return;
  14075. sel.innerHTML = '<option value="">Select interface...</option>';
  14076. const ifaces = state.interfaces || [];
  14077. ifaces.forEach(i => {
  14078. const opt = document.createElement('option');
  14079. opt.value = i.name;
  14080. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14081. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14082. sel.appendChild(opt);
  14083. });
  14084. }
  14085. function openAddVRRPModal() {
  14086. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14087. document.getElementById('modal-vrrp-id').value = '';
  14088. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14089. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14090. document.getElementById('modal-vrrp-priority').value = 100;
  14091. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14092. document.getElementById('modal-vrrp-version').value = '3';
  14093. document.getElementById('modal-vrrp-interval').value = 1;
  14094. document.getElementById('modal-vrrp-authtype').value = 'none';
  14095. document.getElementById('modal-vrrp-authpass').value = '';
  14096. document.getElementById('modal-vrrp-comment').value = '';
  14097. document.getElementById('modal-vrrp-preempt').checked = true;
  14098. document.getElementById('modal-vrrp-disabled').checked = false;
  14099. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14100. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14101. }
  14102. function openEditVRRPModal(id) {
  14103. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14104. if (!inst) return;
  14105. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14106. document.getElementById('modal-vrrp-id').value = inst.id;
  14107. document.getElementById('modal-vrrp-name').value = inst.name;
  14108. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14109. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14110. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14111. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14112. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14113. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14114. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14115. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14116. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14117. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14118. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14119. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14120. }
  14121. function closeVRRPModal() {
  14122. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14123. }
  14124. async function submitSaveVRRP(e) {
  14125. e.preventDefault();
  14126. const id = document.getElementById('modal-vrrp-id').value;
  14127. const name = document.getElementById('modal-vrrp-name').value.trim();
  14128. const iface = document.getElementById('modal-vrrp-iface').value;
  14129. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14130. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14131. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14132. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14133. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14134. const authType = document.getElementById('modal-vrrp-authtype').value;
  14135. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14136. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14137. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14138. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14139. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14140. try {
  14141. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14142. method: 'POST',
  14143. headers: { 'Content-Type': 'application/json' },
  14144. body: JSON.stringify({
  14145. id,
  14146. name,
  14147. interface: iface,
  14148. vrid,
  14149. priority,
  14150. virtual_ips: vips,
  14151. version,
  14152. interval,
  14153. auth_type: authType,
  14154. auth_password: authPass,
  14155. comment,
  14156. preempt,
  14157. disabled
  14158. })
  14159. });
  14160. if (res.ok) {
  14161. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14162. closeVRRPModal();
  14163. loadVRRP(false);
  14164. fetchData(false);
  14165. } else {
  14166. const err = await res.text();
  14167. showToast('Error', err, 'error');
  14168. }
  14169. } catch (err) {
  14170. showToast('Error', err.message, 'error');
  14171. }
  14172. }
  14173. async function deleteVRRP(id, name) {
  14174. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14175. try {
  14176. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14177. if (res.ok) {
  14178. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14179. loadVRRP(false);
  14180. fetchData(false);
  14181. } else {
  14182. const err = await res.text();
  14183. showToast('Error', err, 'error');
  14184. }
  14185. } catch (err) {
  14186. showToast('Error', err.message, 'error');
  14187. }
  14188. }
  14189. async function toggleVRRPState(id, disabled) {
  14190. try {
  14191. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14192. method: 'POST',
  14193. headers: { 'Content-Type': 'application/json' },
  14194. body: JSON.stringify({ disabled })
  14195. });
  14196. if (res.ok) {
  14197. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14198. loadVRRP(false);
  14199. fetchData(false);
  14200. } else {
  14201. const err = await res.text();
  14202. showToast('Error', err, 'error');
  14203. }
  14204. } catch (err) {
  14205. showToast('Error', err.message, 'error');
  14206. }
  14207. }
  14208. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14209. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14210. let docSortDebounce = null;
  14211. const docTableObserver = new MutationObserver((mutations) => {
  14212. let needsInit = false;
  14213. for (const m of mutations) {
  14214. for (const node of m.addedNodes) {
  14215. if (node.nodeType === 1) {
  14216. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14217. needsInit = true;
  14218. break;
  14219. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14220. needsInit = true;
  14221. break;
  14222. }
  14223. }
  14224. }
  14225. if (needsInit) break;
  14226. }
  14227. if (needsInit) {
  14228. clearTimeout(docSortDebounce);
  14229. docSortDebounce = setTimeout(initTableSorting, 100);
  14230. }
  14231. });
  14232. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14233. }
  14234. // =========================================================================
  14235. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14236. // =========================================================================
  14237. const bwtestState = {
  14238. running: false,
  14239. pollTimer: null,
  14240. eventSource: null,
  14241. chartPoints: [],
  14242. maxChartPoints: 60,
  14243. serverConfig: null,
  14244. peakTx: 0,
  14245. peakRx: 0,
  14246. targetDuration: 10,
  14247. lastSampleElapsed: -1,
  14248. sessionID: null
  14249. };
  14250. async function loadBwTestView() {
  14251. resizeBwTestCanvas();
  14252. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14253. }
  14254. async function fetchBwTestServerStatus() {
  14255. try {
  14256. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14257. if (!res.ok) return;
  14258. const s = await res.json();
  14259. bwtestState.serverConfig = s;
  14260. // Update indicator and badges
  14261. const indicator = document.getElementById('bwtest-server-indicator');
  14262. const badge = document.getElementById('bwtest-server-badge');
  14263. const sideBadge = document.getElementById('badge-bwtest-server');
  14264. if (s.enabled && s.running) {
  14265. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14266. if (badge) {
  14267. badge.innerText = `Port ${s.port} (Active)`;
  14268. badge.className = 'text-emerald-400 font-bold';
  14269. }
  14270. if (sideBadge) {
  14271. sideBadge.innerText = s.port;
  14272. 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';
  14273. }
  14274. } else {
  14275. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14276. if (badge) {
  14277. badge.innerText = `Disabled`;
  14278. badge.className = 'text-slate-500 font-bold';
  14279. }
  14280. if (sideBadge) {
  14281. sideBadge.innerText = 'Off';
  14282. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14283. }
  14284. }
  14285. // Modal fields
  14286. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14287. const serverModal = document.getElementById('modal-bwtest-server');
  14288. const editing = serverModal && !serverModal.classList.contains('hidden');
  14289. if (toggle && !editing) toggle.checked = !!s.enabled;
  14290. const portInp = document.getElementById('bwtest-server-port-input');
  14291. if (portInp && !editing) portInp.value = s.port || 2000;
  14292. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14293. if (actSess) actSess.innerText = s.active_sessions || 0;
  14294. const totServ = document.getElementById('bwtest-modal-total-served');
  14295. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14296. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14297. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14298. } catch (err) {
  14299. console.error('Failed to fetch BwTest server status:', err);
  14300. }
  14301. }
  14302. function openBwTestServerModal() {
  14303. const cfg = bwtestState.serverConfig;
  14304. if (cfg) {
  14305. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14306. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14307. }
  14308. fetchBwTestServerStatus();
  14309. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14310. }
  14311. function closeBwTestServerModal() {
  14312. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14313. }
  14314. async function submitBwTestServerSettings(e) {
  14315. e.preventDefault();
  14316. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14317. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14318. try {
  14319. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14320. method: 'POST',
  14321. headers: { 'Content-Type': 'application/json' },
  14322. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14323. });
  14324. if (!res.ok) {
  14325. const err = await res.json();
  14326. throw new Error(err.error || 'Failed to update server configuration');
  14327. }
  14328. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14329. closeBwTestServerModal();
  14330. fetchBwTestServerStatus();
  14331. } catch (err) {
  14332. showToast('Server Configuration Error', err.message, 'error');
  14333. }
  14334. }
  14335. function setBwTestTarget(target) {
  14336. const inp = document.getElementById('bwtest-input-target');
  14337. if (inp) inp.value = target;
  14338. }
  14339. function setBwTestProtocol(proto) {
  14340. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14341. if (hiddenInp) hiddenInp.value = proto;
  14342. const btnUdp = document.getElementById('bwtest-proto-udp');
  14343. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14344. const badge = document.getElementById('bwtest-proto-badge');
  14345. const pktField = document.getElementById('bwtest-field-pktsize');
  14346. 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';
  14347. 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';
  14348. 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';
  14349. if (proto === 'udp') {
  14350. if (btnUdp) {
  14351. btnUdp.className = activeUdpCls;
  14352. const dot = btnUdp.querySelector('span');
  14353. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14354. }
  14355. if (btnTcp) {
  14356. btnTcp.className = inactiveCls;
  14357. const dot = btnTcp.querySelector('span');
  14358. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14359. }
  14360. if (badge) {
  14361. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14362. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14363. }
  14364. if (pktField) pktField.classList.remove('opacity-40');
  14365. } else {
  14366. if (btnUdp) {
  14367. btnUdp.className = inactiveCls;
  14368. const dot = btnUdp.querySelector('span');
  14369. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14370. }
  14371. if (btnTcp) {
  14372. btnTcp.className = activeTcpCls;
  14373. const dot = btnTcp.querySelector('span');
  14374. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14375. }
  14376. if (badge) {
  14377. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14378. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14379. }
  14380. if (pktField) pktField.classList.add('opacity-40');
  14381. }
  14382. }
  14383. function setBwTestDirection(dir) {
  14384. const hiddenInp = document.getElementById('bwtest-input-direction');
  14385. if (hiddenInp) hiddenInp.value = dir;
  14386. const btnBoth = document.getElementById('bwtest-dir-both');
  14387. const btnTx = document.getElementById('bwtest-dir-tx');
  14388. const btnRx = document.getElementById('bwtest-dir-rx');
  14389. 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';
  14390. 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';
  14391. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14392. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14393. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14394. }
  14395. function setBwTestLimit(bps) {
  14396. const sel = document.getElementById('bwtest-input-limit');
  14397. if (sel) sel.value = String(bps);
  14398. }
  14399. async function checkActiveBwTest() {
  14400. try {
  14401. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14402. if (!res.ok) return;
  14403. const st = await res.json();
  14404. if (st.running) {
  14405. setBwTestRunningUI(true);
  14406. processBwTestStatus(st);
  14407. startBwTestTelemetry();
  14408. }
  14409. } catch (err) {
  14410. console.error('Failed to check active BwTest:', err);
  14411. }
  14412. }
  14413. async function startBwTest(e) {
  14414. if (e && e.preventDefault) e.preventDefault();
  14415. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14416. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14417. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14418. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14419. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14420. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14421. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14422. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14423. bwtestState.targetDuration = duration;
  14424. bwtestState.chartPoints = [];
  14425. bwtestState.peakTx = 0;
  14426. bwtestState.peakRx = 0;
  14427. bwtestState.lastSampleElapsed = -1;
  14428. bwtestState.sessionID = null;
  14429. // Clear UI elements
  14430. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14431. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14432. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14433. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14434. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14435. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14436. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14437. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14438. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14439. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14440. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14441. const tbody = document.getElementById('bwtest-samples-tbody');
  14442. if (tbody) tbody.innerHTML = '';
  14443. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14444. setBwTestRunningUI(true);
  14445. try {
  14446. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14447. method: 'POST',
  14448. headers: { 'Content-Type': 'application/json' },
  14449. body: JSON.stringify({
  14450. target,
  14451. port,
  14452. direction,
  14453. protocol,
  14454. bandwidth_limit,
  14455. packet_size,
  14456. streams,
  14457. duration
  14458. })
  14459. });
  14460. if (!res.ok) {
  14461. const err = await res.json();
  14462. throw new Error(err.error || 'Failed to start bandwidth test');
  14463. }
  14464. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14465. startBwTestTelemetry();
  14466. } catch (err) {
  14467. setBwTestRunningUI(false);
  14468. showToast('Start Failed', err.message, 'error');
  14469. }
  14470. }
  14471. function setBwTestRunningUI(running) {
  14472. bwtestState.running = running;
  14473. const startBtn = document.getElementById('bwtest-btn-start');
  14474. const stopBtn = document.getElementById('bwtest-btn-stop');
  14475. const badge = document.getElementById('bwtest-run-status-badge');
  14476. const ph = document.getElementById('bwtest-chart-placeholder');
  14477. if (running) {
  14478. if (startBtn) {
  14479. startBtn.disabled = true;
  14480. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14481. }
  14482. if (stopBtn) {
  14483. stopBtn.disabled = false;
  14484. stopBtn.classList.remove('opacity-40');
  14485. }
  14486. if (badge) {
  14487. badge.innerText = 'TESTING...';
  14488. 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';
  14489. }
  14490. if (ph) ph.style.display = 'none';
  14491. } else {
  14492. if (startBtn) {
  14493. startBtn.disabled = false;
  14494. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14495. }
  14496. if (stopBtn) {
  14497. stopBtn.disabled = true;
  14498. stopBtn.classList.add('opacity-40');
  14499. }
  14500. if (badge) {
  14501. badge.innerText = 'IDLE';
  14502. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14503. }
  14504. }
  14505. }
  14506. async function stopBwTest() {
  14507. try {
  14508. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14509. if (!res.ok) throw new Error(await responseError(res));
  14510. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14511. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14512. } catch (err) {
  14513. showToast('Stop Failed', err.message, 'error');
  14514. }
  14515. }
  14516. async function responseError(res) {
  14517. const text = await res.text();
  14518. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14519. catch { return text || `HTTP ${res.status}`; }
  14520. }
  14521. function processBwTestStatus(st) {
  14522. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14523. bwtestState.sessionID = st.session_id;
  14524. bwtestState.lastSampleElapsed = -1;
  14525. }
  14526. for (const sample of st.recent_samples || []) {
  14527. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14528. handleBwTestSample(sample);
  14529. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14530. }
  14531. }
  14532. if (!st.running) {
  14533. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14534. bwtestState.pollTimer = null;
  14535. setBwTestRunningUI(false);
  14536. handleBwTestFinish(st.summary, st.error);
  14537. }
  14538. }
  14539. function startBwTestTelemetry() {
  14540. if (!state.currentUser) return;
  14541. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14542. let busy = false;
  14543. const poll = async () => {
  14544. if (busy || !state.currentUser || document.hidden) return;
  14545. busy = true;
  14546. try {
  14547. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14548. if (!res.ok) throw new Error(await responseError(res));
  14549. processBwTestStatus(await res.json());
  14550. } catch (err) {
  14551. console.error('BwTest polling error:', err);
  14552. } finally { busy = false; }
  14553. };
  14554. bwtestState.pollTimer = setInterval(poll, 400);
  14555. poll();
  14556. }
  14557. function handleBwTestSample(s) {
  14558. if (!s) return;
  14559. const payloadHint = document.getElementById('bwtest-effective-payload');
  14560. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14561. const txMbps = s.tx_mbps || 0;
  14562. const rxMbps = s.rx_mbps || 0;
  14563. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14564. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14565. // KPI updates
  14566. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14567. if (elTx) {
  14568. elTx.innerText = txMbps.toFixed(2);
  14569. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14570. }
  14571. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14572. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14573. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14574. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14575. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14576. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14577. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14578. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14579. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14580. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14581. const elLoss = document.getElementById('bwtest-stat-loss');
  14582. if (elLoss) {
  14583. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14584. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14585. }
  14586. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14587. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14588. const elJitter = document.getElementById('bwtest-stat-jitter');
  14589. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14590. const elTime = document.getElementById('bwtest-stat-time');
  14591. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14592. const elData = document.getElementById('bwtest-stat-data');
  14593. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14594. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14595. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14596. // Append point to chart buffer
  14597. bwtestState.chartPoints.push({
  14598. elapsed: s.elapsed_sec || 0,
  14599. tx: txMbps,
  14600. rx: rxMbps
  14601. });
  14602. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14603. bwtestState.chartPoints.shift();
  14604. }
  14605. drawBwTestChart();
  14606. // Add row to breakdown table
  14607. const tbody = document.getElementById('bwtest-samples-tbody');
  14608. if (tbody) {
  14609. const tr = document.createElement('tr');
  14610. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14611. tr.innerHTML = `
  14612. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14613. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14614. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14615. <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>
  14616. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14617. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14618. `;
  14619. tbody.insertBefore(tr, tbody.firstChild);
  14620. const countEl = document.getElementById('bwtest-sample-count');
  14621. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14622. }
  14623. }
  14624. function handleBwTestFinish(summary, error) {
  14625. const badge = document.getElementById('bwtest-run-status-badge');
  14626. if (error) {
  14627. showToast('Benchmark Error', error, 'error');
  14628. if (badge) {
  14629. badge.innerText = 'ERROR';
  14630. 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';
  14631. }
  14632. } else if (summary) {
  14633. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14634. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14635. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14636. if (badge) {
  14637. badge.innerText = 'COMPLETED';
  14638. 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';
  14639. }
  14640. }
  14641. loadBwTestHistory();
  14642. fetchBwTestServerStatus();
  14643. }
  14644. function resizeBwTestCanvas() {
  14645. const canvas = document.getElementById('bwtest-chart');
  14646. if (!canvas || !canvas.parentElement) return;
  14647. const rect = canvas.parentElement.getBoundingClientRect();
  14648. const dpr = window.devicePixelRatio || 1;
  14649. canvas.width = rect.width * dpr;
  14650. canvas.height = rect.height * dpr;
  14651. const ctx = canvas.getContext('2d');
  14652. ctx.scale(dpr, dpr);
  14653. drawBwTestChart();
  14654. }
  14655. window.addEventListener('resize', () => {
  14656. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14657. });
  14658. function drawBwTestChart() {
  14659. const canvas = document.getElementById('bwtest-chart');
  14660. if (!canvas) return;
  14661. const ctx = canvas.getContext('2d');
  14662. const dpr = window.devicePixelRatio || 1;
  14663. const width = canvas.width / dpr;
  14664. const height = canvas.height / dpr;
  14665. ctx.clearRect(0, 0, width, height);
  14666. const points = bwtestState.chartPoints;
  14667. if (!points || points.length === 0) return;
  14668. // Determine scale ceiling
  14669. let maxRate = 10;
  14670. for (const p of points) {
  14671. if (p.tx > maxRate) maxRate = p.tx;
  14672. if (p.rx > maxRate) maxRate = p.rx;
  14673. }
  14674. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14675. const paddingLeft = 55;
  14676. const paddingBottom = 24;
  14677. const paddingTop = 12;
  14678. const paddingRight = 16;
  14679. const chartW = width - paddingLeft - paddingRight;
  14680. const chartH = height - paddingTop - paddingBottom;
  14681. // Grid Lines and Y-Axis labels
  14682. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14683. ctx.lineWidth = 1;
  14684. ctx.fillStyle = '#94a3b8';
  14685. ctx.font = '10px monospace';
  14686. ctx.textAlign = 'right';
  14687. const gridSteps = 4;
  14688. for (let i = 0; i <= gridSteps; i++) {
  14689. const val = (maxRate / gridSteps) * i;
  14690. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14691. ctx.beginPath();
  14692. ctx.moveTo(paddingLeft, y);
  14693. ctx.lineTo(width - paddingRight, y);
  14694. ctx.stroke();
  14695. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14696. }
  14697. // Draw TX Line (Cyan #22d3ee)
  14698. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14699. // Draw RX Line (Purple #a855f7)
  14700. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14701. }
  14702. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14703. if (points.length < 2) return;
  14704. const stepX = w / Math.max(points.length - 1, 1);
  14705. // Gradient area fill
  14706. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14707. grad.addColorStop(0, fillColor);
  14708. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14709. ctx.beginPath();
  14710. points.forEach((p, idx) => {
  14711. const x = left + idx * stepX;
  14712. const val = valFn(p);
  14713. const y = top + h - (val / maxVal) * h;
  14714. if (idx === 0) {
  14715. ctx.moveTo(x, y);
  14716. } else {
  14717. ctx.lineTo(x, y);
  14718. }
  14719. });
  14720. // Complete path for fill
  14721. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14722. ctx.lineTo(left, top + h);
  14723. ctx.closePath();
  14724. ctx.fillStyle = grad;
  14725. ctx.fill();
  14726. // Draw line stroke
  14727. ctx.beginPath();
  14728. ctx.lineWidth = 2.5;
  14729. ctx.strokeStyle = strokeColor;
  14730. points.forEach((p, idx) => {
  14731. const x = left + idx * stepX;
  14732. const val = valFn(p);
  14733. const y = top + h - (val / maxVal) * h;
  14734. if (idx === 0) {
  14735. ctx.moveTo(x, y);
  14736. } else {
  14737. ctx.lineTo(x, y);
  14738. }
  14739. });
  14740. ctx.stroke();
  14741. // Draw end point halo
  14742. const lastP = points[points.length - 1];
  14743. const lastX = left + (points.length - 1) * stepX;
  14744. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14745. ctx.fillStyle = strokeColor;
  14746. ctx.beginPath();
  14747. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14748. ctx.fill();
  14749. }
  14750. async function loadBwTestHistory() {
  14751. try {
  14752. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14753. if (!res.ok) return;
  14754. const list = await res.json();
  14755. renderBwTestHistory(Array.isArray(list) ? list : []);
  14756. } catch (err) {
  14757. console.error('Failed to load BwTest history:', err);
  14758. }
  14759. }
  14760. function renderBwTestHistory(list) {
  14761. const tbody = document.getElementById('bwtest-history-tbody');
  14762. if (!tbody) return;
  14763. if (list.length === 0) {
  14764. 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>`;
  14765. return;
  14766. }
  14767. tbody.innerHTML = '';
  14768. list.forEach(item => {
  14769. const s = item.summary || {};
  14770. const tr = document.createElement('tr');
  14771. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14772. const dirBadge = item.direction === 'both'
  14773. ? `<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>`
  14774. : item.direction === 'tx'
  14775. ? `<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>`
  14776. : `<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>`;
  14777. const protoBadge = item.protocol === 'tcp'
  14778. ? `<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>`
  14779. : `<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>`;
  14780. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14781. tr.innerHTML = `
  14782. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14783. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14784. <td class="py-2.5 px-4">${protoBadge}</td>
  14785. <td class="py-2.5 px-4">${dirBadge}</td>
  14786. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14787. <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>
  14788. <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>
  14789. <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>
  14790. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14791. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14792. `;
  14793. tbody.appendChild(tr);
  14794. });
  14795. }
  14796. // ======================== SETTINGS & ROUTER DNS ========================
  14797. state.settingsSubTab = 'dns';
  14798. state.dnsSettings = null;
  14799. state.dnsStaticRecords = [];
  14800. state.dnsStatus = null;
  14801. function switchSettingsSubTab(sub) {
  14802. state.settingsSubTab = sub;
  14803. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14804. const btnSys = document.getElementById('btn-settings-subtab-system');
  14805. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14806. const tabDns = document.getElementById('settings-subtab-dns');
  14807. const tabSys = document.getElementById('settings-subtab-system');
  14808. const tabBak = document.getElementById('settings-subtab-backup');
  14809. const activeClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5 cursor-pointer';
  14810. const inactiveClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5 cursor-pointer';
  14811. if (btnDns) btnDns.className = inactiveClass;
  14812. if (btnSys) btnSys.className = inactiveClass;
  14813. if (btnBak) btnBak.className = inactiveClass;
  14814. tabDns?.classList.add('hidden');
  14815. tabSys?.classList.add('hidden');
  14816. tabBak?.classList.add('hidden');
  14817. if (sub === 'dns') {
  14818. if (btnDns) btnDns.className = activeClass;
  14819. tabDns?.classList.remove('hidden');
  14820. loadDNSSettings();
  14821. } else if (sub === 'system') {
  14822. if (btnSys) btnSys.className = activeClass;
  14823. tabSys?.classList.remove('hidden');
  14824. loadSystemSettings();
  14825. } else if (sub === 'backup') {
  14826. if (btnBak) btnBak.className = activeClass;
  14827. tabBak?.classList.remove('hidden');
  14828. loadBackupList();
  14829. }
  14830. }
  14831. async function loadSettingsData(showLoading = false) {
  14832. if (state.settingsSubTab === 'system') {
  14833. await loadSystemSettings();
  14834. } else if (state.settingsSubTab === 'backup') {
  14835. await loadBackupList();
  14836. } else {
  14837. await loadDNSSettings();
  14838. }
  14839. }
  14840. async function loadDNSSettings() {
  14841. try {
  14842. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14843. fetch(`${API_BASE}/dns/settings`),
  14844. fetch(`${API_BASE}/dns/static`),
  14845. fetch(`${API_BASE}/dns/status`)
  14846. ]);
  14847. if (settingsRes.ok) {
  14848. state.dnsSettings = await settingsRes.json();
  14849. populateDNSSettingsForm(state.dnsSettings);
  14850. }
  14851. if (staticRes.ok) {
  14852. state.dnsStaticRecords = await staticRes.json();
  14853. renderStaticDNSList();
  14854. }
  14855. if (statusRes.ok) {
  14856. state.dnsStatus = await statusRes.json();
  14857. updateDNSStatusView(state.dnsStatus);
  14858. }
  14859. } catch (err) {
  14860. console.error('Failed to load DNS settings:', err);
  14861. }
  14862. }
  14863. function populateDNSSettingsForm(s) {
  14864. if (!s) return;
  14865. const dnsForm = document.getElementById('form-dns-settings');
  14866. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14867. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14868. if (dynamicEl) {
  14869. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14870. 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(' ');
  14871. } else {
  14872. dynamicEl.innerText = 'None';
  14873. }
  14874. }
  14875. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14876. if (isEditing) return;
  14877. const serversInput = document.getElementById('dns-servers-input');
  14878. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14879. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14880. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14881. const domainInput = document.getElementById('dns-domain-input');
  14882. if (domainInput) domainInput.value = s.domain || '';
  14883. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14884. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14885. }
  14886. function updateDNSStatusView(st) {
  14887. if (!st) return;
  14888. const preview = document.getElementById('dns-resolv-preview');
  14889. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14890. const pillText = document.getElementById('dns-live-status-text');
  14891. const pill = document.getElementById('dns-live-status-pill');
  14892. if (pill && pillText) {
  14893. if (st.service_running) {
  14894. 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';
  14895. pillText.innerText = 'DNS Service Active';
  14896. } else {
  14897. 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';
  14898. pillText.innerText = 'DNS Service Inactive';
  14899. }
  14900. }
  14901. }
  14902. function appendDNSPreset(preset) {
  14903. const input = document.getElementById('dns-servers-input');
  14904. if (!input) return;
  14905. const dnsForm = document.getElementById('form-dns-settings');
  14906. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14907. const current = input.value.trim();
  14908. if (!current) {
  14909. input.value = preset;
  14910. } else {
  14911. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14912. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14913. toAdd.forEach(ip => {
  14914. if (!existing.includes(ip)) existing.push(ip);
  14915. });
  14916. input.value = existing.join(', ');
  14917. }
  14918. }
  14919. async function saveDNSSettings(e) {
  14920. e.preventDefault();
  14921. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14922. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14923. if (servers.length === 0) {
  14924. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14925. return;
  14926. }
  14927. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14928. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14929. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14930. try {
  14931. const res = await fetch(`${API_BASE}/dns/settings`, {
  14932. method: 'POST',
  14933. headers: { 'Content-Type': 'application/json' },
  14934. body: JSON.stringify({
  14935. servers: servers,
  14936. cache_size: cacheSize,
  14937. domain: domain,
  14938. allow_remote_requests: allowRemote
  14939. })
  14940. });
  14941. const data = await res.json();
  14942. if (res.ok) {
  14943. const dnsForm = document.getElementById('form-dns-settings');
  14944. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14945. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14946. loadDNSSettings();
  14947. } else {
  14948. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14949. }
  14950. } catch (err) {
  14951. showToast('Error', err.message, 'error');
  14952. }
  14953. }
  14954. async function flushDNSCache() {
  14955. try {
  14956. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14957. if (res.ok) {
  14958. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14959. loadDNSSettings();
  14960. } else {
  14961. const err = await res.json();
  14962. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14963. }
  14964. } catch (err) {
  14965. showToast('Error', err.message, 'error');
  14966. }
  14967. }
  14968. function renderStaticDNSList() {
  14969. const tbody = document.getElementById('dns-static-tbody');
  14970. const empty = document.getElementById('dns-static-empty');
  14971. const badge = document.getElementById('dns-static-count-badge');
  14972. if (!tbody) return;
  14973. tbody.innerHTML = '';
  14974. const records = state.dnsStaticRecords || [];
  14975. if (badge) badge.innerText = `${records.length} Records`;
  14976. if (records.length === 0) {
  14977. empty?.classList.remove('hidden');
  14978. return;
  14979. }
  14980. empty?.classList.add('hidden');
  14981. records.forEach(rec => {
  14982. const tr = document.createElement('tr');
  14983. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14984. tr.innerHTML = `
  14985. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14986. <td class="py-2.5 px-4">
  14987. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14988. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14989. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14990. }">
  14991. ${rec.type || 'A'}
  14992. </span>
  14993. </td>
  14994. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14995. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14996. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14997. <td class="py-2.5 px-4">
  14998. <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'}">
  14999. ${rec.disabled ? 'Disabled' : 'Active'}
  15000. </span>
  15001. </td>
  15002. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15003. <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>
  15004. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15005. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15006. </td>
  15007. `;
  15008. tbody.appendChild(tr);
  15009. });
  15010. }
  15011. function openStaticDNSModal(id = null) {
  15012. const modal = document.getElementById('modal-static-dns');
  15013. const title = document.getElementById('modal-static-dns-title');
  15014. const form = document.getElementById('form-static-dns');
  15015. if (!modal || !form) return;
  15016. form.reset();
  15017. document.getElementById('modal-static-dns-id').value = '';
  15018. if (id) {
  15019. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15020. if (rec) {
  15021. if (title) title.innerText = 'Edit Static DNS Record';
  15022. document.getElementById('modal-static-dns-id').value = rec.id;
  15023. document.getElementById('modal-static-dns-name').value = rec.name;
  15024. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15025. document.getElementById('modal-static-dns-addr').value = rec.address;
  15026. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15027. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15028. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15029. }
  15030. } else {
  15031. if (title) title.innerText = 'Add Static DNS Record';
  15032. }
  15033. modal.classList.remove('hidden');
  15034. }
  15035. function closeStaticDNSModal() {
  15036. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15037. }
  15038. async function submitSaveStaticDNS(e) {
  15039. e.preventDefault();
  15040. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15041. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15042. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15043. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15044. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15045. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15046. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15047. if (!name || !address) {
  15048. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15049. return;
  15050. }
  15051. try {
  15052. const res = await fetch(`${API_BASE}/dns/static`, {
  15053. method: 'POST',
  15054. headers: { 'Content-Type': 'application/json' },
  15055. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15056. });
  15057. const data = await res.json();
  15058. if (res.ok) {
  15059. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15060. closeStaticDNSModal();
  15061. loadDNSSettings();
  15062. } else {
  15063. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15064. }
  15065. } catch (err) {
  15066. showToast('Error', err.message, 'error');
  15067. }
  15068. }
  15069. async function deleteStaticDNS(id) {
  15070. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15071. try {
  15072. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15073. if (res.ok) {
  15074. showToast('Deleted', 'Static DNS record deleted', 'success');
  15075. loadDNSSettings();
  15076. }
  15077. } catch (err) {
  15078. showToast('Error', err.message, 'error');
  15079. }
  15080. }
  15081. async function toggleStaticDNS(id, disabled) {
  15082. try {
  15083. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15084. method: 'POST',
  15085. headers: { 'Content-Type': 'application/json' },
  15086. body: JSON.stringify({ disabled })
  15087. });
  15088. if (res.ok) {
  15089. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15090. loadDNSSettings();
  15091. }
  15092. } catch (err) {
  15093. showToast('Error', err.message, 'error');
  15094. }
  15095. }
  15096. async function loadSystemSettings() {
  15097. try {
  15098. const sysForm = document.getElementById('form-system-settings');
  15099. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15100. const res = await fetch(`${API_BASE}/system/settings`);
  15101. if (res.ok) {
  15102. const data = await res.json();
  15103. if (!isEditing) {
  15104. const hostInput = document.getElementById('system-hostname-input');
  15105. if (hostInput) hostInput.value = data.hostname || '';
  15106. const tzInput = document.getElementById('system-timezone-input');
  15107. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15108. }
  15109. }
  15110. } catch (err) {
  15111. console.error('Failed to load system settings:', err);
  15112. }
  15113. }
  15114. async function saveSystemSettings(e) {
  15115. e.preventDefault();
  15116. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15117. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15118. try {
  15119. const res = await fetch(`${API_BASE}/system/settings`, {
  15120. method: 'POST',
  15121. headers: { 'Content-Type': 'application/json' },
  15122. body: JSON.stringify({ hostname, timezone })
  15123. });
  15124. const data = await res.json();
  15125. if (res.ok) {
  15126. const sysForm = document.getElementById('form-system-settings');
  15127. if (sysForm) sysForm.dataset.dirty = 'false';
  15128. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15129. const sideH = document.getElementById('side-hostname');
  15130. if (sideH) sideH.innerText = data.hostname;
  15131. } else {
  15132. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15133. }
  15134. } catch (err) {
  15135. showToast('Error', err.message, 'error');
  15136. }
  15137. }
  15138. // =============================================================================
  15139. // BACKUP & RESTORE MANAGER
  15140. // =============================================================================
  15141. state.selectedBackupFile = null;
  15142. state.inspectedBackupManifest = null;
  15143. state.pendingRestoreTarget = null;
  15144. state.backupsList = [];
  15145. async function exportBackupDownload() {
  15146. const btn = document.getElementById('btn-export-backup');
  15147. const commentInput = document.getElementById('backup-export-comment');
  15148. const comment = (commentInput?.value || '').trim();
  15149. const originalHtml = btn ? btn.innerHTML : '';
  15150. if (btn) {
  15151. btn.disabled = true;
  15152. btn.innerHTML = `<span class="w-3.5 h-3.5 rounded-full border-2 border-white border-t-transparent animate-spin inline-block"></span> Generating Backup...`;
  15153. }
  15154. try {
  15155. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15156. if (!res.ok) {
  15157. const err = await res.json().catch(() => ({}));
  15158. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15159. return;
  15160. }
  15161. const blob = await res.blob();
  15162. const disposition = res.headers.get('Content-Disposition') || '';
  15163. let filename = 'debtik-backup.zip';
  15164. const match = disposition.match(/filename="?([^";]+)"?/);
  15165. if (match && match[1]) {
  15166. filename = match[1];
  15167. }
  15168. const blobUrl = window.URL.createObjectURL(blob);
  15169. const a = document.createElement('a');
  15170. a.href = blobUrl;
  15171. a.download = filename;
  15172. document.body.appendChild(a);
  15173. a.click();
  15174. setTimeout(() => {
  15175. window.URL.revokeObjectURL(blobUrl);
  15176. a.remove();
  15177. }, 1000);
  15178. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15179. } catch (err) {
  15180. showToast('Export Error', err.message || 'Network error during download', 'error');
  15181. } finally {
  15182. if (btn) {
  15183. btn.disabled = false;
  15184. btn.innerHTML = originalHtml;
  15185. }
  15186. }
  15187. }
  15188. async function onBackupFileSelected(e) {
  15189. const file = e.target.files?.[0];
  15190. if (!file) return;
  15191. const label = document.getElementById('backup-file-label');
  15192. if (label) {
  15193. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15194. }
  15195. await inspectBackupFile(file);
  15196. }
  15197. async function inspectBackupFile(file) {
  15198. const preview = document.getElementById('backup-inspect-preview');
  15199. const restoreBtn = document.getElementById('btn-restore-backup');
  15200. const formData = new FormData();
  15201. formData.append('backup', file);
  15202. try {
  15203. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15204. method: 'POST',
  15205. body: formData
  15206. });
  15207. const data = await res.json();
  15208. if (!res.ok || !data.success || !data.manifest) {
  15209. if (preview) preview.classList.add('hidden');
  15210. if (restoreBtn) restoreBtn.disabled = true;
  15211. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15212. return;
  15213. }
  15214. const mf = data.manifest;
  15215. state.selectedBackupFile = file;
  15216. state.inspectedBackupManifest = mf;
  15217. const vEl = document.getElementById('backup-inspect-version');
  15218. const hEl = document.getElementById('backup-inspect-hostname');
  15219. const fEl = document.getElementById('backup-inspect-files');
  15220. const dEl = document.getElementById('backup-inspect-date');
  15221. const cEl = document.getElementById('backup-inspect-comment');
  15222. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15223. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15224. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15225. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15226. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15227. if (preview) preview.classList.remove('hidden');
  15228. if (restoreBtn) restoreBtn.disabled = false;
  15229. } catch (err) {
  15230. if (preview) preview.classList.add('hidden');
  15231. if (restoreBtn) restoreBtn.disabled = true;
  15232. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15233. }
  15234. }
  15235. function confirmRestoreBackup(localFilename = null) {
  15236. const modal = document.getElementById('modal-restore-confirm');
  15237. const details = document.getElementById('modal-restore-details');
  15238. const progress = document.getElementById('modal-restore-progress');
  15239. const cancelBtn = document.getElementById('btn-cancel-restore');
  15240. const execBtn = document.getElementById('btn-execute-restore');
  15241. if (progress) progress.classList.add('hidden');
  15242. if (cancelBtn) cancelBtn.disabled = false;
  15243. if (execBtn) {
  15244. execBtn.disabled = false;
  15245. execBtn.innerText = 'Yes, Restore & Reload';
  15246. }
  15247. if (localFilename) {
  15248. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15249. if (details) {
  15250. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15251. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15252. }
  15253. } else {
  15254. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15255. showToast('Error', 'Please select a valid backup archive first', 'error');
  15256. return;
  15257. }
  15258. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15259. const mf = state.inspectedBackupManifest;
  15260. if (details) {
  15261. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15262. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15263. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15264. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15265. }
  15266. }
  15267. if (modal) modal.classList.remove('hidden');
  15268. }
  15269. function closeRestoreModal() {
  15270. const modal = document.getElementById('modal-restore-confirm');
  15271. if (modal) modal.classList.add('hidden');
  15272. }
  15273. async function executeRestoreBackup() {
  15274. const target = state.pendingRestoreTarget;
  15275. if (!target) return;
  15276. const progress = document.getElementById('modal-restore-progress');
  15277. const progressText = document.getElementById('modal-restore-progress-text');
  15278. const cancelBtn = document.getElementById('btn-cancel-restore');
  15279. const execBtn = document.getElementById('btn-execute-restore');
  15280. if (cancelBtn) cancelBtn.disabled = true;
  15281. if (execBtn) execBtn.disabled = true;
  15282. if (progress) progress.classList.remove('hidden');
  15283. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15284. try {
  15285. let res;
  15286. if (target.type === 'file') {
  15287. const formData = new FormData();
  15288. formData.append('backup', target.file);
  15289. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15290. method: 'POST',
  15291. body: formData
  15292. });
  15293. } else {
  15294. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15295. method: 'POST'
  15296. });
  15297. }
  15298. const data = await res.json();
  15299. if (!res.ok || !data.success) {
  15300. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15301. if (cancelBtn) cancelBtn.disabled = false;
  15302. if (execBtn) execBtn.disabled = false;
  15303. if (progress) progress.classList.add('hidden');
  15304. return;
  15305. }
  15306. if (progressText) {
  15307. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15308. }
  15309. pollAfterRestoreReconnect();
  15310. } catch (err) {
  15311. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15312. if (cancelBtn) cancelBtn.disabled = false;
  15313. if (execBtn) execBtn.disabled = false;
  15314. if (progress) progress.classList.add('hidden');
  15315. }
  15316. }
  15317. function pollAfterRestoreReconnect() {
  15318. let attempts = 0;
  15319. const maxAttempts = 25;
  15320. const timer = setInterval(async () => {
  15321. attempts++;
  15322. try {
  15323. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15324. if (res.ok) {
  15325. clearInterval(timer);
  15326. closeRestoreModal();
  15327. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15328. setTimeout(() => {
  15329. window.location.reload();
  15330. }, 1200);
  15331. }
  15332. } catch (_) {
  15333. // Still restarting, retry
  15334. }
  15335. if (attempts >= maxAttempts) {
  15336. clearInterval(timer);
  15337. closeRestoreModal();
  15338. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15339. }
  15340. }, 1500);
  15341. }
  15342. async function loadBackupList() {
  15343. const tbody = document.getElementById('backups-table-tbody');
  15344. const empty = document.getElementById('backups-empty-state');
  15345. if (!tbody) return;
  15346. try {
  15347. const res = await fetch(`${API_BASE}/system/backups`);
  15348. if (!res.ok) return;
  15349. const list = await res.json();
  15350. state.backupsList = list || [];
  15351. renderBackupsTable(state.backupsList);
  15352. } catch (err) {
  15353. console.error('Failed to load backup list:', err);
  15354. }
  15355. }
  15356. function renderBackupsTable(backups) {
  15357. const tbody = document.getElementById('backups-table-tbody');
  15358. const empty = document.getElementById('backups-empty-state');
  15359. if (!tbody) return;
  15360. if (!backups || backups.length === 0) {
  15361. tbody.innerHTML = '';
  15362. if (empty) empty.classList.remove('hidden');
  15363. return;
  15364. }
  15365. if (empty) empty.classList.add('hidden');
  15366. tbody.innerHTML = backups.map(bk => {
  15367. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15368. const badge = isAuto
  15369. ? `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-amber-500/10 text-amber-300 border border-amber-500/20">PRE-RESTORE</span>`
  15370. : `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-cyan-500/10 text-cyan-300 border border-cyan-500/20">MANUAL</span>`;
  15371. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15372. return `<tr class="hover:bg-slate-800/40 transition">
  15373. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15374. ${badge}
  15375. <span>${escapeHtml(bk.filename)}</span>
  15376. </td>
  15377. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15378. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15379. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15380. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15381. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15382. <td class="py-3 px-4 text-right space-x-2">
  15383. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15384. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-cyan-400 border border-slate-700 transition cursor-pointer">
  15385. Download
  15386. </button>
  15387. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15388. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-amber-600/20 hover:bg-amber-600/30 text-amber-300 border border-amber-500/30 transition cursor-pointer">
  15389. Restore
  15390. </button>
  15391. </td>
  15392. </tr>`;
  15393. }).join('');
  15394. }
  15395. async function downloadLocalBackup(filename) {
  15396. try {
  15397. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15398. if (!res.ok) {
  15399. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15400. return;
  15401. }
  15402. const blob = await res.blob();
  15403. const blobUrl = window.URL.createObjectURL(blob);
  15404. const a = document.createElement('a');
  15405. a.href = blobUrl;
  15406. a.download = filename;
  15407. document.body.appendChild(a);
  15408. a.click();
  15409. setTimeout(() => {
  15410. window.URL.revokeObjectURL(blobUrl);
  15411. a.remove();
  15412. }, 1000);
  15413. } catch (err) {
  15414. showToast('Download Error', err.message, 'error');
  15415. }
  15416. }
  15417. // =============================================================================
  15418. // AUTHENTICATION & USER MANAGER
  15419. // =============================================================================
  15420. async function checkAuthStatus() {
  15421. try {
  15422. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15423. headers: {
  15424. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15425. }
  15426. });
  15427. if (res.ok) {
  15428. const user = await res.json();
  15429. state.currentUser = user;
  15430. updateUserProfileHeader(user);
  15431. hideLoginScreen();
  15432. state.isPolling = true;
  15433. fetchData();
  15434. initLiveTrafficStream();
  15435. return true;
  15436. } else {
  15437. showLoginScreen(false);
  15438. return false;
  15439. }
  15440. } catch (err) {
  15441. showLoginScreen(false);
  15442. return false;
  15443. }
  15444. }
  15445. function showLoginScreen(isExpired = false) {
  15446. const el = document.getElementById('login-screen');
  15447. if (el) el.classList.remove('hidden');
  15448. const errEl = document.getElementById('login-error');
  15449. const errTxt = document.getElementById('login-error-text');
  15450. if (isExpired && errEl && errTxt) {
  15451. errTxt.innerText = 'Session expired. Please sign in again.';
  15452. errEl.classList.remove('hidden');
  15453. } else if (errEl) {
  15454. errEl.classList.add('hidden');
  15455. }
  15456. const pwInput = document.getElementById('login-password');
  15457. if (pwInput) pwInput.value = '';
  15458. const userInput = document.getElementById('login-username');
  15459. if (userInput && !userInput.value) userInput.focus();
  15460. else if (pwInput) pwInput.focus();
  15461. }
  15462. function hideLoginScreen() {
  15463. const el = document.getElementById('login-screen');
  15464. if (el) el.classList.add('hidden');
  15465. const errEl = document.getElementById('login-error');
  15466. if (errEl) errEl.classList.add('hidden');
  15467. }
  15468. async function handleLoginSubmit(event) {
  15469. event.preventDefault();
  15470. const username = (document.getElementById('login-username')?.value || '').trim();
  15471. const password = document.getElementById('login-password')?.value || '';
  15472. const errEl = document.getElementById('login-error');
  15473. const errTxt = document.getElementById('login-error-text');
  15474. const btn = document.getElementById('login-submit-btn');
  15475. const btnText = document.getElementById('login-btn-text');
  15476. const spinner = document.getElementById('login-btn-spinner');
  15477. if (!username || !password) {
  15478. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15479. if (errEl) errEl.classList.remove('hidden');
  15480. return;
  15481. }
  15482. if (errEl) errEl.classList.add('hidden');
  15483. if (btn) btn.disabled = true;
  15484. if (btnText) btnText.innerText = 'Authenticating...';
  15485. if (spinner) spinner.classList.remove('hidden');
  15486. try {
  15487. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15488. method: 'POST',
  15489. headers: { 'Content-Type': 'application/json' },
  15490. body: JSON.stringify({ username, password })
  15491. });
  15492. const data = await res.json();
  15493. if (res.ok && data.success) {
  15494. localStorage.setItem('debtik_token', data.token);
  15495. state.currentUser = data.user;
  15496. updateUserProfileHeader(data.user);
  15497. hideLoginScreen();
  15498. state.isPolling = true;
  15499. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15500. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15501. navigate(hash);
  15502. fetchData();
  15503. initLiveTrafficStream();
  15504. // Ensure background telemetry polling is active
  15505. if (!window._telemetryInterval) {
  15506. window._telemetryInterval = setInterval(() => {
  15507. if (state.isPolling && state.currentUser && !document.hidden) {
  15508. fetchData(false);
  15509. }
  15510. }, 5000);
  15511. }
  15512. } else {
  15513. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15514. if (errEl) errEl.classList.remove('hidden');
  15515. }
  15516. } catch (err) {
  15517. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15518. if (errEl) errEl.classList.remove('hidden');
  15519. } finally {
  15520. if (btn) btn.disabled = false;
  15521. if (btnText) btnText.innerText = 'Sign In to Controller';
  15522. if (spinner) spinner.classList.add('hidden');
  15523. }
  15524. }
  15525. async function handleLogoutClick() {
  15526. try {
  15527. await originalFetch(`${API_BASE}/auth/logout`, {
  15528. method: 'POST',
  15529. headers: {
  15530. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15531. }
  15532. });
  15533. } catch (e) {}
  15534. stopSessionPolling();
  15535. localStorage.removeItem('debtik_token');
  15536. state.currentUser = null;
  15537. state.isPolling = false;
  15538. if (window._telemetryInterval) {
  15539. clearInterval(window._telemetryInterval);
  15540. window._telemetryInterval = null;
  15541. }
  15542. if (trafficEventSource) {
  15543. trafficEventSource.close();
  15544. trafficEventSource = null;
  15545. }
  15546. if (trafficPollFallback) {
  15547. clearInterval(trafficPollFallback);
  15548. trafficPollFallback = null;
  15549. }
  15550. showLoginScreen(false);
  15551. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15552. }
  15553. function togglePasswordVisibility(id) {
  15554. const input = document.getElementById(id);
  15555. if (!input) return;
  15556. input.type = input.type === 'password' ? 'text' : 'password';
  15557. }
  15558. function toggleUserMenu() {
  15559. const menu = document.getElementById('user-menu-dropdown');
  15560. if (menu) menu.classList.toggle('hidden');
  15561. }
  15562. function closeUserMenu() {
  15563. const menu = document.getElementById('user-menu-dropdown');
  15564. if (menu) menu.classList.add('hidden');
  15565. }
  15566. // Close user menu on outside click
  15567. document.addEventListener('click', (e) => {
  15568. const menu = document.getElementById('user-menu-dropdown');
  15569. if (!menu || menu.classList.contains('hidden')) return;
  15570. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15571. menu.classList.add('hidden');
  15572. }
  15573. });
  15574. function updateUserProfileHeader(user) {
  15575. if (!user) return;
  15576. const navName = document.getElementById('nav-user-name');
  15577. if (navName) navName.innerText = user.username;
  15578. const dropName = document.getElementById('dropdown-user-name');
  15579. if (dropName) dropName.innerText = user.username;
  15580. const navRole = document.getElementById('nav-user-role');
  15581. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15582. const navAvatar = document.getElementById('nav-user-avatar');
  15583. if (navAvatar) {
  15584. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15585. navAvatar.innerText = initials;
  15586. }
  15587. const statCurUser = document.getElementById('stat-current-user');
  15588. if (statCurUser) statCurUser.innerText = user.username;
  15589. const statCurRole = document.getElementById('stat-current-role');
  15590. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15591. // Role permissions UI visibility: hide user management for non-admins
  15592. const isFullAdmin = user.role === 'full';
  15593. const navUsers = document.getElementById('nav-users');
  15594. if (navUsers) {
  15595. if (isFullAdmin) navUsers.classList.remove('hidden');
  15596. else navUsers.classList.add('hidden');
  15597. }
  15598. const dropdownUsers = document.getElementById('dropdown-item-users');
  15599. if (dropdownUsers) {
  15600. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15601. else dropdownUsers.classList.add('hidden');
  15602. }
  15603. }
  15604. // ================= User Management CRUD =================
  15605. async function loadUsers(isManual = false) {
  15606. try {
  15607. const res = await fetch(`${API_BASE}/users`);
  15608. if (res.status === 403) {
  15609. const tbody = document.getElementById('users-table-tbody');
  15610. if (tbody) {
  15611. tbody.innerHTML = `
  15612. <tr>
  15613. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15614. <div class="inline-flex items-center gap-2">
  15615. <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>
  15616. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15617. </div>
  15618. </td>
  15619. </tr>
  15620. `;
  15621. }
  15622. return;
  15623. }
  15624. if (res.ok) {
  15625. state.users = await res.json();
  15626. renderUsersTable();
  15627. const totalUsers = document.getElementById('stat-total-users');
  15628. if (totalUsers) totalUsers.innerText = state.users.length;
  15629. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15630. const adminUsers = document.getElementById('stat-admin-users');
  15631. if (adminUsers) adminUsers.innerText = adminCount;
  15632. const badgeCount = document.getElementById('badge-users-count');
  15633. if (badgeCount) badgeCount.innerText = state.users.length;
  15634. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15635. }
  15636. } catch (err) {
  15637. console.error('Failed to load users:', err);
  15638. }
  15639. }
  15640. function renderUsersTable() {
  15641. const tbody = document.getElementById('users-table-tbody');
  15642. const emptyState = document.getElementById('users-empty-state');
  15643. if (!tbody) return;
  15644. tbody.innerHTML = '';
  15645. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15646. const filtered = (state.users || []).filter(u => {
  15647. if (!query) return true;
  15648. return u.username.toLowerCase().includes(query) ||
  15649. (u.role || '').toLowerCase().includes(query) ||
  15650. (u.comment || '').toLowerCase().includes(query);
  15651. });
  15652. if (filtered.length === 0) {
  15653. if (emptyState) emptyState.classList.remove('hidden');
  15654. return;
  15655. }
  15656. if (emptyState) emptyState.classList.add('hidden');
  15657. const currentAuthUser = state.currentUser?.username || '';
  15658. filtered.forEach(u => {
  15659. const isSelf = u.username === currentAuthUser;
  15660. const isFull = u.role === 'full';
  15661. const isWrite = u.role === 'write';
  15662. 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>`;
  15663. if (isFull) {
  15664. 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>`;
  15665. } else if (isWrite) {
  15666. 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>`;
  15667. }
  15668. const statusBadge = u.disabled
  15669. ? `<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>`
  15670. : `<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>`;
  15671. let lastLoginText = 'Never';
  15672. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15673. const dt = new Date(u.last_login_at);
  15674. lastLoginText = dt.toLocaleString();
  15675. }
  15676. const initials = u.username.slice(0, 2).toUpperCase();
  15677. const tr = document.createElement('tr');
  15678. tr.className = 'hover:bg-slate-800/40 transition group';
  15679. tr.innerHTML = `
  15680. <td class="py-3 px-4">
  15681. <div class="flex items-center gap-3">
  15682. <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">
  15683. ${initials}
  15684. </div>
  15685. <div>
  15686. <div class="font-bold text-white text-xs flex items-center gap-2">
  15687. <span>${escapeHtml(u.username)}</span>
  15688. ${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>' : ''}
  15689. </div>
  15690. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15691. </div>
  15692. </div>
  15693. </td>
  15694. <td class="py-3 px-4 font-sans">
  15695. ${roleBadge}
  15696. </td>
  15697. <td class="py-3 px-4 font-sans">
  15698. ${statusBadge}
  15699. </td>
  15700. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15701. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15702. </td>
  15703. <td class="py-3 px-4 text-slate-400 text-xs">
  15704. ${lastLoginText}
  15705. </td>
  15706. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15707. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15708. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15709. <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>
  15710. </button>
  15711. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15712. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15713. <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>
  15714. </button>
  15715. ${!isSelf ? `
  15716. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15717. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15718. <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>
  15719. </button>
  15720. ` : ''}
  15721. </td>
  15722. `;
  15723. tbody.appendChild(tr);
  15724. });
  15725. }
  15726. function openAddUserModal() {
  15727. document.getElementById('user-add-username').value = '';
  15728. document.getElementById('user-add-password').value = '';
  15729. document.getElementById('user-add-confirm').value = '';
  15730. document.getElementById('user-add-role').value = 'full';
  15731. document.getElementById('user-add-comment').value = '';
  15732. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15733. document.getElementById('user-add-username')?.focus();
  15734. }
  15735. function closeAddUserModal() {
  15736. document.getElementById('modal-add-user')?.classList.add('hidden');
  15737. }
  15738. async function submitAddUser(event) {
  15739. event.preventDefault();
  15740. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15741. const password = document.getElementById('user-add-password')?.value || '';
  15742. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15743. const role = document.getElementById('user-add-role')?.value || 'full';
  15744. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15745. if (password !== confirm) {
  15746. showToast('Validation Error', 'Passwords do not match', 'warning');
  15747. return;
  15748. }
  15749. if (password.length < 4) {
  15750. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15751. return;
  15752. }
  15753. try {
  15754. const res = await fetch(`${API_BASE}/users`, {
  15755. method: 'POST',
  15756. headers: { 'Content-Type': 'application/json' },
  15757. body: JSON.stringify({ username, password, role, comment })
  15758. });
  15759. const data = await res.json();
  15760. if (res.ok) {
  15761. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15762. closeAddUserModal();
  15763. loadUsers(false);
  15764. } else {
  15765. showToast('Error', data.message || 'Failed to create user', 'error');
  15766. }
  15767. } catch (err) {
  15768. showToast('Error', err.message, 'error');
  15769. }
  15770. }
  15771. function openEditUserModal(username) {
  15772. const user = (state.users || []).find(u => u.username === username);
  15773. if (!user) return;
  15774. document.getElementById('user-edit-username').value = user.username;
  15775. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15776. document.getElementById('user-edit-role').value = user.role || 'read';
  15777. document.getElementById('user-edit-comment').value = user.comment || '';
  15778. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15779. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15780. }
  15781. function closeEditUserModal() {
  15782. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15783. }
  15784. async function submitEditUser(event) {
  15785. event.preventDefault();
  15786. const username = document.getElementById('user-edit-username')?.value;
  15787. const role = document.getElementById('user-edit-role')?.value || 'read';
  15788. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15789. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15790. try {
  15791. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15792. method: 'PUT',
  15793. headers: { 'Content-Type': 'application/json' },
  15794. body: JSON.stringify({ role, comment, disabled })
  15795. });
  15796. const data = await res.json();
  15797. if (res.ok) {
  15798. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15799. closeEditUserModal();
  15800. loadUsers(false);
  15801. // If updated own role/disabled status, refresh self profile
  15802. if (username === state.currentUser?.username) {
  15803. checkAuthStatus();
  15804. }
  15805. } else {
  15806. showToast('Error', data.message || 'Failed to update user', 'error');
  15807. }
  15808. } catch (err) {
  15809. showToast('Error', err.message, 'error');
  15810. }
  15811. }
  15812. function openAdminResetPasswordModal(username) {
  15813. document.getElementById('admin-reset-username').value = username;
  15814. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15815. document.getElementById('admin-reset-new-pw').value = '';
  15816. document.getElementById('admin-reset-confirm-pw').value = '';
  15817. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15818. document.getElementById('admin-reset-new-pw')?.focus();
  15819. }
  15820. function closeAdminResetPasswordModal() {
  15821. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15822. }
  15823. async function submitAdminResetPassword(event) {
  15824. event.preventDefault();
  15825. const username = document.getElementById('admin-reset-username')?.value;
  15826. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15827. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15828. if (newPassword !== confirm) {
  15829. showToast('Validation Error', 'Passwords do not match', 'warning');
  15830. return;
  15831. }
  15832. if (newPassword.length < 4) {
  15833. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15834. return;
  15835. }
  15836. try {
  15837. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15838. method: 'POST',
  15839. headers: { 'Content-Type': 'application/json' },
  15840. body: JSON.stringify({ new_password: newPassword })
  15841. });
  15842. const data = await res.json();
  15843. if (res.ok) {
  15844. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15845. closeAdminResetPasswordModal();
  15846. } else {
  15847. showToast('Error', data.message || 'Failed to reset password', 'error');
  15848. }
  15849. } catch (err) {
  15850. showToast('Error', err.message, 'error');
  15851. }
  15852. }
  15853. async function deleteUser(username) {
  15854. if (username === state.currentUser?.username) {
  15855. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15856. return;
  15857. }
  15858. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15859. return;
  15860. }
  15861. try {
  15862. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15863. method: 'DELETE'
  15864. });
  15865. const data = await res.json();
  15866. if (res.ok) {
  15867. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15868. loadUsers(false);
  15869. } else {
  15870. showToast('Error', data.message || 'Failed to delete user', 'error');
  15871. }
  15872. } catch (err) {
  15873. showToast('Error', err.message, 'error');
  15874. }
  15875. }
  15876. function openSelfPasswordModal() {
  15877. document.getElementById('self-current-password').value = '';
  15878. document.getElementById('self-new-password').value = '';
  15879. document.getElementById('self-confirm-password').value = '';
  15880. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15881. document.getElementById('self-current-password')?.focus();
  15882. }
  15883. function closeSelfPasswordModal() {
  15884. document.getElementById('modal-self-password')?.classList.add('hidden');
  15885. }
  15886. async function submitSelfPassword(event) {
  15887. event.preventDefault();
  15888. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15889. const newPassword = document.getElementById('self-new-password')?.value || '';
  15890. const confirm = document.getElementById('self-confirm-password')?.value || '';
  15891. if (newPassword !== confirm) {
  15892. showToast('Validation Error', 'New passwords do not match', 'warning');
  15893. return;
  15894. }
  15895. if (newPassword.length < 4) {
  15896. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15897. return;
  15898. }
  15899. try {
  15900. const res = await fetch(`${API_BASE}/auth/change-password`, {
  15901. method: 'POST',
  15902. headers: { 'Content-Type': 'application/json' },
  15903. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15904. });
  15905. const data = await res.json();
  15906. if (res.ok) {
  15907. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15908. closeSelfPasswordModal();
  15909. } else {
  15910. showToast('Error', data.message || 'Failed to change password', 'error');
  15911. }
  15912. } catch (err) {
  15913. showToast('Error', err.message, 'error');
  15914. }
  15915. }
  15916. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15917. state.services = [];
  15918. async function loadServices(manual = false) {
  15919. try {
  15920. const res = await fetch(`${API_BASE}/system/services`);
  15921. if (!res.ok) throw new Error('Failed to load services');
  15922. const data = await res.json();
  15923. state.services = data || [];
  15924. renderServicesTable();
  15925. updateCertificatesBadges();
  15926. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15927. } catch (err) {
  15928. if (manual) showToast('Error', err.message, 'error');
  15929. }
  15930. }
  15931. function renderServicesTable() {
  15932. const tbody = document.getElementById('services-table-body');
  15933. if (!tbody) return;
  15934. if (!state.services || state.services.length === 0) {
  15935. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15936. return;
  15937. }
  15938. tbody.innerHTML = state.services.map(s => {
  15939. const isOff = s.disabled;
  15940. const statusBadge = isOff
  15941. ? '<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>'
  15942. : '<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>';
  15943. const toggleBtn = isOff
  15944. ? `<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>`
  15945. : `<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>`;
  15946. let certBadge = '';
  15947. if (s.name === 'www-ssl') {
  15948. if (s.certificate) {
  15949. 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>`;
  15950. } else {
  15951. 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>`;
  15952. }
  15953. }
  15954. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15955. return `
  15956. <tr class="hover:bg-slate-800/40 transition">
  15957. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15958. <td class="py-3 px-4">
  15959. <div class="flex items-center gap-2">
  15960. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15961. <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">
  15962. <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>
  15963. </button>
  15964. </div>
  15965. </td>
  15966. <td class="py-3 px-4">${statusBadge}</td>
  15967. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  15968. <td class="py-3 px-4 text-right">
  15969. <div class="flex items-center justify-end gap-2">
  15970. <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">
  15971. <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>
  15972. <span>Edit</span>
  15973. </button>
  15974. ${toggleBtn}
  15975. </div>
  15976. </td>
  15977. </tr>
  15978. `;
  15979. }).join('');
  15980. }
  15981. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  15982. document.getElementById('modal-service-name').value = serviceName;
  15983. document.getElementById('modal-service-disabled').value = String(isDisabled);
  15984. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  15985. document.getElementById('modal-service-port').value = currentPort;
  15986. const hintEl = document.getElementById('modal-service-port-hint');
  15987. const warnEl = document.getElementById('modal-service-warning');
  15988. const certGroup = document.getElementById('modal-service-cert-group');
  15989. const certSelect = document.getElementById('modal-service-cert-select');
  15990. if (serviceName === 'www') {
  15991. hintEl.textContent = 'Default HTTP web port: 80';
  15992. warnEl.classList.remove('hidden');
  15993. certGroup.classList.add('hidden');
  15994. } else if (serviceName === 'www-ssl') {
  15995. hintEl.textContent = 'Default HTTPS web port: 443';
  15996. warnEl.classList.remove('hidden');
  15997. certGroup.classList.remove('hidden');
  15998. const populateCertOptions = (certs) => {
  15999. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16000. (certs || []).forEach(c => {
  16001. const opt = document.createElement('option');
  16002. opt.value = c.name;
  16003. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16004. if (c.name === currentCert) opt.selected = true;
  16005. certSelect.appendChild(opt);
  16006. });
  16007. };
  16008. if (state.certificates && state.certificates.length > 0) {
  16009. populateCertOptions(state.certificates);
  16010. } else {
  16011. loadCertificates(false).then(() => {
  16012. populateCertOptions(state.certificates);
  16013. });
  16014. }
  16015. } else if (serviceName === 'telnet') {
  16016. hintEl.textContent = 'Default Telnet console port: 8282';
  16017. warnEl.classList.add('hidden');
  16018. certGroup.classList.add('hidden');
  16019. } else if (serviceName === 'ssh') {
  16020. hintEl.textContent = 'Default SSH port: 2222';
  16021. warnEl.classList.add('hidden');
  16022. certGroup.classList.add('hidden');
  16023. } else {
  16024. hintEl.textContent = '';
  16025. warnEl.classList.add('hidden');
  16026. certGroup.classList.add('hidden');
  16027. }
  16028. const modal = document.getElementById('modal-service-edit');
  16029. modal.classList.remove('hidden');
  16030. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16031. }
  16032. function closeEditServiceModal() {
  16033. const modal = document.getElementById('modal-service-edit');
  16034. if (modal) modal.classList.add('hidden');
  16035. }
  16036. async function submitSaveServicePort(event) {
  16037. event.preventDefault();
  16038. const name = document.getElementById('modal-service-name').value;
  16039. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16040. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16041. if (isNaN(port) || port < 1 || port > 65535) {
  16042. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16043. return;
  16044. }
  16045. const certSelect = document.getElementById('modal-service-cert-select');
  16046. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16047. try {
  16048. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16049. method: 'POST',
  16050. headers: { 'Content-Type': 'application/json' },
  16051. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16052. });
  16053. if (!res.ok) {
  16054. const errData = await res.json();
  16055. throw new Error(errData.message || 'Failed to update service settings');
  16056. }
  16057. closeEditServiceModal();
  16058. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16059. await loadServices();
  16060. } catch (err) {
  16061. showToast('Error', err.message, 'error');
  16062. }
  16063. }
  16064. async function toggleServiceState(serviceName, newDisabled) {
  16065. if (serviceName === 'www' && newDisabled) {
  16066. 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?")) {
  16067. return;
  16068. }
  16069. }
  16070. if (serviceName === 'www-ssl' && !newDisabled) {
  16071. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16072. if (!sslSvc || !sslSvc.certificate) {
  16073. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16074. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16075. return;
  16076. }
  16077. }
  16078. try {
  16079. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16080. method: 'POST',
  16081. headers: { 'Content-Type': 'application/json' },
  16082. body: JSON.stringify({ disabled: newDisabled })
  16083. });
  16084. if (!res.ok) {
  16085. const errData = await res.json();
  16086. throw new Error(errData.message || 'Failed to update service');
  16087. }
  16088. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16089. await loadServices();
  16090. } catch (err) {
  16091. showToast('Error', err.message, 'error');
  16092. }
  16093. }
  16094. // ==================== SYSTEM LOGS (/log) ====================
  16095. state.logs = [];
  16096. let logsTimer = null;
  16097. async function loadLogs(manual = false) {
  16098. const limitEl = document.getElementById('logs-limit-select');
  16099. const limit = limitEl ? limitEl.value : '100';
  16100. try {
  16101. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16102. if (!res.ok) throw new Error('Failed to load logs');
  16103. const data = await res.json();
  16104. state.logs = data.logs || [];
  16105. renderLogsTable();
  16106. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16107. } catch (err) {
  16108. if (manual) showToast('Error', err.message, 'error');
  16109. }
  16110. // Setup auto-refresh if enabled and on logs tab
  16111. if (!logsTimer && state.currentUser) {
  16112. logsTimer = setInterval(() => {
  16113. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16114. const auto = document.getElementById('logs-auto-refresh');
  16115. if (auto && auto.checked) {
  16116. loadLogs(false);
  16117. }
  16118. }
  16119. }, 3000);
  16120. }
  16121. }
  16122. function renderLogsTable() {
  16123. const tbody = document.getElementById('logs-table-body');
  16124. if (!tbody) return;
  16125. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16126. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16127. const filtered = state.logs.filter(entry => {
  16128. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16129. return false;
  16130. }
  16131. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16132. return false;
  16133. }
  16134. return true;
  16135. });
  16136. if (filtered.length === 0) {
  16137. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16138. return;
  16139. }
  16140. tbody.innerHTML = filtered.map(l => {
  16141. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16142. const topLower = l.topics.toLowerCase();
  16143. if (topLower.includes('auth')) {
  16144. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16145. } else if (topLower.includes('dhcp')) {
  16146. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16147. } else if (topLower.includes('route')) {
  16148. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16149. } else if (topLower.includes('firewall')) {
  16150. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16151. } else if (topLower.includes('error')) {
  16152. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16153. } else if (topLower.includes('system')) {
  16154. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16155. }
  16156. const d = new Date(l.time);
  16157. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16158. return `
  16159. <tr class="hover:bg-slate-800/40 transition">
  16160. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16161. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16162. <td class="py-2 px-3 whitespace-nowrap">
  16163. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16164. </td>
  16165. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16166. </tr>
  16167. `;
  16168. }).join('');
  16169. }
  16170. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16171. state.certificates = [];
  16172. async function loadCertificates(manual = false) {
  16173. try {
  16174. const res = await fetch(`${API_BASE}/certificates`);
  16175. if (!res.ok) throw new Error('Failed to load certificates');
  16176. state.certificates = await res.json() || [];
  16177. updateCertificatesBadges();
  16178. renderCertificatesTable();
  16179. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16180. } catch (err) {
  16181. if (manual) showToast('Error', err.message, 'error');
  16182. }
  16183. }
  16184. function updateCertificatesBadges() {
  16185. const total = (state.certificates || []).length;
  16186. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16187. const bCount = document.getElementById('badge-certs-count');
  16188. if (bCount) bCount.innerText = total;
  16189. const kpiTotal = document.getElementById('kpi-certs-total');
  16190. if (kpiTotal) kpiTotal.innerText = total;
  16191. const kpiCA = document.getElementById('kpi-certs-ca');
  16192. if (kpiCA) kpiCA.innerText = caCount;
  16193. const kpiHttps = document.getElementById('kpi-https-status');
  16194. if (kpiHttps) {
  16195. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16196. if (sslSvc) {
  16197. if (!sslSvc.disabled) {
  16198. 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>`;
  16199. } else {
  16200. 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>`;
  16201. }
  16202. }
  16203. }
  16204. }
  16205. function renderCertificatesTable() {
  16206. const tbody = document.getElementById('certs-table-body');
  16207. if (!tbody) return;
  16208. if (!state.certificates || state.certificates.length === 0) {
  16209. 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>';
  16210. return;
  16211. }
  16212. tbody.innerHTML = state.certificates.map(c => {
  16213. let typeBadge = '';
  16214. if (c.is_ca) {
  16215. 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>';
  16216. } else if (c.type === 'acme') {
  16217. 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>';
  16218. } else if (c.issuer && c.issuer !== c.common_name) {
  16219. 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>';
  16220. } else {
  16221. 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>';
  16222. }
  16223. const sansHtml = (c.sans && c.sans.length > 0)
  16224. ? 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('')
  16225. : '<span class="text-slate-500">-</span>';
  16226. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16227. let validStr = '-';
  16228. let validBadge = '';
  16229. if (validTo && !isNaN(validTo.getTime())) {
  16230. const now = new Date();
  16231. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16232. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16233. if (daysLeft < 0) {
  16234. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16235. } else if (daysLeft < 30) {
  16236. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16237. } else {
  16238. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16239. }
  16240. }
  16241. return `
  16242. <tr class="hover:bg-slate-800/40 transition">
  16243. <td class="py-3 px-4">${typeBadge}</td>
  16244. <td class="py-3 px-4">
  16245. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16246. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16247. </td>
  16248. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16249. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16250. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16251. <span>${validStr}</span> ${validBadge}
  16252. ${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>` : ''}
  16253. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16254. </td>
  16255. <td class="py-3 px-4 text-right whitespace-nowrap">
  16256. <div class="flex items-center justify-end gap-1.5">
  16257. <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">
  16258. <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>
  16259. <span>View</span>
  16260. </button>
  16261. <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">
  16262. <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>
  16263. </button>
  16264. </div>
  16265. </td>
  16266. </tr>
  16267. `;
  16268. }).join('');
  16269. }
  16270. // Create CA
  16271. function openCreateCAModal() {
  16272. document.getElementById('form-create-ca').reset();
  16273. document.getElementById('ca-days').value = '3650';
  16274. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16275. document.getElementById('ca-country').value = 'GR';
  16276. document.getElementById('ca-key-type').value = 'RSA-2048';
  16277. document.getElementById('modal-create-ca').classList.remove('hidden');
  16278. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16279. }
  16280. function closeCreateCAModal() {
  16281. document.getElementById('modal-create-ca').classList.add('hidden');
  16282. }
  16283. async function submitCreateCA(event) {
  16284. event.preventDefault();
  16285. const payload = {
  16286. name: document.getElementById('ca-name').value.trim(),
  16287. common_name: document.getElementById('ca-cn').value.trim(),
  16288. organization: document.getElementById('ca-org').value.trim(),
  16289. country: document.getElementById('ca-country').value.trim(),
  16290. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16291. key_type: document.getElementById('ca-key-type').value
  16292. };
  16293. try {
  16294. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16295. method: 'POST',
  16296. headers: { 'Content-Type': 'application/json' },
  16297. body: JSON.stringify(payload)
  16298. });
  16299. if (!res.ok) {
  16300. const errData = await res.json();
  16301. throw new Error(errData.message || 'Failed to create CA');
  16302. }
  16303. closeCreateCAModal();
  16304. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16305. await loadCertificates();
  16306. } catch (err) {
  16307. showToast('Error', err.message, 'error');
  16308. }
  16309. }
  16310. // Create Cert
  16311. function openCreateCertModal() {
  16312. document.getElementById('form-create-cert').reset();
  16313. document.getElementById('cert-days').value = '730';
  16314. document.getElementById('cert-key-type').value = 'RSA-2048';
  16315. const caSelect = document.getElementById('cert-ca-select');
  16316. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16317. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16318. const opt = document.createElement('option');
  16319. opt.value = ca.name;
  16320. opt.textContent = `${ca.name} (${ca.common_name})`;
  16321. caSelect.appendChild(opt);
  16322. });
  16323. document.getElementById('modal-create-cert').classList.remove('hidden');
  16324. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16325. }
  16326. function closeCreateCertModal() {
  16327. document.getElementById('modal-create-cert').classList.add('hidden');
  16328. }
  16329. async function submitCreateCert(event) {
  16330. event.preventDefault();
  16331. const rawSans = document.getElementById('cert-sans').value;
  16332. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16333. const caName = document.getElementById('cert-ca-select').value;
  16334. const payload = {
  16335. name: document.getElementById('cert-name').value.trim(),
  16336. common_name: document.getElementById('cert-cn').value.trim(),
  16337. ca_name: caName,
  16338. sans: sansList,
  16339. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16340. key_type: document.getElementById('cert-key-type').value,
  16341. is_server: true
  16342. };
  16343. try {
  16344. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16345. method: 'POST',
  16346. headers: { 'Content-Type': 'application/json' },
  16347. body: JSON.stringify(payload)
  16348. });
  16349. if (!res.ok) {
  16350. const errData = await res.json();
  16351. throw new Error(errData.message || 'Failed to issue certificate');
  16352. }
  16353. closeCreateCertModal();
  16354. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16355. await loadCertificates();
  16356. } catch (err) {
  16357. showToast('Error', err.message, 'error');
  16358. }
  16359. }
  16360. // Let's Encrypt
  16361. function openLetsEncryptModal() {
  16362. document.getElementById('form-letsencrypt').reset();
  16363. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16364. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16365. }
  16366. function closeLetsEncryptModal() {
  16367. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16368. }
  16369. async function submitLetsEncrypt(event) {
  16370. event.preventDefault();
  16371. const domain = document.getElementById('le-domain').value.trim();
  16372. const email = document.getElementById('le-email').value.trim();
  16373. let name = document.getElementById('le-name').value.trim();
  16374. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16375. const staging = document.getElementById('le-staging').checked;
  16376. const btn = document.getElementById('btn-submit-letsencrypt');
  16377. const origBtnHtml = btn.innerHTML;
  16378. btn.disabled = true;
  16379. 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>`;
  16380. try {
  16381. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16382. method: 'POST',
  16383. headers: { 'Content-Type': 'application/json' },
  16384. body: JSON.stringify({
  16385. name: name,
  16386. domain: domain,
  16387. email: email,
  16388. staging: staging
  16389. })
  16390. });
  16391. if (!res.ok) {
  16392. const errData = await res.json();
  16393. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16394. }
  16395. closeLetsEncryptModal();
  16396. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16397. await loadCertificates();
  16398. } catch (err) {
  16399. showToast('Let\'s Encrypt Error', err.message, 'error');
  16400. } finally {
  16401. btn.disabled = false;
  16402. btn.innerHTML = origBtnHtml;
  16403. }
  16404. }
  16405. // Import Cert
  16406. function openImportCertModal() {
  16407. document.getElementById('form-import-cert').reset();
  16408. document.getElementById('modal-import-cert').classList.remove('hidden');
  16409. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16410. }
  16411. function closeImportCertModal() {
  16412. document.getElementById('modal-import-cert').classList.add('hidden');
  16413. }
  16414. async function submitImportCert(event) {
  16415. event.preventDefault();
  16416. const payload = {
  16417. name: document.getElementById('import-cert-name').value.trim(),
  16418. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16419. key_pem: document.getElementById('import-key-pem').value.trim()
  16420. };
  16421. try {
  16422. const res = await fetch(`${API_BASE}/certificates/import`, {
  16423. method: 'POST',
  16424. headers: { 'Content-Type': 'application/json' },
  16425. body: JSON.stringify(payload)
  16426. });
  16427. if (!res.ok) {
  16428. const errData = await res.json();
  16429. throw new Error(errData.message || 'Failed to import certificate');
  16430. }
  16431. closeImportCertModal();
  16432. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16433. await loadCertificates();
  16434. } catch (err) {
  16435. showToast('Error', err.message, 'error');
  16436. }
  16437. }
  16438. // View / Export Modal
  16439. async function openViewCertModal(name) {
  16440. const c = (state.certificates || []).find(x => x.name === name);
  16441. if (!c) return;
  16442. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16443. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16444. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16445. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16446. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16447. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16448. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16449. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16450. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16451. document.getElementById('modal-view-cert').classList.remove('hidden');
  16452. try {
  16453. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16454. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16455. const data = await res.json();
  16456. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16457. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16458. } catch (err) {
  16459. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16460. document.getElementById('view-key-pem-text').value = '';
  16461. }
  16462. }
  16463. function closeViewCertModal() {
  16464. document.getElementById('modal-view-cert').classList.add('hidden');
  16465. }
  16466. function copyCertPEM() {
  16467. const text = document.getElementById('view-cert-pem-text').value;
  16468. if (!text) return;
  16469. navigator.clipboard.writeText(text).then(() => {
  16470. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16471. }).catch(() => {
  16472. showToast('Error', 'Failed to copy to clipboard', 'error');
  16473. });
  16474. }
  16475. function copyKeyPEM() {
  16476. const text = document.getElementById('view-key-pem-text').value;
  16477. if (!text) return;
  16478. navigator.clipboard.writeText(text).then(() => {
  16479. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16480. }).catch(() => {
  16481. showToast('Error', 'Failed to copy to clipboard', 'error');
  16482. });
  16483. }
  16484. async function deleteCertificate(name) {
  16485. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16486. return;
  16487. }
  16488. try {
  16489. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16490. method: 'DELETE'
  16491. });
  16492. if (!res.ok) {
  16493. const errData = await res.json();
  16494. throw new Error(errData.message || 'Failed to delete certificate');
  16495. }
  16496. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16497. await loadCertificates();
  16498. } catch (err) {
  16499. showToast('Error', err.message, 'error');
  16500. }
  16501. }
  16502. // Refresh immediately when returning to a backgrounded controller tab.
  16503. document.addEventListener('visibilitychange', () => {
  16504. if (!state.currentUser) return;
  16505. if (document.hidden) {
  16506. if (trafficEventSource) trafficEventSource.close();
  16507. trafficEventSource = null;
  16508. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16509. trafficPollFallback = null;
  16510. } else {
  16511. fetchData(false);
  16512. initLiveTrafficStream();
  16513. if (state.activeTab === 'bwtest') loadBwTestView();
  16514. }
  16515. });
  16516. async function loadUpdateStatus(populate = true) {
  16517. try {
  16518. const res = await fetch(`${API_BASE}/update/status`);
  16519. if (!res.ok) throw new Error(await responseError(res));
  16520. const data = await res.json();
  16521. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16522. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16523. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16524. document.getElementById('update-state').textContent = data.state || 'idle';
  16525. document.getElementById('update-log').textContent = data.log || '';
  16526. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16527. }
  16528. async function saveUpdateConfig() {
  16529. try {
  16530. const repository = document.getElementById('update-repository').value.trim();
  16531. const branch = 'master';
  16532. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16533. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16534. if (!res.ok) throw new Error(await responseError(res));
  16535. document.getElementById('update-install-button').disabled = true;
  16536. document.getElementById('update-available').textContent = '—';
  16537. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16538. await loadUpdateStatus(false);
  16539. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16540. }
  16541. async function checkUpdate() {
  16542. try {
  16543. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16544. if (!res.ok) throw new Error(await responseError(res));
  16545. const data = await res.json();
  16546. document.getElementById('update-available').textContent = data.available_version;
  16547. document.getElementById('update-install-button').disabled = !data.update_available;
  16548. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16549. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16550. }
  16551. async function startUpdate(action) {
  16552. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16553. try {
  16554. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16555. if (!res.ok) throw new Error(await responseError(res));
  16556. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16557. await loadUpdateStatus(false);
  16558. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16559. }
  16560. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16561. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16562. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16563. function safeFirewallRow(row) {
  16564. const result = {...row};
  16565. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16566. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16567. return result;
  16568. }
  16569. function setFirewallDays(prefix, days) {
  16570. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16571. 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); }
  16572. }
  16573. function getFirewallDays(prefix) {
  16574. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16575. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16576. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16577. return selected.join(',');
  16578. }
  16579. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16580. const id = document.getElementById(kind+'-modal-id')?.value;
  16581. if (!id) { resetDisplay(); return; }
  16582. try {
  16583. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16584. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16585. resetDisplay(); await loadFirewall(false);
  16586. } catch(error) { showToast('Error', error.message, 'error'); }
  16587. }
  16588. function reviewLegacyFirewallSettings(kind, id) {
  16589. if (!id) return true;
  16590. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16591. const rule = (rows || []).find(r => r.id === id);
  16592. if (!rule) return true;
  16593. 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'];
  16594. const present = unsupported.filter(key => rule[key]);
  16595. if (!present.length) return true;
  16596. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16597. }
  16598. function refreshFirewallRejectTypes() {
  16599. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16600. const old=select.value;
  16601. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16602. 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'];
  16603. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16604. if(types.includes(old))select.value=old;
  16605. }
  16606. function setFirewallActionSelection(kind, value) {
  16607. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16608. if(!Array.from(select.options).some(option=>option.value===value)) {
  16609. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16610. }
  16611. select.value=value;
  16612. }
  16613. // ==========================================
  16614. // REVERSE PROXY & APPLICATION GATEWAY
  16615. // ==========================================
  16616. state.proxyRules = [];
  16617. state.proxyConfig = null;
  16618. async function loadReverseProxy(manual = false) {
  16619. try {
  16620. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16621. fetch(`${API_BASE}/proxy/config`),
  16622. fetch(`${API_BASE}/proxy/rules`),
  16623. fetch(`${API_BASE}/certificates`).catch(() => null)
  16624. ]);
  16625. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16626. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16627. state.proxyConfig = await cfgRes.json();
  16628. state.proxyRules = await rulesRes.json() || [];
  16629. if (certsRes && certsRes.ok) {
  16630. state.certificates = await certsRes.json() || [];
  16631. }
  16632. renderProxyRules(state.proxyRules);
  16633. updateProxyMetrics();
  16634. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16635. } catch (err) {
  16636. console.error('loadReverseProxy error:', err);
  16637. if (manual) showToast('Error', err.message, 'error');
  16638. }
  16639. }
  16640. function updateProxyMetrics() {
  16641. const badge = document.getElementById('badge-proxy-count');
  16642. if (badge) badge.textContent = (state.proxyRules || []).length;
  16643. const metricRules = document.getElementById('proxy-metric-rules');
  16644. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16645. const cfg = state.proxyConfig;
  16646. const statusEl = document.getElementById('proxy-metric-status');
  16647. const portsEl = document.getElementById('proxy-metric-ports');
  16648. if (cfg) {
  16649. if (statusEl) {
  16650. if (cfg.enabled) {
  16651. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16652. } else {
  16653. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16654. }
  16655. }
  16656. if (portsEl) {
  16657. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16658. }
  16659. }
  16660. let totalRequests = 0;
  16661. const certSet = new Set();
  16662. (state.proxyRules || []).forEach(r => {
  16663. totalRequests += (r.stats && r.stats.requests) || 0;
  16664. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16665. });
  16666. const metricRequests = document.getElementById('proxy-metric-requests');
  16667. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16668. const metricCerts = document.getElementById('proxy-metric-certs');
  16669. if (metricCerts) metricCerts.textContent = certSet.size;
  16670. }
  16671. function renderProxyRules(rules) {
  16672. const tbody = document.getElementById('proxy-rules-table-body');
  16673. if (!tbody) return;
  16674. if (!rules || rules.length === 0) {
  16675. tbody.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500 text-xs font-sans">No reverse proxy rules configured yet. Click "Add Proxy Rule" to begin.</td></tr>';
  16676. return;
  16677. }
  16678. tbody.innerHTML = rules.map(r => {
  16679. const isEnabled = r.enabled !== false;
  16680. const domainsStr = (r.domains && r.domains.length > 0) ? r.domains.map(d => `<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${escapeHtml(d)}</span>`).join(' ') : '<span class="px-1.5 py-0.5 rounded bg-violet-950/60 text-violet-300 border border-violet-800/40 font-mono text-[11px]">* (any)</span>';
  16681. const pathBadge = `<span class="px-2 py-0.5 rounded bg-cyan-950/60 text-cyan-300 border border-cyan-800/40 font-mono text-[11px] font-bold">${escapeHtml(r.path || '/')}</span>`;
  16682. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16683. if (r.protocol === 'https') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[10px] font-mono font-bold">HTTPS</span>';
  16684. else if (r.protocol === 'http') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-sky-950 text-sky-400 border border-sky-800/40 text-[10px] font-mono">HTTP</span>';
  16685. const certBadge = r.certificate ? `<span class="ml-1 text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40 px-1 py-0.5 rounded font-mono truncate max-w-[120px] inline-block align-bottom" title="${escapeHtml(r.certificate)}">🔒 ${escapeHtml(r.certificate)}</span>` : '';
  16686. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16687. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16688. return `
  16689. <tr class="hover:bg-slate-800/40 transition">
  16690. <td class="py-3 px-4">
  16691. <button onclick="toggleProxyRuleState('${escapeHtml(r.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-emerald-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  16692. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  16693. </button>
  16694. </td>
  16695. <td class="py-3 px-4">
  16696. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16697. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16698. </td>
  16699. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16700. ${domainsStr}
  16701. </td>
  16702. <td class="py-3 px-4">
  16703. ${pathBadge}
  16704. </td>
  16705. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16706. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16707. </td>
  16708. <td class="py-3 px-4 whitespace-nowrap">
  16709. ${protoBadge}${certBadge}
  16710. </td>
  16711. <td class="py-3 px-4 font-mono">
  16712. ${stripBadge}
  16713. </td>
  16714. <td class="py-3 px-4 font-mono text-slate-300">
  16715. ${requests}
  16716. </td>
  16717. <td class="py-3 px-4 text-right whitespace-nowrap">
  16718. <button onclick="openEditProxyRuleModal('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs mr-1 transition font-sans">Edit</button>
  16719. <button onclick="deleteProxyRule('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-300 border border-rose-800/40 text-xs transition font-sans">Delete</button>
  16720. </td>
  16721. </tr>
  16722. `;
  16723. }).join('');
  16724. }
  16725. function populateProxyCertDropdown(selectedVal = '') {
  16726. const select = document.getElementById('proxy-rule-cert');
  16727. if (!select) return;
  16728. const certs = state.certificates || [];
  16729. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16730. certs.filter(c => !c.is_ca).forEach(c => {
  16731. const opt = document.createElement('option');
  16732. opt.value = c.name;
  16733. const cn = c.common_name ? ` (${c.common_name})` : '';
  16734. opt.textContent = `${c.name}${cn}`;
  16735. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16736. opt.selected = true;
  16737. }
  16738. select.appendChild(opt);
  16739. });
  16740. }
  16741. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16742. const select = document.getElementById('proxy-cfg-default-cert');
  16743. if (!select) return;
  16744. const certs = state.certificates || [];
  16745. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16746. certs.filter(c => !c.is_ca).forEach(c => {
  16747. const opt = document.createElement('option');
  16748. opt.value = c.name;
  16749. const cn = c.common_name ? ` (${c.common_name})` : '';
  16750. opt.textContent = `${c.name}${cn}`;
  16751. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16752. opt.selected = true;
  16753. }
  16754. select.appendChild(opt);
  16755. });
  16756. }
  16757. function onProxyProtoChange() {
  16758. const proto = document.getElementById('proxy-rule-proto')?.value;
  16759. const certSelect = document.getElementById('proxy-rule-cert');
  16760. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16761. if (proto === 'http') {
  16762. if (certSelect) certSelect.disabled = true;
  16763. if (redirectCheck) redirectCheck.disabled = true;
  16764. } else {
  16765. if (certSelect) certSelect.disabled = false;
  16766. if (redirectCheck) redirectCheck.disabled = false;
  16767. }
  16768. }
  16769. function openAddProxyRuleModal() {
  16770. const modal = document.getElementById('modal-proxy-rule');
  16771. if (!modal) return;
  16772. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16773. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" /></svg>
  16774. <span>Add Reverse Proxy Rule</span>
  16775. `;
  16776. document.getElementById('proxy-rule-id').value = '';
  16777. document.getElementById('proxy-rule-name').value = '';
  16778. document.getElementById('proxy-rule-domains').value = '';
  16779. document.getElementById('proxy-rule-path').value = '/';
  16780. document.getElementById('proxy-rule-target').value = '';
  16781. document.getElementById('proxy-rule-proto').value = 'both';
  16782. document.getElementById('proxy-rule-strip-path').checked = false;
  16783. document.getElementById('proxy-rule-http-to-https').checked = false;
  16784. document.getElementById('proxy-rule-preserve-host').checked = false;
  16785. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16786. document.getElementById('proxy-rule-enabled').checked = true;
  16787. document.getElementById('proxy-rule-comment').value = '';
  16788. populateProxyCertDropdown('');
  16789. onProxyProtoChange();
  16790. modal.classList.remove('hidden');
  16791. }
  16792. function openEditProxyRuleModal(id) {
  16793. const modal = document.getElementById('modal-proxy-rule');
  16794. if (!modal) return;
  16795. const rule = (state.proxyRules || []).find(r => r.id === id);
  16796. if (!rule) {
  16797. showToast('Error', 'Rule not found', 'error');
  16798. return;
  16799. }
  16800. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16801. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
  16802. <span>Edit Reverse Proxy Rule</span>
  16803. `;
  16804. document.getElementById('proxy-rule-id').value = rule.id || '';
  16805. document.getElementById('proxy-rule-name').value = rule.name || '';
  16806. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16807. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16808. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16809. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16810. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16811. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16812. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16813. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16814. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16815. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16816. populateProxyCertDropdown(rule.certificate || '');
  16817. onProxyProtoChange();
  16818. modal.classList.remove('hidden');
  16819. }
  16820. function closeProxyRuleModal() {
  16821. const modal = document.getElementById('modal-proxy-rule');
  16822. if (modal) modal.classList.add('hidden');
  16823. }
  16824. async function saveProxyRule(event) {
  16825. event.preventDefault();
  16826. const id = document.getElementById('proxy-rule-id').value;
  16827. const name = document.getElementById('proxy-rule-name').value.trim();
  16828. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16829. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16830. const target = document.getElementById('proxy-rule-target').value.trim();
  16831. const proto = document.getElementById('proxy-rule-proto').value;
  16832. const cert = document.getElementById('proxy-rule-cert').value;
  16833. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16834. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16835. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16836. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16837. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16838. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16839. let domains = [];
  16840. if (rawDomains && rawDomains !== '*') {
  16841. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16842. }
  16843. const payload = {
  16844. id: id || undefined,
  16845. name,
  16846. domains,
  16847. path: pathVal,
  16848. target_url: target,
  16849. protocol: proto,
  16850. certificate: cert,
  16851. strip_path: stripPath,
  16852. http_to_https: httpToHttps,
  16853. preserve_host: preserveHost,
  16854. insecure_tls: insecureTLS,
  16855. enabled,
  16856. comment
  16857. };
  16858. try {
  16859. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16860. const method = id ? 'PUT' : 'POST';
  16861. const res = await fetch(url, {
  16862. method,
  16863. headers: { 'Content-Type': 'application/json' },
  16864. body: JSON.stringify(payload)
  16865. });
  16866. if (!res.ok) {
  16867. const errData = await res.json().catch(() => ({}));
  16868. throw new Error(errData.message || 'Failed to save proxy rule');
  16869. }
  16870. closeProxyRuleModal();
  16871. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16872. await loadReverseProxy(false);
  16873. } catch (err) {
  16874. showToast('Error', err.message, 'error');
  16875. }
  16876. }
  16877. async function deleteProxyRule(id) {
  16878. const rule = (state.proxyRules || []).find(r => r.id === id);
  16879. const name = rule ? rule.name : id;
  16880. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  16881. return;
  16882. }
  16883. try {
  16884. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  16885. method: 'DELETE'
  16886. });
  16887. if (!res.ok) {
  16888. const errData = await res.json().catch(() => ({}));
  16889. throw new Error(errData.message || 'Failed to delete rule');
  16890. }
  16891. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  16892. await loadReverseProxy(false);
  16893. } catch (err) {
  16894. showToast('Error', err.message, 'error');
  16895. }
  16896. }
  16897. async function toggleProxyRuleState(id, currentState) {
  16898. try {
  16899. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  16900. method: 'POST',
  16901. headers: { 'Content-Type': 'application/json' },
  16902. body: JSON.stringify({ enabled: !currentState })
  16903. });
  16904. if (!res.ok) {
  16905. const errData = await res.json().catch(() => ({}));
  16906. throw new Error(errData.message || 'Failed to toggle rule state');
  16907. }
  16908. await loadReverseProxy(false);
  16909. } catch (err) {
  16910. showToast('Error', err.message, 'error');
  16911. }
  16912. }
  16913. function openProxyConfigModal() {
  16914. const modal = document.getElementById('modal-proxy-config');
  16915. if (!modal) return;
  16916. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  16917. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  16918. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  16919. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  16920. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  16921. modal.classList.remove('hidden');
  16922. }
  16923. function closeProxyConfigModal() {
  16924. const modal = document.getElementById('modal-proxy-config');
  16925. if (modal) modal.classList.add('hidden');
  16926. }
  16927. async function saveProxyConfig(event) {
  16928. event.preventDefault();
  16929. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  16930. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  16931. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  16932. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  16933. const payload = {
  16934. enabled,
  16935. http_port: httpPort,
  16936. https_port: httpsPort,
  16937. default_cert: defaultCert
  16938. };
  16939. try {
  16940. const res = await fetch(`${API_BASE}/proxy/config`, {
  16941. method: 'POST',
  16942. headers: { 'Content-Type': 'application/json' },
  16943. body: JSON.stringify(payload)
  16944. });
  16945. if (!res.ok) {
  16946. const errData = await res.json().catch(() => ({}));
  16947. throw new Error(errData.message || 'Failed to update proxy settings');
  16948. }
  16949. closeProxyConfigModal();
  16950. showToast('Success', 'Reverse proxy settings updated', 'success');
  16951. await loadReverseProxy(false);
  16952. } catch (err) {
  16953. showToast('Error', err.message, 'error');
  16954. }
  16955. }
  16956. // ==================== SD-WAN Controller ====================
  16957. async function loadSDWAN(manual = false) {
  16958. try {
  16959. const [groupsRes, telemetryRes] = await Promise.all([
  16960. fetch(`${API_BASE}/sdwan/groups`),
  16961. fetch(`${API_BASE}/sdwan/telemetry`)
  16962. ]);
  16963. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  16964. state.sdwanGroups = await groupsRes.json() || [];
  16965. if (telemetryRes.ok) {
  16966. state.sdwanTelemetry = await telemetryRes.json() || {};
  16967. }
  16968. renderSDWANGroups(state.sdwanGroups);
  16969. renderSDWANMembers(state.sdwanGroups);
  16970. updateSDWANMetrics(state.sdwanTelemetry);
  16971. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  16972. } catch (err) {
  16973. console.error('loadSDWAN error:', err);
  16974. if (manual) showToast('Error', err.message, 'error');
  16975. }
  16976. }
  16977. function updateSDWANMetrics(telemetry) {
  16978. const groups = state.sdwanGroups || [];
  16979. const t = telemetry || {};
  16980. const badge = document.getElementById('badge-sdwan-count');
  16981. if (badge) badge.textContent = groups.length;
  16982. const metricGroups = document.getElementById('sdwan-metric-groups');
  16983. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  16984. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  16985. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  16986. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  16987. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  16988. const metricDown = document.getElementById('sdwan-metric-down');
  16989. if (metricDown) metricDown.textContent = t.down_members || 0;
  16990. }
  16991. function renderSDWANGroups(groups) {
  16992. const tbody = document.getElementById('sdwan-groups-table-body');
  16993. if (!tbody) return;
  16994. if (!groups || groups.length === 0) {
  16995. tbody.innerHTML = '<tr><td colspan="8" class="py-8 text-center text-slate-500 text-xs font-sans">No SD-WAN groups configured yet. Click "Create SD-WAN Group" to begin.</td></tr>';
  16996. return;
  16997. }
  16998. tbody.innerHTML = groups.map(g => {
  16999. const isEnabled = g.disabled !== true;
  17000. const members = g.members || [];
  17001. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17002. // Build distribution progress bar
  17003. let distHtml = '';
  17004. if (members.length === 0) {
  17005. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17006. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17007. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17008. const segments = members.map((m, idx) => {
  17009. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17010. const col = colors[idx % colors.length];
  17011. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17012. }).join('');
  17013. const labels = members.map((m, idx) => {
  17014. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17015. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17016. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17017. }).join('');
  17018. distHtml = `
  17019. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17020. <div class="flex flex-wrap">${labels}</div>
  17021. `;
  17022. } else if (g.mode === 'lowest-latency') {
  17023. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17024. } else if (g.mode === 'lowest-loss') {
  17025. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17026. } else if (g.mode === 'failover') {
  17027. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17028. }
  17029. let modeBadge = '';
  17030. switch (g.mode) {
  17031. case 'weighted':
  17032. modeBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30 text-[10px] font-bold">Weighted LB</span>';
  17033. break;
  17034. case 'pcc':
  17035. modeBadge = '<span class="px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 text-[10px] font-bold">PCC Hashing</span>';
  17036. break;
  17037. case 'lowest-latency':
  17038. modeBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold">Lowest Latency SLA</span>';
  17039. break;
  17040. case 'lowest-loss':
  17041. modeBadge = '<span class="px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 text-[10px] font-bold">Lowest Loss SLA</span>';
  17042. break;
  17043. case 'failover':
  17044. modeBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 text-[10px] font-bold">Failover</span>';
  17045. break;
  17046. default:
  17047. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17048. }
  17049. const autoNatBadge = g.auto_nat
  17050. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17051. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17052. return `
  17053. <tr class="hover:bg-slate-800/40 transition">
  17054. <td class="py-3 px-4">
  17055. <button onclick="toggleSDWANGroupState('${escapeHtml(g.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  17056. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17057. </button>
  17058. </td>
  17059. <td class="py-3 px-4">
  17060. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17061. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(g.name)}</span>
  17062. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17063. </div>
  17064. </td>
  17065. <td class="py-3 px-4">${modeBadge}</td>
  17066. <td class="py-3 px-4">${distHtml}</td>
  17067. <td class="py-3 px-4">
  17068. <span class="px-2 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${members.length} links</span>
  17069. </td>
  17070. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17071. <td class="py-3 px-4">${autoNatBadge}</td>
  17072. <td class="py-3 px-4 text-right">
  17073. <div class="flex items-center justify-end gap-1.5">
  17074. <button onclick="openAddSDWANMemberModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 transition" title="Add Member Link">
  17075. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
  17076. </button>
  17077. <button onclick="openEditSDWANGroupModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Group">
  17078. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  17079. </button>
  17080. <button onclick="deleteSDWANGroup('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Delete Group">
  17081. <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>
  17082. </button>
  17083. </div>
  17084. </td>
  17085. </tr>
  17086. `;
  17087. }).join('');
  17088. }
  17089. function renderSDWANMembers(groups) {
  17090. const tbody = document.getElementById('sdwan-members-table-body');
  17091. if (!tbody) return;
  17092. const allMembers = [];
  17093. (groups || []).forEach(g => {
  17094. (g.members || []).forEach(m => {
  17095. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17096. });
  17097. });
  17098. if (allMembers.length === 0) {
  17099. tbody.innerHTML = '<tr><td colspan="11" class="py-8 text-center text-slate-500 text-xs font-sans">No member WAN links configured. Click "Add Member Link" above.</td></tr>';
  17100. return;
  17101. }
  17102. tbody.innerHTML = allMembers.map(m => {
  17103. const isEnabled = m.disabled !== true;
  17104. let statusBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-bold">HEALTHY</span>';
  17105. if (!isEnabled) {
  17106. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17107. } else if (m.status === 'DEGRADED') {
  17108. statusBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30 text-[10px] font-bold">DEGRADED</span>';
  17109. } else if (m.status === 'DOWN') {
  17110. statusBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[10px] font-bold animate-pulse">DOWN</span>';
  17111. }
  17112. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17113. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17114. return `
  17115. <tr class="hover:bg-slate-800/40 transition">
  17116. <td class="py-3 px-4">
  17117. <button onclick="toggleSDWANMemberState('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable link' : 'Click to enable link'}">
  17118. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17119. </button>
  17120. </td>
  17121. <td class="py-3 px-4">
  17122. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(m.group_name)}</span>
  17123. </td>
  17124. <td class="py-3 px-4">
  17125. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17126. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17127. </td>
  17128. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17129. <td class="py-3 px-4">
  17130. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17131. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17132. </td>
  17133. <td class="py-3 px-4">${statusBadge}</td>
  17134. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17135. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17136. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17137. </td>
  17138. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17139. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17140. </td>
  17141. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17142. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17143. </td>
  17144. <td class="py-3 px-4 text-right">
  17145. <div class="flex items-center justify-end gap-1.5">
  17146. <button onclick="openEditSDWANMemberModal('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Member">
  17147. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  17148. </button>
  17149. <button onclick="deleteSDWANMember('${escapeHtml(m.group_id)}', '${escapeHtml(m.interface)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Remove Link">
  17150. <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>
  17151. </button>
  17152. </div>
  17153. </td>
  17154. </tr>
  17155. `;
  17156. }).join('');
  17157. }
  17158. // Modal handling for SD-WAN Groups
  17159. function openAddSDWANGroupModal() {
  17160. const modal = document.getElementById('modal-sdwan-group');
  17161. if (!modal) return;
  17162. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17163. document.getElementById('sdwan-group-id').value = '';
  17164. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17165. document.getElementById('sdwan-group-name').disabled = false;
  17166. document.getElementById('sdwan-group-mode').value = 'weighted';
  17167. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17168. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17169. document.getElementById('sdwan-group-probe-interval').value = 3;
  17170. document.getElementById('sdwan-group-auto-nat').checked = true;
  17171. document.getElementById('sdwan-group-comment').value = '';
  17172. modal.classList.remove('hidden');
  17173. }
  17174. function openEditSDWANGroupModal(id) {
  17175. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17176. if (!group) return;
  17177. const modal = document.getElementById('modal-sdwan-group');
  17178. if (!modal) return;
  17179. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17180. document.getElementById('sdwan-group-id').value = group.id;
  17181. document.getElementById('sdwan-group-name').value = group.name;
  17182. document.getElementById('sdwan-group-name').disabled = true;
  17183. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17184. if (group.mode === 'pcc') {
  17185. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17186. } else {
  17187. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17188. }
  17189. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17190. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17191. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17192. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17193. modal.classList.remove('hidden');
  17194. }
  17195. function closeSDWANGroupModal() {
  17196. const modal = document.getElementById('modal-sdwan-group');
  17197. if (modal) modal.classList.add('hidden');
  17198. }
  17199. function onSDWANModeChange() {
  17200. const mode = document.getElementById('sdwan-group-mode').value;
  17201. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17202. if (pccContainer) {
  17203. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17204. else pccContainer.classList.add('hidden');
  17205. }
  17206. }
  17207. async function saveSDWANGroup(event) {
  17208. event.preventDefault();
  17209. const id = document.getElementById('sdwan-group-id').value;
  17210. const name = document.getElementById('sdwan-group-name').value.trim();
  17211. const mode = document.getElementById('sdwan-group-mode').value;
  17212. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17213. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17214. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17215. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17216. const payload = {
  17217. id: id || undefined,
  17218. name,
  17219. mode,
  17220. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17221. probe_interval: probeInterval,
  17222. auto_nat: autoNAT,
  17223. comment
  17224. };
  17225. try {
  17226. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17227. method: 'POST',
  17228. headers: { 'Content-Type': 'application/json' },
  17229. body: JSON.stringify(payload)
  17230. });
  17231. if (!res.ok) {
  17232. const err = await res.json().catch(() => ({}));
  17233. throw new Error(err.message || 'Failed to save SD-WAN group');
  17234. }
  17235. closeSDWANGroupModal();
  17236. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17237. await loadSDWAN(false);
  17238. } catch (err) {
  17239. showToast('Error', err.message, 'error');
  17240. }
  17241. }
  17242. async function toggleSDWANGroupState(id, currentState) {
  17243. try {
  17244. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17245. method: 'POST',
  17246. headers: { 'Content-Type': 'application/json' },
  17247. body: JSON.stringify({ disabled: currentState })
  17248. });
  17249. if (!res.ok) throw new Error('Failed to update group state');
  17250. await loadSDWAN(false);
  17251. } catch (err) {
  17252. showToast('Error', err.message, 'error');
  17253. }
  17254. }
  17255. async function deleteSDWANGroup(id) {
  17256. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17257. const name = group ? group.name : id;
  17258. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17259. try {
  17260. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17261. method: 'DELETE'
  17262. });
  17263. if (!res.ok) {
  17264. const err = await res.json().catch(() => ({}));
  17265. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17266. }
  17267. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17268. await loadSDWAN(false);
  17269. } catch (err) {
  17270. showToast('Error', err.message, 'error');
  17271. }
  17272. }
  17273. // Modal handling for SD-WAN Members
  17274. function populateSDWANGroupsSelect(selectedId = '') {
  17275. const sel = document.getElementById('sdwan-member-group-id');
  17276. if (!sel) return;
  17277. sel.innerHTML = '';
  17278. (state.sdwanGroups || []).forEach(g => {
  17279. const opt = document.createElement('option');
  17280. opt.value = g.id;
  17281. opt.textContent = `${g.name} (${g.mode})`;
  17282. if (g.id === selectedId) opt.selected = true;
  17283. sel.appendChild(opt);
  17284. });
  17285. }
  17286. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17287. const sel = document.getElementById('sdwan-member-interface');
  17288. if (!sel) return;
  17289. sel.innerHTML = '';
  17290. (state.interfaces || []).forEach(i => {
  17291. const opt = document.createElement('option');
  17292. opt.value = i.name;
  17293. opt.textContent = `${i.name} (${i.role || i.type})`;
  17294. if (i.name === selectedVal) opt.selected = true;
  17295. sel.appendChild(opt);
  17296. });
  17297. }
  17298. function openAddSDWANMemberModal(defaultGroupId = null) {
  17299. const modal = document.getElementById('modal-sdwan-member');
  17300. if (!modal) return;
  17301. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17302. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17303. return;
  17304. }
  17305. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17306. document.getElementById('sdwan-member-id').value = '';
  17307. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17308. populateSDWANMemberInterfaceSelect();
  17309. document.getElementById('sdwan-member-gateway').value = '';
  17310. document.getElementById('sdwan-member-weight').value = 50;
  17311. document.getElementById('sdwan-member-priority').value = 1;
  17312. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17313. document.getElementById('sdwan-member-max-lat').value = 250;
  17314. document.getElementById('sdwan-member-max-loss').value = 20;
  17315. document.getElementById('sdwan-member-comment').value = '';
  17316. modal.classList.remove('hidden');
  17317. }
  17318. function openEditSDWANMemberModal(groupId, memberId) {
  17319. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17320. if (!group) return;
  17321. const member = (group.members || []).find(m => m.id === memberId);
  17322. if (!member) return;
  17323. const modal = document.getElementById('modal-sdwan-member');
  17324. if (!modal) return;
  17325. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17326. document.getElementById('sdwan-member-id').value = member.id;
  17327. populateSDWANGroupsSelect(group.id);
  17328. document.getElementById('sdwan-member-group-id').disabled = true;
  17329. populateSDWANMemberInterfaceSelect(member.interface);
  17330. document.getElementById('sdwan-member-interface').disabled = true;
  17331. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17332. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17333. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17334. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17335. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17336. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17337. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17338. modal.classList.remove('hidden');
  17339. }
  17340. function closeSDWANMemberModal() {
  17341. const modal = document.getElementById('modal-sdwan-member');
  17342. if (modal) {
  17343. document.getElementById('sdwan-member-group-id').disabled = false;
  17344. document.getElementById('sdwan-member-interface').disabled = false;
  17345. modal.classList.add('hidden');
  17346. }
  17347. }
  17348. async function saveSDWANMember(event) {
  17349. event.preventDefault();
  17350. const id = document.getElementById('sdwan-member-id').value;
  17351. const groupId = document.getElementById('sdwan-member-group-id').value;
  17352. const iface = document.getElementById('sdwan-member-interface').value;
  17353. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17354. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17355. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17356. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17357. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17358. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17359. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17360. const payload = {
  17361. id: id || undefined,
  17362. interface: iface,
  17363. gateway,
  17364. weight,
  17365. priority,
  17366. target_probe: targetProbe,
  17367. max_latency: maxLatency,
  17368. max_loss: maxLoss,
  17369. comment
  17370. };
  17371. try {
  17372. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17373. method: 'POST',
  17374. headers: { 'Content-Type': 'application/json' },
  17375. body: JSON.stringify(payload)
  17376. });
  17377. if (!res.ok) {
  17378. const err = await res.json().catch(() => ({}));
  17379. throw new Error(err.message || 'Failed to save member link');
  17380. }
  17381. closeSDWANMemberModal();
  17382. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17383. await loadSDWAN(false);
  17384. } catch (err) {
  17385. showToast('Error', err.message, 'error');
  17386. }
  17387. }
  17388. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17389. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17390. if (!group) return;
  17391. const member = (group.members || []).find(m => m.id === memberId);
  17392. if (!member) return;
  17393. const payload = {
  17394. ...member,
  17395. disabled: currentState
  17396. };
  17397. try {
  17398. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17399. method: 'POST',
  17400. headers: { 'Content-Type': 'application/json' },
  17401. body: JSON.stringify(payload)
  17402. });
  17403. if (!res.ok) throw new Error('Failed to update member state');
  17404. await loadSDWAN(false);
  17405. } catch (err) {
  17406. showToast('Error', err.message, 'error');
  17407. }
  17408. }
  17409. async function deleteSDWANMember(groupId, iface) {
  17410. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17411. try {
  17412. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17413. method: 'DELETE'
  17414. });
  17415. if (!res.ok) {
  17416. const err = await res.json().catch(() => ({}));
  17417. throw new Error(err.message || 'Failed to remove member link');
  17418. }
  17419. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17420. await loadSDWAN(false);
  17421. } catch (err) {
  17422. showToast('Error', err.message, 'error');
  17423. }
  17424. }