app.js 823 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442
  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. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10500. loadDynamicRouting();
  10501. }
  10502. async function disableSelectedOspfStaticNbr() {
  10503. const id = state.selectedOspfRow?.['static-nbrs'];
  10504. if (!id) return;
  10505. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10506. loadDynamicRouting();
  10507. }
  10508. async function removeSelectedOspfStaticNbr() {
  10509. const id = state.selectedOspfRow?.['static-nbrs'];
  10510. if (!id) return;
  10511. if (!confirm('Delete selected static neighbor?')) return;
  10512. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10513. loadDynamicRouting();
  10514. }
  10515. async function promptCommentOspfStaticNbr() {
  10516. const id = state.selectedOspfRow?.['static-nbrs'];
  10517. if (!id) return;
  10518. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10519. if (!n) return;
  10520. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10521. if (comment === null) return;
  10522. n.comment = comment;
  10523. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10524. loadDynamicRouting();
  10525. }
  10526. // Backward-compat aliases
  10527. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10528. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10529. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10530. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10531. function deleteOspfInterface(id) {
  10532. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10533. }
  10534. function toggleOspfInterfaceState(id, disabled) {
  10535. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10536. method: 'POST',
  10537. headers: { 'Content-Type': 'application/json' },
  10538. body: JSON.stringify({ disabled })
  10539. }).then(() => loadDynamicRouting());
  10540. }
  10541. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10542. function deleteOspfArea(id) {
  10543. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10544. }
  10545. // ============================================================================
  10546. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10547. // ============================================================================
  10548. function switchBridgeSubTab(tab) {
  10549. state.bridgeSubTab = tab;
  10550. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10551. tabs.forEach(t => {
  10552. const panel = document.getElementById(`bridge-subtab-${t}`);
  10553. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10554. if (panel) {
  10555. if (t === tab) panel.classList.remove('hidden');
  10556. else panel.classList.add('hidden');
  10557. }
  10558. if (btn) {
  10559. if (t === tab) {
  10560. 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';
  10561. } else {
  10562. 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';
  10563. }
  10564. }
  10565. });
  10566. const addBtn = document.getElementById('bridge-top-action-btn');
  10567. if (addBtn) {
  10568. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10569. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10570. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10571. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10572. }
  10573. if (tab === 'hosts') loadBridgeHosts();
  10574. setTimeout(initTableSorting, 50);
  10575. }
  10576. function openCurrentBridgeModal() {
  10577. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10578. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10579. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10580. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10581. }
  10582. async function loadBridge() {
  10583. try {
  10584. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10585. fetch(`${API_BASE}/bridge/bridges`),
  10586. fetch(`${API_BASE}/bridge/ports`),
  10587. fetch(`${API_BASE}/bridge/vlans`),
  10588. fetch(`${API_BASE}/bridge/summary`),
  10589. fetch(`${API_BASE}/vpn/eoip`),
  10590. fetch(`${API_BASE}/vpn/vxlan`),
  10591. fetch(`${API_BASE}/vlans`)
  10592. ]);
  10593. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10594. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10595. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10596. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10597. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10598. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10599. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10600. // Badges & Stats
  10601. const bBridges = document.getElementById('bridge-badge-bridges');
  10602. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10603. const bPorts = document.getElementById('bridge-badge-ports');
  10604. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10605. const bVlans = document.getElementById('bridge-badge-vlans');
  10606. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10607. const bHosts = document.getElementById('bridge-badge-hosts');
  10608. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10609. const sBr = document.getElementById('bridge-stat-bridges');
  10610. if (sBr) sBr.innerText = (state.bridges || []).length;
  10611. const sPorts = document.getElementById('bridge-stat-ports');
  10612. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10613. const sHosts = document.getElementById('bridge-stat-hosts');
  10614. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10615. renderBridges();
  10616. renderBridgePorts();
  10617. renderBridgeVLANs();
  10618. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10619. } catch (err) {
  10620. console.error('Failed to load bridge subsystem:', err);
  10621. }
  10622. }
  10623. // ----------------- Bridges -----------------
  10624. function renderBridges() {
  10625. const tbody = document.getElementById('bridge-table-body');
  10626. const empty = document.getElementById('bridge-empty-bridges');
  10627. const countBadge = document.getElementById('bridge-count-badge');
  10628. if (!tbody) return;
  10629. tbody.innerHTML = '';
  10630. const bridges = state.bridges || [];
  10631. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10632. if (bridges.length === 0) {
  10633. empty?.classList.remove('hidden');
  10634. return;
  10635. }
  10636. empty?.classList.add('hidden');
  10637. bridges.forEach((b, idx) => {
  10638. const tr = document.createElement('tr');
  10639. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10640. // Format IP addresses pill list
  10641. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10642. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10643. ipsHtml = b.ip_addresses.map(ip => `
  10644. <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">
  10645. <span>${ip}</span>
  10646. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10647. </span>
  10648. `).join(' ');
  10649. }
  10650. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10651. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10652. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10653. tr.innerHTML = `
  10654. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10655. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10656. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10657. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10658. </td>
  10659. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10660. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10661. <td class="py-2.5 px-3">
  10662. <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>
  10663. </td>
  10664. <td class="py-2.5 px-3 text-center">
  10665. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10666. </td>
  10667. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10668. <td class="py-2.5 px-3">
  10669. <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>
  10670. </td>
  10671. <td class="py-2.5 px-3">
  10672. <div class="flex items-center gap-1.5 flex-wrap">
  10673. ${ipsHtml}
  10674. <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>
  10675. </div>
  10676. </td>
  10677. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10678. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10679. </td>
  10680. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10681. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10682. <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>
  10683. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10684. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10685. </td>
  10686. `;
  10687. tbody.appendChild(tr);
  10688. });
  10689. }
  10690. function openAddBridgeModal() {
  10691. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10692. document.getElementById('bridge-modal-id').value = '';
  10693. document.getElementById('bridge-modal-name').value = 'bridge1';
  10694. document.getElementById('bridge-modal-name').disabled = false;
  10695. document.getElementById('bridge-modal-mtu').value = '1500';
  10696. document.getElementById('bridge-modal-mac').value = '';
  10697. document.getElementById('bridge-modal-stp').value = 'stp';
  10698. document.getElementById('bridge-modal-priority').value = '32768';
  10699. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10700. document.getElementById('bridge-modal-pvid').value = '1';
  10701. document.getElementById('bridge-modal-fastforward').checked = true;
  10702. document.getElementById('bridge-modal-comment').value = '';
  10703. document.getElementById('bridge-modal-disabled').checked = false;
  10704. toggleBridgeModalVlanFiltering();
  10705. document.getElementById('bridge-modal').classList.remove('hidden');
  10706. }
  10707. function openEditBridgeModal(id) {
  10708. const b = (state.bridges || []).find(x => x.id === id);
  10709. if (!b) return;
  10710. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10711. document.getElementById('bridge-modal-id').value = b.id;
  10712. document.getElementById('bridge-modal-name').value = b.name;
  10713. document.getElementById('bridge-modal-name').disabled = true;
  10714. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10715. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10716. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10717. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10718. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10719. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10720. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10721. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10722. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10723. toggleBridgeModalVlanFiltering();
  10724. document.getElementById('bridge-modal').classList.remove('hidden');
  10725. }
  10726. function closeBridgeModal() {
  10727. document.getElementById('bridge-modal').classList.add('hidden');
  10728. }
  10729. function toggleBridgeModalVlanFiltering() {
  10730. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10731. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10732. if (pvidBox) {
  10733. if (chk) pvidBox.classList.remove('opacity-40');
  10734. else pvidBox.classList.add('opacity-40');
  10735. }
  10736. }
  10737. async function submitSaveBridge(e) {
  10738. e.preventDefault();
  10739. const id = document.getElementById('bridge-modal-id').value;
  10740. const name = document.getElementById('bridge-modal-name').value.trim();
  10741. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10742. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10743. const stp = document.getElementById('bridge-modal-stp').value;
  10744. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10745. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10746. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10747. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10748. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10749. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10750. try {
  10751. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10752. method: 'POST',
  10753. headers: { 'Content-Type': 'application/json' },
  10754. body: JSON.stringify({
  10755. id,
  10756. name,
  10757. mtu,
  10758. mac_address: mac,
  10759. stp,
  10760. priority,
  10761. vlan_filtering: vlanFiltering,
  10762. pvid,
  10763. fast_forward: fastForward,
  10764. comment,
  10765. disabled
  10766. })
  10767. });
  10768. if (res.ok) {
  10769. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10770. closeBridgeModal();
  10771. loadBridge();
  10772. fetchData(false);
  10773. } else {
  10774. const err = await res.json();
  10775. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10776. }
  10777. } catch (err) {
  10778. showToast('Error', err.message, 'error');
  10779. }
  10780. }
  10781. async function toggleBridgeState(id, disabled) {
  10782. try {
  10783. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10784. method: 'POST',
  10785. headers: { 'Content-Type': 'application/json' },
  10786. body: JSON.stringify({ disabled })
  10787. });
  10788. if (res.ok) {
  10789. loadBridge();
  10790. fetchData(false);
  10791. }
  10792. } catch (err) {
  10793. showToast('Error', err.message, 'error');
  10794. }
  10795. }
  10796. async function deleteBridge(id) {
  10797. const b = (state.bridges || []).find(x => x.id === id);
  10798. const name = b ? b.name : id;
  10799. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10800. try {
  10801. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10802. if (res.ok) {
  10803. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10804. loadBridge();
  10805. fetchData(false);
  10806. } else {
  10807. const err = await res.json();
  10808. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10809. }
  10810. } catch (err) {
  10811. showToast('Error', err.message, 'error');
  10812. }
  10813. }
  10814. // ----------------- Bridge IP Assignments -----------------
  10815. function openAddBridgeIPModal(id, name) {
  10816. document.getElementById('bridge-ip-modal-id').value = id;
  10817. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10818. document.getElementById('bridge-ip-modal-cidr').value = '';
  10819. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10820. }
  10821. function closeBridgeIPModal() {
  10822. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10823. }
  10824. async function submitAddBridgeIP(e) {
  10825. e.preventDefault();
  10826. const id = document.getElementById('bridge-ip-modal-id').value;
  10827. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10828. try {
  10829. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10830. method: 'POST',
  10831. headers: { 'Content-Type': 'application/json' },
  10832. body: JSON.stringify({ ip })
  10833. });
  10834. if (res.ok) {
  10835. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10836. closeBridgeIPModal();
  10837. loadBridge();
  10838. fetchData(false);
  10839. } else {
  10840. const err = await res.json();
  10841. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10842. }
  10843. } catch (err) {
  10844. showToast('Error', err.message, 'error');
  10845. }
  10846. }
  10847. async function deleteBridgeIP(id, ip) {
  10848. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10849. try {
  10850. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10851. method: 'DELETE',
  10852. headers: { 'Content-Type': 'application/json' },
  10853. body: JSON.stringify({ ip })
  10854. });
  10855. if (res.ok) {
  10856. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10857. loadBridge();
  10858. fetchData(false);
  10859. }
  10860. } catch (err) {
  10861. showToast('Error', err.message, 'error');
  10862. }
  10863. }
  10864. // ----------------- Bridge Ports -----------------
  10865. function renderBridgePorts() {
  10866. const tbody = document.getElementById('bridge-ports-table-body');
  10867. const empty = document.getElementById('bridge-empty-ports');
  10868. const countBadge = document.getElementById('bridge-ports-count-badge');
  10869. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10870. if (!tbody) return;
  10871. tbody.innerHTML = '';
  10872. // Update filter select
  10873. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10874. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10875. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10876. if (ports.length === 0) {
  10877. empty?.classList.remove('hidden');
  10878. return;
  10879. }
  10880. empty?.classList.add('hidden');
  10881. ports.forEach((p, idx) => {
  10882. const tr = document.createElement('tr');
  10883. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10884. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10885. tr.innerHTML = `
  10886. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10887. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10888. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10889. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10890. </td>
  10891. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10892. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10893. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10894. <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>
  10895. <td class="py-2.5 px-3">
  10896. ${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>'}
  10897. </td>
  10898. <td class="py-2.5 px-3">
  10899. <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>
  10900. </td>
  10901. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10902. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10903. <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>
  10904. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10905. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10906. </td>
  10907. `;
  10908. tbody.appendChild(tr);
  10909. });
  10910. }
  10911. function openAddBridgePortModal() {
  10912. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10913. document.getElementById('bridge-port-modal-id').value = '';
  10914. populateBridgeSelect('bridge-port-modal-bridge');
  10915. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10916. document.getElementById('bridge-port-modal-pvid').value = '1';
  10917. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10918. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10919. document.getElementById('bridge-port-modal-horizon').value = '0';
  10920. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10921. document.getElementById('bridge-port-modal-priority').value = '128';
  10922. document.getElementById('bridge-port-modal-learn').checked = true;
  10923. document.getElementById('bridge-port-modal-comment').value = '';
  10924. document.getElementById('bridge-port-modal-disabled').checked = false;
  10925. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10926. }
  10927. function openEditBridgePortModal(id) {
  10928. const p = (state.bridgePorts || []).find(x => x.id === id);
  10929. if (!p) return;
  10930. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10931. document.getElementById('bridge-port-modal-id').value = p.id;
  10932. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10933. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10934. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10935. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10936. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10937. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10938. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10939. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10940. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10941. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10942. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10943. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10944. }
  10945. function closeBridgePortModal() {
  10946. document.getElementById('bridge-port-modal').classList.add('hidden');
  10947. }
  10948. async function submitSaveBridgePort(e) {
  10949. e.preventDefault();
  10950. const id = document.getElementById('bridge-port-modal-id').value;
  10951. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10952. const iface = document.getElementById('bridge-port-modal-interface').value;
  10953. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10954. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10955. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10956. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10957. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10958. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10959. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10960. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10961. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10962. try {
  10963. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10964. method: 'POST',
  10965. headers: { 'Content-Type': 'application/json' },
  10966. body: JSON.stringify({
  10967. id,
  10968. bridge,
  10969. interface: iface,
  10970. pvid,
  10971. frame_types: frameTypes,
  10972. ingress_filtering: ingressFiltering,
  10973. horizon,
  10974. path_cost: pathCost,
  10975. priority,
  10976. learn,
  10977. comment,
  10978. disabled
  10979. })
  10980. });
  10981. if (res.ok) {
  10982. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10983. closeBridgePortModal();
  10984. loadBridge();
  10985. fetchData(false);
  10986. } else {
  10987. const err = await res.json();
  10988. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10989. }
  10990. } catch (err) {
  10991. showToast('Error', err.message, 'error');
  10992. }
  10993. }
  10994. async function toggleBridgePortState(id, disabled) {
  10995. try {
  10996. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10997. method: 'POST',
  10998. headers: { 'Content-Type': 'application/json' },
  10999. body: JSON.stringify({ disabled })
  11000. });
  11001. if (res.ok) {
  11002. loadBridge();
  11003. fetchData(false);
  11004. }
  11005. } catch (err) {
  11006. showToast('Error', err.message, 'error');
  11007. }
  11008. }
  11009. async function deleteBridgePort(id) {
  11010. const p = (state.bridgePorts || []).find(x => x.id === id);
  11011. const iface = p ? p.interface : id;
  11012. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11013. try {
  11014. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11015. if (res.ok) {
  11016. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11017. loadBridge();
  11018. fetchData(false);
  11019. }
  11020. } catch (err) {
  11021. showToast('Error', err.message, 'error');
  11022. }
  11023. }
  11024. // ----------------- Bridge VLANs -----------------
  11025. function renderBridgeVLANs() {
  11026. const tbody = document.getElementById('bridge-vlans-table-body');
  11027. const empty = document.getElementById('bridge-empty-vlans');
  11028. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11029. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11030. if (!tbody) return;
  11031. tbody.innerHTML = '';
  11032. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11033. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11034. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11035. if (vlans.length === 0) {
  11036. empty?.classList.remove('hidden');
  11037. return;
  11038. }
  11039. empty?.classList.add('hidden');
  11040. vlans.forEach((v, idx) => {
  11041. const tr = document.createElement('tr');
  11042. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11043. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11044. ? 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(' ')
  11045. : '<span class="text-slate-600">none</span>';
  11046. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11047. ? 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(' ')
  11048. : '<span class="text-slate-600">none</span>';
  11049. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11050. tr.innerHTML = `
  11051. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11052. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11053. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11054. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11055. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11056. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11057. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11058. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11059. <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>
  11060. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11061. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11062. </td>
  11063. `;
  11064. tbody.appendChild(tr);
  11065. });
  11066. }
  11067. function openAddBridgeVLANModal() {
  11068. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11069. document.getElementById('bridge-vlan-modal-id').value = '';
  11070. populateBridgeSelect('bridge-vlan-modal-bridge');
  11071. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11072. document.getElementById('bridge-vlan-modal-comment').value = '';
  11073. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11074. updateBridgeVlanPortCheckboxes();
  11075. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11076. }
  11077. function openEditBridgeVLANModal(id) {
  11078. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11079. if (!v) return;
  11080. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11081. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11082. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11083. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11084. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11085. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11086. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11087. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11088. }
  11089. function closeBridgeVlanModal() {
  11090. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11091. }
  11092. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11093. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11094. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11095. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11096. if (!taggedBox || !untaggedBox) return;
  11097. // Ports belonging to the selected bridge
  11098. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11099. if (memberPorts.length === 0) {
  11100. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11101. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11102. return;
  11103. }
  11104. taggedBox.innerHTML = memberPorts.map(p => `
  11105. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11106. <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">
  11107. <span>${p.interface}</span>
  11108. </label>
  11109. `).join('');
  11110. untaggedBox.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-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  11113. <span>${p.interface}</span>
  11114. </label>
  11115. `).join('');
  11116. }
  11117. async function submitSaveBridgeVLAN(e) {
  11118. e.preventDefault();
  11119. const id = document.getElementById('bridge-vlan-modal-id').value;
  11120. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11121. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11122. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11123. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11124. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11125. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11126. try {
  11127. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11128. method: 'POST',
  11129. headers: { 'Content-Type': 'application/json' },
  11130. body: JSON.stringify({
  11131. id,
  11132. bridge,
  11133. vlan_ids: vlanIDs,
  11134. tagged,
  11135. untagged,
  11136. comment,
  11137. disabled
  11138. })
  11139. });
  11140. if (res.ok) {
  11141. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11142. closeBridgeVlanModal();
  11143. loadBridge();
  11144. } else {
  11145. const err = await res.json();
  11146. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11147. }
  11148. } catch (err) {
  11149. showToast('Error', err.message, 'error');
  11150. }
  11151. }
  11152. async function toggleBridgeVLANState(id, disabled) {
  11153. try {
  11154. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11155. method: 'POST',
  11156. headers: { 'Content-Type': 'application/json' },
  11157. body: JSON.stringify({ disabled })
  11158. });
  11159. if (res.ok) loadBridge();
  11160. } catch (err) {
  11161. showToast('Error', err.message, 'error');
  11162. }
  11163. }
  11164. async function deleteBridgeVLAN(id) {
  11165. if (!confirm('Delete this bridge VLAN entry?')) return;
  11166. try {
  11167. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11168. if (res.ok) {
  11169. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11170. loadBridge();
  11171. }
  11172. } catch (err) {
  11173. showToast('Error', err.message, 'error');
  11174. }
  11175. }
  11176. // ----------------- Hosts / MAC Table -----------------
  11177. async function loadBridgeHosts() {
  11178. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11179. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11180. try {
  11181. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11182. const res = await fetch(url);
  11183. if (res.ok) {
  11184. state.bridgeHosts = await res.json();
  11185. renderBridgeHosts();
  11186. }
  11187. } catch (err) {
  11188. console.error('Failed to load bridge hosts:', err);
  11189. }
  11190. }
  11191. function renderBridgeHosts() {
  11192. const tbody = document.getElementById('bridge-hosts-table-body');
  11193. const empty = document.getElementById('bridge-empty-hosts');
  11194. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11195. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11196. if (!tbody) return;
  11197. tbody.innerHTML = '';
  11198. const hosts = (state.bridgeHosts || []).filter(h => {
  11199. if (!search) return true;
  11200. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11201. });
  11202. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11203. if (hosts.length === 0) {
  11204. empty?.classList.remove('hidden');
  11205. return;
  11206. }
  11207. empty?.classList.add('hidden');
  11208. hosts.forEach(h => {
  11209. const tr = document.createElement('tr');
  11210. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11211. let flagBadges = '';
  11212. 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>';
  11213. 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>';
  11214. 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>';
  11215. tr.innerHTML = `
  11216. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11217. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11218. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11219. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11220. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11221. <td class="py-2.5 px-3">${flagBadges}</td>
  11222. `;
  11223. tbody.appendChild(tr);
  11224. });
  11225. }
  11226. async function flushBridgeHosts() {
  11227. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11228. if (!selBridge) {
  11229. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11230. return;
  11231. }
  11232. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11233. try {
  11234. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11235. method: 'POST',
  11236. headers: { 'Content-Type': 'application/json' },
  11237. body: JSON.stringify({ bridge: selBridge })
  11238. });
  11239. if (res.ok) {
  11240. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11241. loadBridgeHosts();
  11242. }
  11243. } catch (err) {
  11244. showToast('Error', err.message, 'error');
  11245. }
  11246. }
  11247. // ----------------- Helpers -----------------
  11248. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11249. const sel = document.getElementById(selectId);
  11250. if (!sel) return;
  11251. const prevVal = currentVal || sel.value;
  11252. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11253. (state.bridges || []).forEach(b => {
  11254. const opt = document.createElement('option');
  11255. opt.value = b.name;
  11256. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11257. if (b.name === prevVal) opt.selected = true;
  11258. sel.appendChild(opt);
  11259. });
  11260. }
  11261. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11262. const sel = document.getElementById(selectId);
  11263. if (!sel) return;
  11264. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11265. // 1. Physical Interfaces
  11266. const grpPhys = document.createElement('optgroup');
  11267. grpPhys.label = 'Physical Interfaces';
  11268. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11269. const opt = document.createElement('option');
  11270. opt.value = i.name;
  11271. opt.innerText = `${i.name} (${i.role || i.type})`;
  11272. if (i.name === currentVal) opt.selected = true;
  11273. grpPhys.appendChild(opt);
  11274. });
  11275. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11276. // 2. VLAN Sub-interfaces
  11277. const grpVlans = document.createElement('optgroup');
  11278. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11279. (state.vlans || []).forEach(v => {
  11280. const opt = document.createElement('option');
  11281. opt.value = v.name;
  11282. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11283. if (v.name === currentVal) opt.selected = true;
  11284. grpVlans.appendChild(opt);
  11285. });
  11286. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11287. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11288. const grpEoip = document.createElement('optgroup');
  11289. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11290. (state.eoipTunnels || []).forEach(t => {
  11291. const opt = document.createElement('option');
  11292. opt.value = t.name;
  11293. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11294. if (t.name === currentVal) opt.selected = true;
  11295. grpEoip.appendChild(opt);
  11296. });
  11297. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11298. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11299. const grpVxlan = document.createElement('optgroup');
  11300. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11301. (state.vxlanTunnels || []).forEach(t => {
  11302. const opt = document.createElement('option');
  11303. opt.value = t.name;
  11304. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11305. if (t.name === currentVal) opt.selected = true;
  11306. grpVxlan.appendChild(opt);
  11307. });
  11308. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11309. }
  11310. // -------------------------------------------------------------
  11311. // DebTik Routing Filters Management (/routing filter)
  11312. // -------------------------------------------------------------
  11313. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11314. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11315. if (!state.rfSort) state.rfSort = {};
  11316. function switchRoutingFilterTab(tab) {
  11317. state.activeRoutingFilterTab = tab;
  11318. const tabs = ['rules', 'community-lists', 'as-lists'];
  11319. tabs.forEach(t => {
  11320. const btn = document.getElementById(`tab-rf-${t}`);
  11321. const content = document.getElementById(`tab-content-rf-${t}`);
  11322. if (btn) {
  11323. if (t === tab) {
  11324. 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';
  11325. } else {
  11326. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11327. }
  11328. }
  11329. if (content) {
  11330. if (t === tab) content.classList.remove('hidden');
  11331. else content.classList.add('hidden');
  11332. }
  11333. });
  11334. const chainContainer = document.getElementById('rf-chain-filter-container');
  11335. if (chainContainer) {
  11336. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11337. else chainContainer.classList.add('hidden');
  11338. }
  11339. renderRoutingFilters();
  11340. }
  11341. function selectFilterRow(tab, id) {
  11342. if (state.selectedFilterRow[tab] === id) {
  11343. delete state.selectedFilterRow[tab];
  11344. } else {
  11345. state.selectedFilterRow[tab] = id;
  11346. }
  11347. if (tab === 'rules') renderRoutingFilterRules();
  11348. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11349. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11350. }
  11351. function openRoutingFilterNewModal() {
  11352. const tab = state.activeRoutingFilterTab || 'rules';
  11353. if (tab === 'rules') openAddRoutingFilterModal();
  11354. else if (tab === 'community-lists') openAddCommunityListModal();
  11355. else if (tab === 'as-lists') openAddASListModal();
  11356. }
  11357. function toggleSelectedRoutingFilter(disabled) {
  11358. const tab = state.activeRoutingFilterTab || 'rules';
  11359. const id = state.selectedFilterRow[tab];
  11360. if (!id) {
  11361. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11362. return;
  11363. }
  11364. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11365. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11366. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11367. }
  11368. function removeSelectedRoutingFilter() {
  11369. const tab = state.activeRoutingFilterTab || 'rules';
  11370. const id = state.selectedFilterRow[tab];
  11371. if (!id) {
  11372. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11373. return;
  11374. }
  11375. if (tab === 'rules') deleteRoutingFilter(id);
  11376. else if (tab === 'community-lists') deleteCommunityList(id);
  11377. else if (tab === 'as-lists') deleteASList(id);
  11378. }
  11379. function searchRoutingFilters(q) {
  11380. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11381. renderRoutingFilters();
  11382. }
  11383. function sortFilterTable(tab, col) {
  11384. if (!state.rfSort) state.rfSort = {};
  11385. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11386. if (state.rfSort[tab].col === col) {
  11387. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11388. } else {
  11389. state.rfSort[tab].col = col;
  11390. state.rfSort[tab].asc = true;
  11391. }
  11392. const asc = state.rfSort[tab].asc;
  11393. let list = [];
  11394. if (tab === 'rules') list = state.routingFilters || [];
  11395. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11396. else if (tab === 'as-lists') list = state.routingASLists || [];
  11397. list.sort((a, b) => {
  11398. let valA = a[col] ?? '';
  11399. let valB = b[col] ?? '';
  11400. if (col === 'flags') {
  11401. valA = a.disabled ? 'X' : 'A';
  11402. valB = b.disabled ? 'X' : 'A';
  11403. }
  11404. if (typeof valA === 'number' && typeof valB === 'number') {
  11405. return asc ? valA - valB : valB - valA;
  11406. }
  11407. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11408. });
  11409. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11410. allCols.forEach(c => {
  11411. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11412. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11413. });
  11414. if (tab === 'rules') renderRoutingFilterRules();
  11415. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11416. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11417. }
  11418. function renderRoutingFilters() {
  11419. const navBadge = document.getElementById('badge-filters-count');
  11420. const allRules = state.routingFilters || [];
  11421. if (navBadge) navBadge.innerText = allRules.length;
  11422. // Populate chain filter select options and datalist
  11423. const chainSelect = document.getElementById('routing-filter-chain-select');
  11424. const chainDatalist = document.getElementById('dl-routing-chains');
  11425. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11426. if (chainSelect) {
  11427. const currentVal = state.filterChainSelected || 'all';
  11428. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11429. uniqueChains.map(ch => {
  11430. const count = allRules.filter(r => r.chain === ch).length;
  11431. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11432. }).join('');
  11433. chainSelect.value = currentVal;
  11434. }
  11435. if (chainDatalist) {
  11436. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11437. }
  11438. renderRoutingFilterRules();
  11439. renderRoutingFilterCommunityLists();
  11440. renderRoutingFilterASLists();
  11441. }
  11442. function filterRoutingFiltersByChain(chain) {
  11443. state.filterChainSelected = chain;
  11444. renderRoutingFilters();
  11445. }
  11446. // -------------------------------------------------------------
  11447. // TAB 1: RULES (/routing filter rule)
  11448. // -------------------------------------------------------------
  11449. function renderRoutingFilterRules() {
  11450. const tbody = document.getElementById('routing-filter-rules-tbody');
  11451. if (!tbody) return;
  11452. const empty = document.getElementById('rf-rules-empty');
  11453. const statusCount = document.getElementById('rf-status-count');
  11454. let list = (state.routingFilters || []).slice();
  11455. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11456. list = list.filter(r => r.chain === state.filterChainSelected);
  11457. }
  11458. const q = state.rfSearchQuery;
  11459. if (q) {
  11460. list = list.filter(r =>
  11461. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11462. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11463. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11464. (r.comment && r.comment.toLowerCase().includes(q))
  11465. );
  11466. }
  11467. if (!state.rfSort?.['rules']) {
  11468. list.sort((a, b) => {
  11469. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11470. return (a.rule_order || 0) - (b.rule_order || 0);
  11471. });
  11472. }
  11473. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11474. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11475. }
  11476. if (list.length === 0) {
  11477. tbody.innerHTML = '';
  11478. if (empty) empty.classList.remove('hidden');
  11479. return;
  11480. }
  11481. if (empty) empty.classList.add('hidden');
  11482. tbody.innerHTML = list.map(r => {
  11483. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11484. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11485. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11486. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11487. let ruleDisplay = '';
  11488. if (r.rule && r.rule.trim() !== '') {
  11489. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11490. } else {
  11491. let conds = [];
  11492. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11493. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11494. let act = r.action || 'accept';
  11495. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11496. }
  11497. return `
  11498. <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'}">
  11499. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11500. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11501. <td class="py-2 px-3">
  11502. <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>
  11503. </td>
  11504. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11505. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11506. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11507. <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>
  11508. <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>
  11509. <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'}">
  11510. ${r.disabled ? 'Enable' : 'Disable'}
  11511. </button>
  11512. <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">
  11513. Edit
  11514. </button>
  11515. <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">
  11516. ✕
  11517. </button>
  11518. </td>
  11519. </tr>
  11520. `;
  11521. }).join('');
  11522. }
  11523. // -------------------------------------------------------------
  11524. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11525. // -------------------------------------------------------------
  11526. function renderRoutingFilterCommunityLists() {
  11527. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11528. if (!tbody) return;
  11529. const empty = document.getElementById('rf-comm-lists-empty');
  11530. const statusCount = document.getElementById('rf-status-count');
  11531. let list = (state.routingCommunityLists || []).slice();
  11532. const q = state.rfSearchQuery;
  11533. if (q) {
  11534. list = list.filter(cl =>
  11535. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11536. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11537. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11538. );
  11539. }
  11540. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11541. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11542. }
  11543. if (list.length === 0) {
  11544. tbody.innerHTML = '';
  11545. if (empty) empty.classList.remove('hidden');
  11546. return;
  11547. }
  11548. if (empty) empty.classList.add('hidden');
  11549. tbody.innerHTML = list.map(cl => {
  11550. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11551. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11552. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11553. const commBadges = (cl.communities || []).map(c =>
  11554. `<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>`
  11555. ).join(' ');
  11556. return `
  11557. <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'}">
  11558. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11559. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11560. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11561. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11562. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11563. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11564. <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'}">
  11565. ${cl.disabled ? 'Enable' : 'Disable'}
  11566. </button>
  11567. <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">
  11568. Edit
  11569. </button>
  11570. <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">
  11571. ✕
  11572. </button>
  11573. </td>
  11574. </tr>
  11575. `;
  11576. }).join('');
  11577. }
  11578. // -------------------------------------------------------------
  11579. // TAB 4: AS LISTS (/routing filter num-list)
  11580. // -------------------------------------------------------------
  11581. function renderRoutingFilterASLists() {
  11582. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11583. if (!tbody) return;
  11584. const empty = document.getElementById('rf-as-lists-empty');
  11585. const statusCount = document.getElementById('rf-status-count');
  11586. let list = (state.routingASLists || []).slice();
  11587. const q = state.rfSearchQuery;
  11588. if (q) {
  11589. list = list.filter(al =>
  11590. (al.name && al.name.toLowerCase().includes(q)) ||
  11591. (al.range && al.range.toLowerCase().includes(q)) ||
  11592. (al.comment && al.comment.toLowerCase().includes(q))
  11593. );
  11594. }
  11595. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11596. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11597. }
  11598. if (list.length === 0) {
  11599. tbody.innerHTML = '';
  11600. if (empty) empty.classList.remove('hidden');
  11601. return;
  11602. }
  11603. if (empty) empty.classList.add('hidden');
  11604. tbody.innerHTML = list.map(al => {
  11605. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11606. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11607. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11608. return `
  11609. <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'}">
  11610. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11611. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11612. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11613. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11614. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11615. <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'}">
  11616. ${al.disabled ? 'Enable' : 'Disable'}
  11617. </button>
  11618. <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">
  11619. Edit
  11620. </button>
  11621. <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">
  11622. ✕
  11623. </button>
  11624. </td>
  11625. </tr>
  11626. `;
  11627. }).join('');
  11628. }
  11629. // -------------------------------------------------------------
  11630. // SNIPPETS & WIZARD HELPERS
  11631. // -------------------------------------------------------------
  11632. function insertRuleSnippet(type) {
  11633. const textarea = document.getElementById('modal-rf-rule');
  11634. if (!textarea) return;
  11635. let snippet = '';
  11636. switch (type) {
  11637. case 'accept-default':
  11638. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11639. break;
  11640. case 'drop-rfc1918':
  11641. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11642. break;
  11643. case 'len-24':
  11644. snippet = 'if (dst-len > 24) { reject; }';
  11645. break;
  11646. case 'local-pref-150':
  11647. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11648. break;
  11649. case 'as-prepend-2':
  11650. snippet = 'set bgp-path-prepend 2; accept;';
  11651. break;
  11652. case 'set-comm':
  11653. snippet = 'set bgp-communities.add 65000:100; accept;';
  11654. break;
  11655. case 'match-comm':
  11656. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11657. break;
  11658. case 'reject-all':
  11659. snippet = 'reject;';
  11660. break;
  11661. }
  11662. if (!snippet) return;
  11663. if (!textarea.value.trim()) {
  11664. textarea.value = snippet;
  11665. } else {
  11666. textarea.value = textarea.value.trim() + '\n' + snippet;
  11667. }
  11668. }
  11669. function generateScriptFromWizard() {
  11670. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11671. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11672. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11673. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11674. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11675. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11676. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11677. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11678. const conds = [];
  11679. if (pfx) {
  11680. if (pfxLen) {
  11681. if (pfxLen.includes('-')) {
  11682. const parts = pfxLen.split('-');
  11683. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11684. } else {
  11685. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11686. }
  11687. } else {
  11688. conds.push(`dst in ${pfx}`);
  11689. }
  11690. }
  11691. if (proto && proto !== 'any') {
  11692. conds.push(`protocol ${proto}`);
  11693. }
  11694. if (asp) {
  11695. conds.push(`bgp-as-path "${asp}"`);
  11696. }
  11697. if (comm) {
  11698. conds.push(`bgp-communities includes ${comm}`);
  11699. }
  11700. const actions = [];
  11701. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11702. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11703. if (act && act !== 'passthrough') {
  11704. actions.push(`${act};`);
  11705. }
  11706. let code = '';
  11707. if (conds.length > 0) {
  11708. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11709. } else {
  11710. code = actions.join(' ');
  11711. }
  11712. const textarea = document.getElementById('modal-rf-rule');
  11713. if (textarea) textarea.value = code;
  11714. }
  11715. // -------------------------------------------------------------
  11716. // MODAL CRUD: RULES (/routing filter rule)
  11717. // -------------------------------------------------------------
  11718. function openAddRoutingFilterModal(defaultChain = '') {
  11719. const form = document.getElementById('routing-filter-form');
  11720. if (form) form.reset();
  11721. const idEl = document.getElementById('modal-rf-id');
  11722. if (idEl) idEl.value = '';
  11723. const titleEl = document.getElementById('modal-rf-title');
  11724. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11725. const chainEl = document.getElementById('modal-rf-chain');
  11726. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11727. const orderEl = document.getElementById('modal-rf-order');
  11728. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11729. const ruleEl = document.getElementById('modal-rf-rule');
  11730. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11731. const disEl = document.getElementById('modal-rf-disabled');
  11732. if (disEl) disEl.checked = false;
  11733. const modal = document.getElementById('modal-routing-filter');
  11734. if (modal) modal.classList.remove('hidden');
  11735. }
  11736. function openEditRoutingFilterModal(id) {
  11737. const r = (state.routingFilters || []).find(item => item.id === id);
  11738. if (!r) return;
  11739. const idEl = document.getElementById('modal-rf-id');
  11740. if (idEl) idEl.value = r.id;
  11741. const titleEl = document.getElementById('modal-rf-title');
  11742. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11743. const chainEl = document.getElementById('modal-rf-chain');
  11744. if (chainEl) chainEl.value = r.chain || '';
  11745. const orderEl = document.getElementById('modal-rf-order');
  11746. if (orderEl) orderEl.value = r.rule_order || 10;
  11747. const ruleEl = document.getElementById('modal-rf-rule');
  11748. if (ruleEl) {
  11749. if (r.rule) {
  11750. ruleEl.value = r.rule;
  11751. } else {
  11752. let conds = [];
  11753. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11754. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11755. let act = r.action || 'accept';
  11756. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11757. }
  11758. }
  11759. const comEl = document.getElementById('modal-rf-comment');
  11760. if (comEl) comEl.value = r.comment || '';
  11761. const disEl = document.getElementById('modal-rf-disabled');
  11762. if (disEl) disEl.checked = !!r.disabled;
  11763. const modal = document.getElementById('modal-routing-filter');
  11764. if (modal) modal.classList.remove('hidden');
  11765. }
  11766. function closeRoutingFilterModal() {
  11767. const modal = document.getElementById('modal-routing-filter');
  11768. if (modal) modal.classList.add('hidden');
  11769. }
  11770. async function submitRoutingFilter(e) {
  11771. if (e) e.preventDefault();
  11772. const payload = {
  11773. id: document.getElementById('modal-rf-id').value,
  11774. chain: document.getElementById('modal-rf-chain').value.trim(),
  11775. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11776. rule: document.getElementById('modal-rf-rule').value.trim(),
  11777. comment: document.getElementById('modal-rf-comment').value.trim(),
  11778. disabled: document.getElementById('modal-rf-disabled').checked
  11779. };
  11780. try {
  11781. const res = await fetch(`${API_BASE}/routing/filters`, {
  11782. method: 'POST',
  11783. headers: { 'Content-Type': 'application/json' },
  11784. body: JSON.stringify(payload)
  11785. });
  11786. if (res.ok) {
  11787. closeRoutingFilterModal();
  11788. showToast('Success', 'Routing filter rule saved', 'success');
  11789. loadDynamicRouting();
  11790. } else {
  11791. const err = await res.json();
  11792. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11793. }
  11794. } catch (err) {
  11795. showToast('Error', err.message, 'error');
  11796. }
  11797. }
  11798. async function applyRoutingFilterForm() {
  11799. const payload = {
  11800. id: document.getElementById('modal-rf-id').value,
  11801. chain: document.getElementById('modal-rf-chain').value.trim(),
  11802. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11803. rule: document.getElementById('modal-rf-rule').value.trim(),
  11804. comment: document.getElementById('modal-rf-comment').value.trim(),
  11805. disabled: document.getElementById('modal-rf-disabled').checked
  11806. };
  11807. try {
  11808. const res = await fetch(`${API_BASE}/routing/filters`, {
  11809. method: 'POST',
  11810. headers: { 'Content-Type': 'application/json' },
  11811. body: JSON.stringify(payload)
  11812. });
  11813. if (res.ok) {
  11814. const data = await res.json();
  11815. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11816. showToast('Applied', 'Routing filter configuration applied', 'success');
  11817. loadDynamicRouting();
  11818. } else {
  11819. const err = await res.json();
  11820. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11821. }
  11822. } catch (err) {
  11823. showToast('Error', err.message, 'error');
  11824. }
  11825. }
  11826. async function moveRoutingFilterOrder(id, delta) {
  11827. const list = state.routingFilters || [];
  11828. const idx = list.findIndex(r => r.id === id);
  11829. if (idx < 0) return;
  11830. const targetIdx = idx + delta;
  11831. if (targetIdx < 0 || targetIdx >= list.length) return;
  11832. const currentOrder = list[idx].rule_order || 10;
  11833. const targetOrder = list[targetIdx].rule_order || 20;
  11834. list[idx].rule_order = targetOrder;
  11835. list[targetIdx].rule_order = currentOrder;
  11836. try {
  11837. await fetch(`${API_BASE}/routing/filters`, {
  11838. method: 'POST',
  11839. headers: { 'Content-Type': 'application/json' },
  11840. body: JSON.stringify(list[idx])
  11841. });
  11842. await fetch(`${API_BASE}/routing/filters`, {
  11843. method: 'POST',
  11844. headers: { 'Content-Type': 'application/json' },
  11845. body: JSON.stringify(list[targetIdx])
  11846. });
  11847. loadDynamicRouting();
  11848. } catch (e) {
  11849. console.error('Reorder error:', e);
  11850. }
  11851. }
  11852. async function deleteRoutingFilter(id) {
  11853. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11854. try {
  11855. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11856. if (res.ok) {
  11857. showToast('Deleted', 'Routing filter rule removed', 'info');
  11858. loadDynamicRouting();
  11859. } else {
  11860. const err = await res.json();
  11861. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11862. }
  11863. } catch (err) {
  11864. showToast('Error', err.message, 'error');
  11865. }
  11866. }
  11867. async function toggleRoutingFilterState(id, disabled) {
  11868. try {
  11869. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11870. method: 'POST',
  11871. headers: { 'Content-Type': 'application/json' },
  11872. body: JSON.stringify({ disabled })
  11873. });
  11874. if (res.ok) {
  11875. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11876. loadDynamicRouting();
  11877. } else {
  11878. const err = await res.json();
  11879. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11880. }
  11881. } catch (err) {
  11882. showToast('Error', err.message, 'error');
  11883. }
  11884. }
  11885. // -------------------------------------------------------------
  11886. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11887. // -------------------------------------------------------------
  11888. function openAddCommunityListModal() {
  11889. document.getElementById('modal-rf-cl-id').value = '';
  11890. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11891. document.getElementById('modal-rf-cl-name').value = '';
  11892. document.getElementById('modal-rf-cl-communities').value = '';
  11893. document.getElementById('modal-rf-cl-regexp').value = '';
  11894. document.getElementById('modal-rf-cl-comment').value = '';
  11895. document.getElementById('modal-rf-cl-disabled').checked = false;
  11896. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11897. }
  11898. function openEditCommunityListModal(id) {
  11899. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11900. if (!cl) return;
  11901. document.getElementById('modal-rf-cl-id').value = cl.id;
  11902. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11903. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11904. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11905. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11906. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11907. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11908. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11909. }
  11910. function closeCommunityListModal() {
  11911. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11912. }
  11913. async function submitCommunityList(e) {
  11914. e.preventDefault();
  11915. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11916. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11917. const payload = {
  11918. id: document.getElementById('modal-rf-cl-id').value,
  11919. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11920. communities: comms,
  11921. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11922. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11923. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11924. };
  11925. try {
  11926. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11927. method: 'POST',
  11928. headers: { 'Content-Type': 'application/json' },
  11929. body: JSON.stringify(payload)
  11930. });
  11931. if (res.ok) {
  11932. closeCommunityListModal();
  11933. showToast('Success', 'Community list saved', 'success');
  11934. loadDynamicRouting();
  11935. } else {
  11936. const err = await res.json();
  11937. showToast('Error', err.error || 'Failed to save community list', 'error');
  11938. }
  11939. } catch (err) {
  11940. showToast('Error', err.message, 'error');
  11941. }
  11942. }
  11943. async function deleteCommunityList(id) {
  11944. if (!confirm('Are you sure you want to delete this community list?')) return;
  11945. try {
  11946. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11947. if (res.ok) {
  11948. showToast('Deleted', 'Community list removed', 'info');
  11949. loadDynamicRouting();
  11950. } else {
  11951. const err = await res.json();
  11952. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11953. }
  11954. } catch (err) {
  11955. showToast('Error', err.message, 'error');
  11956. }
  11957. }
  11958. async function toggleCommunityListState(id, disabled) {
  11959. try {
  11960. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11961. method: 'POST',
  11962. headers: { 'Content-Type': 'application/json' },
  11963. body: JSON.stringify({ disabled })
  11964. });
  11965. if (res.ok) {
  11966. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11967. loadDynamicRouting();
  11968. } else {
  11969. const err = await res.json();
  11970. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11971. }
  11972. } catch (err) {
  11973. showToast('Error', err.message, 'error');
  11974. }
  11975. }
  11976. // -------------------------------------------------------------
  11977. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11978. // -------------------------------------------------------------
  11979. function openAddASListModal() {
  11980. document.getElementById('modal-rf-al-id').value = '';
  11981. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11982. document.getElementById('modal-rf-al-name').value = '';
  11983. document.getElementById('modal-rf-al-range').value = '';
  11984. document.getElementById('modal-rf-al-comment').value = '';
  11985. document.getElementById('modal-rf-al-disabled').checked = false;
  11986. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11987. }
  11988. function openEditASListModal(id) {
  11989. const al = (state.routingASLists || []).find(item => item.id === id);
  11990. if (!al) return;
  11991. document.getElementById('modal-rf-al-id').value = al.id;
  11992. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11993. document.getElementById('modal-rf-al-name').value = al.name || '';
  11994. document.getElementById('modal-rf-al-range').value = al.range || '';
  11995. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11996. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11997. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11998. }
  11999. function closeASListModal() {
  12000. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12001. }
  12002. async function submitASList(e) {
  12003. e.preventDefault();
  12004. const payload = {
  12005. id: document.getElementById('modal-rf-al-id').value,
  12006. name: document.getElementById('modal-rf-al-name').value.trim(),
  12007. range: document.getElementById('modal-rf-al-range').value.trim(),
  12008. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12009. disabled: document.getElementById('modal-rf-al-disabled').checked
  12010. };
  12011. try {
  12012. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12013. method: 'POST',
  12014. headers: { 'Content-Type': 'application/json' },
  12015. body: JSON.stringify(payload)
  12016. });
  12017. if (res.ok) {
  12018. closeASListModal();
  12019. showToast('Success', 'AS number list saved', 'success');
  12020. loadDynamicRouting();
  12021. } else {
  12022. const err = await res.json();
  12023. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12024. }
  12025. } catch (err) {
  12026. showToast('Error', err.message, 'error');
  12027. }
  12028. }
  12029. async function deleteASList(id) {
  12030. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12031. try {
  12032. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12033. if (res.ok) {
  12034. showToast('Deleted', 'AS list removed', 'info');
  12035. loadDynamicRouting();
  12036. } else {
  12037. const err = await res.json();
  12038. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12039. }
  12040. } catch (err) {
  12041. showToast('Error', err.message, 'error');
  12042. }
  12043. }
  12044. async function toggleASListState(id, disabled) {
  12045. try {
  12046. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12047. method: 'POST',
  12048. headers: { 'Content-Type': 'application/json' },
  12049. body: JSON.stringify({ disabled })
  12050. });
  12051. if (res.ok) {
  12052. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12053. loadDynamicRouting();
  12054. } else {
  12055. const err = await res.json();
  12056. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12057. }
  12058. } catch (err) {
  12059. showToast('Error', err.message, 'error');
  12060. }
  12061. }
  12062. // ==========================================
  12063. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12064. // ==========================================
  12065. function loadToolsView() {
  12066. populateToolsInterfaces();
  12067. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12068. }
  12069. function populateToolsInterfaces() {
  12070. const pingSel = document.getElementById('tools-ping-iface');
  12071. const traceSel = document.getElementById('tools-tr-iface');
  12072. let opts = '<option value="">Auto (Default Route)</option>';
  12073. if (Array.isArray(state.interfaces)) {
  12074. state.interfaces.forEach(iface => {
  12075. if (iface.name) {
  12076. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12077. }
  12078. });
  12079. }
  12080. if (pingSel) {
  12081. const cur = pingSel.value;
  12082. pingSel.innerHTML = opts;
  12083. if (cur) pingSel.value = cur;
  12084. }
  12085. if (traceSel) {
  12086. const cur = traceSel.value;
  12087. traceSel.innerHTML = opts;
  12088. if (cur) traceSel.value = cur;
  12089. }
  12090. }
  12091. function switchToolsSubTab(subTab) {
  12092. state.activeToolsSubTab = subTab;
  12093. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12094. tabs.forEach(t => {
  12095. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12096. const view = document.getElementById(`tools-view-${t}`);
  12097. if (btn) {
  12098. if (t === subTab) {
  12099. 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';
  12100. } else {
  12101. 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';
  12102. }
  12103. }
  12104. if (view) {
  12105. if (t === subTab) {
  12106. view.classList.remove('hidden');
  12107. } else {
  12108. view.classList.add('hidden');
  12109. }
  12110. }
  12111. });
  12112. }
  12113. function setPortPreset(port) {
  12114. const input = document.getElementById('tools-port-num');
  12115. if (input) input.value = port;
  12116. }
  12117. let pingAbortController = null;
  12118. let tracerouteAbortController = null;
  12119. function clearPingTable() {
  12120. const tbody = document.getElementById('tools-ping-tbody');
  12121. if (tbody) tbody.innerHTML = '';
  12122. const rawEl = document.getElementById('tools-ping-raw');
  12123. if (rawEl) rawEl.innerText = '';
  12124. const sentEl = document.getElementById('tools-ping-stat-sent');
  12125. if (sentEl) sentEl.innerText = '0';
  12126. const recvEl = document.getElementById('tools-ping-stat-recv');
  12127. if (recvEl) recvEl.innerText = '0';
  12128. const lossEl = document.getElementById('tools-ping-stat-loss');
  12129. if (lossEl) lossEl.innerText = '0%';
  12130. const avgEl = document.getElementById('tools-ping-stat-avg');
  12131. if (avgEl) avgEl.innerText = '0 ms';
  12132. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12133. if (minMaxEl) minMaxEl.innerText = '-';
  12134. const badge = document.getElementById('tools-ping-status-badge');
  12135. if (badge) {
  12136. badge.className = '';
  12137. badge.innerText = '';
  12138. }
  12139. }
  12140. function clearTracerouteTable() {
  12141. const tbody = document.getElementById('tools-tr-tbody');
  12142. if (tbody) tbody.innerHTML = '';
  12143. const rawEl = document.getElementById('tools-tr-raw');
  12144. if (rawEl) rawEl.innerText = '';
  12145. const statHops = document.getElementById('tools-tr-hops-count');
  12146. if (statHops) statHops.innerText = '0 Hops';
  12147. }
  12148. function resetPingButton() {
  12149. const btn = document.getElementById('tools-ping-btn');
  12150. const btnText = document.getElementById('tools-ping-btn-text');
  12151. const spinner = document.getElementById('tools-ping-spinner');
  12152. if (btn) {
  12153. btn.disabled = false;
  12154. 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';
  12155. }
  12156. if (btnText) btnText.innerText = 'Start Ping';
  12157. if (spinner) spinner.classList.add('hidden');
  12158. }
  12159. function setPingRunningButton() {
  12160. const btn = document.getElementById('tools-ping-btn');
  12161. const btnText = document.getElementById('tools-ping-btn-text');
  12162. const spinner = document.getElementById('tools-ping-spinner');
  12163. if (btn) {
  12164. btn.disabled = false;
  12165. 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';
  12166. }
  12167. if (btnText) btnText.innerText = 'Stop Ping';
  12168. if (spinner) spinner.classList.remove('hidden');
  12169. }
  12170. function resetTracerouteButton() {
  12171. const btn = document.getElementById('tools-tr-btn');
  12172. const btnText = document.getElementById('tools-tr-btn-text');
  12173. const spinner = document.getElementById('tools-tr-spinner');
  12174. if (btn) {
  12175. btn.disabled = false;
  12176. 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';
  12177. }
  12178. if (btnText) btnText.innerText = 'Start Traceroute';
  12179. if (spinner) spinner.classList.add('hidden');
  12180. }
  12181. function setTracerouteRunningButton() {
  12182. const btn = document.getElementById('tools-tr-btn');
  12183. const btnText = document.getElementById('tools-tr-btn-text');
  12184. const spinner = document.getElementById('tools-tr-spinner');
  12185. if (btn) {
  12186. btn.disabled = false;
  12187. 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';
  12188. }
  12189. if (btnText) btnText.innerText = 'Stop Traceroute';
  12190. if (spinner) spinner.classList.remove('hidden');
  12191. }
  12192. async function executePing(e) {
  12193. if (e) e.preventDefault();
  12194. // If already running, clicking the button stops the stream!
  12195. if (pingAbortController) {
  12196. pingAbortController.abort();
  12197. pingAbortController = null;
  12198. resetPingButton();
  12199. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12200. return;
  12201. }
  12202. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12203. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12204. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12205. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12206. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12207. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12208. if (!target) {
  12209. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12210. return;
  12211. }
  12212. clearPingTable();
  12213. const resCard = document.getElementById('tools-ping-results');
  12214. if (resCard) resCard.classList.remove('hidden');
  12215. pingAbortController = new AbortController();
  12216. setPingRunningButton();
  12217. try {
  12218. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12219. method: 'POST',
  12220. headers: { 'Content-Type': 'application/json' },
  12221. body: JSON.stringify({
  12222. target,
  12223. count,
  12224. size,
  12225. timeout,
  12226. interface: iface,
  12227. dont_frag: dontFrag
  12228. }),
  12229. signal: pingAbortController.signal
  12230. });
  12231. if (!res.ok) {
  12232. const errText = await res.text();
  12233. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12234. resetPingButton();
  12235. pingAbortController = null;
  12236. return;
  12237. }
  12238. const reader = res.body.getReader();
  12239. const decoder = new TextDecoder('utf-8');
  12240. let buffer = '';
  12241. while (true) {
  12242. const { done, value } = await reader.read();
  12243. if (done) break;
  12244. buffer += decoder.decode(value, { stream: true });
  12245. const blocks = buffer.split('\n\n');
  12246. buffer = blocks.pop() || '';
  12247. for (const block of blocks) {
  12248. const trimmed = block.trim();
  12249. if (!trimmed) continue;
  12250. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12251. try {
  12252. const evt = JSON.parse(line);
  12253. handleLivePingEvent(evt);
  12254. } catch (parseErr) {
  12255. console.warn('Ping SSE parse error:', parseErr, line);
  12256. }
  12257. }
  12258. }
  12259. } catch (err) {
  12260. if (err.name === 'AbortError') {
  12261. // User aborted normally
  12262. } else {
  12263. showToast('Ping Error', err.message, 'error');
  12264. }
  12265. } finally {
  12266. pingAbortController = null;
  12267. resetPingButton();
  12268. }
  12269. }
  12270. function handleLivePingEvent(evt) {
  12271. const sentEl = document.getElementById('tools-ping-stat-sent');
  12272. const recvEl = document.getElementById('tools-ping-stat-recv');
  12273. const lossEl = document.getElementById('tools-ping-stat-loss');
  12274. const avgEl = document.getElementById('tools-ping-stat-avg');
  12275. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12276. const badge = document.getElementById('tools-ping-status-badge');
  12277. const tbody = document.getElementById('tools-ping-tbody');
  12278. const rawEl = document.getElementById('tools-ping-raw');
  12279. if (evt.raw && rawEl) {
  12280. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12281. rawEl.scrollTop = rawEl.scrollHeight;
  12282. }
  12283. if (evt.type === 'reply') {
  12284. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12285. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12286. if (lossEl && evt.packet_loss_pct !== undefined) {
  12287. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12288. lossEl.className = evt.packet_loss_pct === 0
  12289. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12290. : (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');
  12291. }
  12292. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12293. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12294. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12295. }
  12296. if (badge) {
  12297. if (evt.packet_loss_pct === 0) {
  12298. 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';
  12299. badge.innerText = '100% OK';
  12300. } else {
  12301. 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';
  12302. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12303. }
  12304. }
  12305. if (tbody) {
  12306. const tr = document.createElement('tr');
  12307. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12308. tr.innerHTML = `
  12309. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12310. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12311. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12312. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12313. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12314. <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>
  12315. `;
  12316. tbody.appendChild(tr);
  12317. }
  12318. } else if (evt.type === 'timeout') {
  12319. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12320. if (lossEl && evt.packet_loss_pct !== undefined) {
  12321. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12322. 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';
  12323. }
  12324. if (badge) {
  12325. 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';
  12326. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12327. }
  12328. if (tbody) {
  12329. const tr = document.createElement('tr');
  12330. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12331. tr.innerHTML = `
  12332. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12333. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12334. <td class="py-2 px-3 text-slate-600">--</td>
  12335. <td class="py-2 px-3 text-slate-600">--</td>
  12336. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12337. <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>
  12338. `;
  12339. tbody.appendChild(tr);
  12340. }
  12341. } else if (evt.type === 'unreach') {
  12342. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12343. if (lossEl && evt.packet_loss_pct !== undefined) {
  12344. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12345. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12346. }
  12347. if (badge) {
  12348. 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';
  12349. badge.innerText = 'UNREACHABLE';
  12350. }
  12351. if (tbody) {
  12352. const tr = document.createElement('tr');
  12353. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12354. tr.innerHTML = `
  12355. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12356. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12357. <td class="py-2 px-3 text-slate-600">--</td>
  12358. <td class="py-2 px-3 text-slate-600">--</td>
  12359. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12360. <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>
  12361. `;
  12362. tbody.appendChild(tr);
  12363. }
  12364. } else if (evt.type === 'stats') {
  12365. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12366. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12367. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12368. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12369. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12370. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12371. }
  12372. } else if (evt.type === 'done') {
  12373. 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');
  12374. }
  12375. }
  12376. async function executeTraceroute(e) {
  12377. if (e) e.preventDefault();
  12378. if (tracerouteAbortController) {
  12379. tracerouteAbortController.abort();
  12380. tracerouteAbortController = null;
  12381. resetTracerouteButton();
  12382. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12383. return;
  12384. }
  12385. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12386. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12387. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12388. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12389. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12390. if (!target) {
  12391. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12392. return;
  12393. }
  12394. clearTracerouteTable();
  12395. const resCard = document.getElementById('tools-tr-results');
  12396. if (resCard) resCard.classList.remove('hidden');
  12397. tracerouteAbortController = new AbortController();
  12398. setTracerouteRunningButton();
  12399. try {
  12400. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12401. method: 'POST',
  12402. headers: { 'Content-Type': 'application/json' },
  12403. body: JSON.stringify({
  12404. target,
  12405. max_hops: maxHops,
  12406. protocol,
  12407. interface: iface,
  12408. resolve
  12409. }),
  12410. signal: tracerouteAbortController.signal
  12411. });
  12412. if (!res.ok) {
  12413. const errText = await res.text();
  12414. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12415. resetTracerouteButton();
  12416. tracerouteAbortController = null;
  12417. return;
  12418. }
  12419. const reader = res.body.getReader();
  12420. const decoder = new TextDecoder('utf-8');
  12421. let buffer = '';
  12422. while (true) {
  12423. const { done, value } = await reader.read();
  12424. if (done) break;
  12425. buffer += decoder.decode(value, { stream: true });
  12426. const blocks = buffer.split('\n\n');
  12427. buffer = blocks.pop() || '';
  12428. for (const block of blocks) {
  12429. const trimmed = block.trim();
  12430. if (!trimmed) continue;
  12431. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12432. try {
  12433. const evt = JSON.parse(line);
  12434. handleLiveTracerouteEvent(evt);
  12435. } catch (parseErr) {
  12436. console.warn('Traceroute SSE parse error:', parseErr, line);
  12437. }
  12438. }
  12439. }
  12440. } catch (err) {
  12441. if (err.name === 'AbortError') {
  12442. // User aborted normally
  12443. } else {
  12444. showToast('Traceroute Error', err.message, 'error');
  12445. }
  12446. } finally {
  12447. tracerouteAbortController = null;
  12448. resetTracerouteButton();
  12449. }
  12450. }
  12451. function handleLiveTracerouteEvent(evt) {
  12452. const statHops = document.getElementById('tools-tr-hops-count');
  12453. const tbody = document.getElementById('tools-tr-tbody');
  12454. const rawEl = document.getElementById('tools-tr-raw');
  12455. if (evt.raw && rawEl) {
  12456. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12457. rawEl.scrollTop = rawEl.scrollHeight;
  12458. }
  12459. if (evt.hops_count !== undefined && statHops) {
  12460. statHops.innerText = `${evt.hops_count} Hops`;
  12461. }
  12462. if (evt.type === 'hop' && evt.hop && tbody) {
  12463. const h = evt.hop;
  12464. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12465. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12466. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12467. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12468. const tr = document.createElement('tr');
  12469. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12470. tr.innerHTML = `
  12471. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12472. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12473. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12474. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12475. <td class="py-2.5 px-3 text-right">
  12476. ${isTimeout
  12477. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12478. : '<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>'}
  12479. </td>
  12480. `;
  12481. tbody.appendChild(tr);
  12482. } else if (evt.type === 'done') {
  12483. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12484. }
  12485. }
  12486. async function executeMTR(e) {
  12487. if (e) e.preventDefault();
  12488. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12489. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12490. if (!target) {
  12491. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12492. return;
  12493. }
  12494. const btn = document.getElementById('tools-mtr-btn');
  12495. const spinner = document.getElementById('tools-mtr-spinner');
  12496. if (btn) btn.disabled = true;
  12497. if (spinner) spinner.classList.remove('hidden');
  12498. try {
  12499. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12500. method: 'POST',
  12501. headers: { 'Content-Type': 'application/json' },
  12502. body: JSON.stringify({ target, count: cycles })
  12503. });
  12504. const data = await res.json();
  12505. if (!res.ok) {
  12506. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12507. return;
  12508. }
  12509. const resCard = document.getElementById('tools-mtr-results');
  12510. if (resCard) resCard.classList.remove('hidden');
  12511. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12512. const statHops = document.getElementById('tools-mtr-hops-count');
  12513. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12514. const tbody = document.getElementById('tools-mtr-tbody');
  12515. if (tbody) {
  12516. if (hopsCount > 0) {
  12517. tbody.innerHTML = data.hops.map(h => {
  12518. 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');
  12519. return `
  12520. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12521. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12522. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12523. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12524. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12525. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12526. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12527. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12528. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12529. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12530. </tr>
  12531. `;
  12532. }).join('');
  12533. } else {
  12534. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12535. }
  12536. }
  12537. const rawEl = document.getElementById('tools-mtr-raw');
  12538. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12539. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12540. } catch (err) {
  12541. showToast('MTR Error', err.message, 'error');
  12542. } finally {
  12543. if (btn) btn.disabled = false;
  12544. if (spinner) spinner.classList.add('hidden');
  12545. }
  12546. }
  12547. async function executeDNS(e) {
  12548. if (e) e.preventDefault();
  12549. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12550. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12551. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12552. if (!domain) {
  12553. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12554. return;
  12555. }
  12556. const btn = document.getElementById('tools-dns-btn');
  12557. const spinner = document.getElementById('tools-dns-spinner');
  12558. if (btn) btn.disabled = true;
  12559. if (spinner) spinner.classList.remove('hidden');
  12560. try {
  12561. const res = await fetch(`${API_BASE}/tools/dns`, {
  12562. method: 'POST',
  12563. headers: { 'Content-Type': 'application/json' },
  12564. body: JSON.stringify({ domain, type, server })
  12565. });
  12566. const data = await res.json();
  12567. if (!res.ok) {
  12568. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12569. return;
  12570. }
  12571. const resCard = document.getElementById('tools-dns-results');
  12572. if (resCard) resCard.classList.remove('hidden');
  12573. const metaEl = document.getElementById('tools-dns-meta');
  12574. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12575. const tbody = document.getElementById('tools-dns-tbody');
  12576. if (tbody) {
  12577. if (Array.isArray(data.records) && data.records.length > 0) {
  12578. tbody.innerHTML = data.records.map(r => `
  12579. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12580. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12581. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12582. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12583. <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>
  12584. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12585. </tr>
  12586. `).join('');
  12587. } else {
  12588. 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>`;
  12589. }
  12590. }
  12591. const rawEl = document.getElementById('tools-dns-raw');
  12592. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12593. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12594. } catch (err) {
  12595. showToast('DNS Error', err.message, 'error');
  12596. } finally {
  12597. if (btn) btn.disabled = false;
  12598. if (spinner) spinner.classList.add('hidden');
  12599. }
  12600. }
  12601. async function executePortProbe(e) {
  12602. if (e) e.preventDefault();
  12603. const target = document.getElementById('tools-port-target')?.value?.trim();
  12604. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12605. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12606. if (!target || !port) {
  12607. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12608. return;
  12609. }
  12610. const btn = document.getElementById('tools-port-btn');
  12611. const spinner = document.getElementById('tools-port-spinner');
  12612. if (btn) btn.disabled = true;
  12613. if (spinner) spinner.classList.remove('hidden');
  12614. try {
  12615. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12616. method: 'POST',
  12617. headers: { 'Content-Type': 'application/json' },
  12618. body: JSON.stringify({ target, port, timeout })
  12619. });
  12620. const data = await res.json();
  12621. if (!res.ok) {
  12622. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12623. return;
  12624. }
  12625. const resCard = document.getElementById('tools-port-results');
  12626. if (resCard) resCard.classList.remove('hidden');
  12627. const banner = document.getElementById('tools-port-banner');
  12628. const icon = document.getElementById('tools-port-icon');
  12629. const title = document.getElementById('tools-port-title');
  12630. const sub = document.getElementById('tools-port-sub');
  12631. const latency = document.getElementById('tools-port-latency');
  12632. if (data.open) {
  12633. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12634. if (icon) {
  12635. 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';
  12636. icon.innerText = '✓';
  12637. }
  12638. if (title) {
  12639. title.className = 'text-sm font-bold text-emerald-300';
  12640. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12641. }
  12642. if (sub) {
  12643. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12644. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12645. }
  12646. if (latency) {
  12647. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12648. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12649. }
  12650. } else {
  12651. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12652. if (icon) {
  12653. 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';
  12654. icon.innerText = '✕';
  12655. }
  12656. if (title) {
  12657. title.className = 'text-sm font-bold text-rose-300';
  12658. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12659. }
  12660. if (sub) {
  12661. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12662. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12663. }
  12664. if (latency) {
  12665. latency.className = 'text-base font-bold font-mono text-slate-500';
  12666. latency.innerText = '--';
  12667. }
  12668. }
  12669. const rawEl = document.getElementById('tools-port-raw');
  12670. 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'}`);
  12671. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12672. } catch (err) {
  12673. showToast('Probe Error', err.message, 'error');
  12674. } finally {
  12675. if (btn) btn.disabled = false;
  12676. if (spinner) spinner.classList.add('hidden');
  12677. }
  12678. }
  12679. // ==========================================
  12680. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12681. // ==========================================
  12682. async function loadDHCPClients(showToastMsg = false) {
  12683. try {
  12684. const [clientsRes, sumRes] = await Promise.all([
  12685. fetch(`${API_BASE}/dhcp/clients`),
  12686. fetch(`${API_BASE}/dhcp/clients/summary`)
  12687. ]);
  12688. if (clientsRes.ok) {
  12689. state.dhcpClients = await clientsRes.json();
  12690. }
  12691. if (sumRes.ok) {
  12692. state.dhcpSummary = await sumRes.json();
  12693. }
  12694. renderDHCPClients();
  12695. updateDHCPSummaryCards();
  12696. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12697. if (bDhcp && state.dhcpSummary) {
  12698. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12699. }
  12700. if (showToastMsg) {
  12701. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12702. }
  12703. } catch (err) {
  12704. console.error('Failed to load DHCP clients:', err);
  12705. if (showToastMsg) {
  12706. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12707. }
  12708. }
  12709. }
  12710. function updateDHCPSummaryCards() {
  12711. const sum = state.dhcpSummary || {
  12712. total_clients: (state.dhcpClients || []).length,
  12713. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12714. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12715. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12716. };
  12717. const totalEl = document.getElementById('dhcp-stat-total');
  12718. const boundEl = document.getElementById('dhcp-stat-bound');
  12719. const searchEl = document.getElementById('dhcp-stat-searching');
  12720. const disEl = document.getElementById('dhcp-stat-disabled');
  12721. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12722. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12723. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12724. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12725. }
  12726. function renderDHCPClients() {
  12727. const tbody = document.getElementById('dhcp-clients-tbody');
  12728. const emptyState = document.getElementById('dhcp-clients-empty');
  12729. if (!tbody) return;
  12730. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12731. if (clients.length === 0) {
  12732. tbody.innerHTML = '';
  12733. if (emptyState) emptyState.classList.remove('hidden');
  12734. return;
  12735. }
  12736. if (emptyState) emptyState.classList.add('hidden');
  12737. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12738. if (tbody.dataset.sig === sig) return;
  12739. tbody.dataset.sig = sig;
  12740. tbody.innerHTML = clients.map(c => {
  12741. let statusBadge = '';
  12742. if (!c.enabled) {
  12743. 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>';
  12744. } else if (c.status === 'bound') {
  12745. 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>';
  12746. } else if (c.status === 'searching') {
  12747. 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>';
  12748. } else if (c.status === 'stopped') {
  12749. 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>';
  12750. } else {
  12751. 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>`;
  12752. }
  12753. 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>';
  12754. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12755. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12756. 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>';
  12757. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12758. // Option flags
  12759. const flags = [];
  12760. 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>');
  12761. 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>');
  12762. 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>');
  12763. 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>`);
  12764. return `
  12765. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12766. <td class="py-3 px-4">
  12767. <div class="flex items-center gap-2">
  12768. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12769. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12770. </div>
  12771. </td>
  12772. <td class="py-3 px-4">${statusBadge}</td>
  12773. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12774. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12775. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12776. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12777. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12778. <td class="py-3 px-4">
  12779. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12780. </td>
  12781. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12782. ${c.enabled ? `
  12783. <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>
  12784. <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>
  12785. <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>
  12786. ` : `
  12787. <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>
  12788. `}
  12789. <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>
  12790. <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>
  12791. </td>
  12792. </tr>
  12793. `;
  12794. }).join('');
  12795. }
  12796. function openDHCPClientModal(clientId = null) {
  12797. const modal = document.getElementById('modal-dhcp-client');
  12798. if (!modal) return;
  12799. const title = document.getElementById('modal-dhcp-title');
  12800. const idInput = document.getElementById('modal-dhcp-id');
  12801. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12802. const distInput = document.getElementById('modal-dhcp-distance');
  12803. const commentInput = document.getElementById('modal-dhcp-comment');
  12804. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12805. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12806. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12807. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12808. // Populate interfaces
  12809. if (ifaceSelect) {
  12810. let opts = '<option value="">Select interface...</option>';
  12811. const allIfaces = state.interfaces || [];
  12812. const allVlans = state.vlans || [];
  12813. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12814. // Group 1: Physical & Bridge Interfaces
  12815. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12816. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12817. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12818. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12819. });
  12820. opts += '</optgroup>';
  12821. // Group 2: VLAN Interfaces
  12822. if (allVlans.length > 0) {
  12823. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12824. allVlans.forEach(v => {
  12825. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12826. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12827. });
  12828. opts += '</optgroup>';
  12829. }
  12830. ifaceSelect.innerHTML = opts;
  12831. }
  12832. if (clientId) {
  12833. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12834. if (client) {
  12835. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12836. if (idInput) idInput.value = client.id;
  12837. if (ifaceSelect) {
  12838. ifaceSelect.value = client.interface;
  12839. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12840. }
  12841. if (distInput) distInput.value = client.default_route_distance || 1;
  12842. if (commentInput) commentInput.value = client.comment || '';
  12843. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12844. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12845. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12846. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12847. }
  12848. } else {
  12849. if (title) title.innerText = 'Add DHCP Client';
  12850. if (idInput) idInput.value = '';
  12851. if (ifaceSelect) {
  12852. ifaceSelect.value = '';
  12853. ifaceSelect.disabled = false;
  12854. }
  12855. if (distInput) distInput.value = 1;
  12856. if (commentInput) commentInput.value = '';
  12857. if (defRouteCheck) defRouteCheck.checked = true;
  12858. if (peerDnsCheck) peerDnsCheck.checked = true;
  12859. if (peerNtpCheck) peerNtpCheck.checked = true;
  12860. if (enabledCheck) enabledCheck.checked = true;
  12861. }
  12862. modal.classList.remove('hidden');
  12863. }
  12864. function openDHCPClientModalForIface(ifaceName) {
  12865. openDHCPClientModal();
  12866. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12867. if (ifaceSelect && ifaceName) {
  12868. ifaceSelect.value = ifaceName;
  12869. }
  12870. }
  12871. function closeDHCPClientModal() {
  12872. const modal = document.getElementById('modal-dhcp-client');
  12873. if (modal) modal.classList.add('hidden');
  12874. }
  12875. async function submitSaveDHCPClient(e) {
  12876. if (e) e.preventDefault();
  12877. const id = document.getElementById('modal-dhcp-id')?.value;
  12878. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12879. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12880. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12881. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12882. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12883. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12884. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12885. if (!id && !iface) {
  12886. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12887. return;
  12888. }
  12889. try {
  12890. let res;
  12891. if (id) {
  12892. // PUT update
  12893. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12894. method: 'PUT',
  12895. headers: { 'Content-Type': 'application/json' },
  12896. body: JSON.stringify({
  12897. enabled,
  12898. add_default_route: defRoute,
  12899. default_route_distance: distance,
  12900. use_peer_dns: peerDns,
  12901. use_peer_ntp: peerNtp,
  12902. comment
  12903. })
  12904. });
  12905. } else {
  12906. // POST create
  12907. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12908. method: 'POST',
  12909. headers: { 'Content-Type': 'application/json' },
  12910. body: JSON.stringify({
  12911. interface: iface,
  12912. enabled,
  12913. add_default_route: defRoute,
  12914. default_route_distance: distance,
  12915. use_peer_dns: peerDns,
  12916. use_peer_ntp: peerNtp,
  12917. comment
  12918. })
  12919. });
  12920. }
  12921. const data = await res.json();
  12922. if (!res.ok) {
  12923. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12924. return;
  12925. }
  12926. closeDHCPClientModal();
  12927. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12928. await loadDHCPClients();
  12929. fetchData(); // refresh interfaces list with new lease/status
  12930. } catch (err) {
  12931. showToast('Error', err.message, 'error');
  12932. }
  12933. }
  12934. async function toggleDHCPClientState(id, enabled) {
  12935. try {
  12936. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12937. method: 'POST',
  12938. headers: { 'Content-Type': 'application/json' },
  12939. body: JSON.stringify({ enabled })
  12940. });
  12941. const data = await res.json();
  12942. if (!res.ok) {
  12943. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12944. return;
  12945. }
  12946. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12947. await loadDHCPClients();
  12948. fetchData();
  12949. } catch (err) {
  12950. showToast('Error', err.message, 'error');
  12951. }
  12952. }
  12953. async function renewDHCPClient(id) {
  12954. try {
  12955. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12956. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12957. method: 'POST'
  12958. });
  12959. const data = await res.json();
  12960. if (!res.ok) {
  12961. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12962. return;
  12963. }
  12964. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12965. setTimeout(() => {
  12966. loadDHCPClients();
  12967. fetchData();
  12968. }, 1500);
  12969. } catch (err) {
  12970. showToast('Error', err.message, 'error');
  12971. }
  12972. }
  12973. async function releaseDHCPClient(id) {
  12974. try {
  12975. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12976. method: 'POST'
  12977. });
  12978. const data = await res.json();
  12979. if (!res.ok) {
  12980. showToast('Error', data.error || 'Failed to release lease', 'error');
  12981. return;
  12982. }
  12983. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12984. await loadDHCPClients();
  12985. fetchData();
  12986. } catch (err) {
  12987. showToast('Error', err.message, 'error');
  12988. }
  12989. }
  12990. async function deleteDHCPClient(id, ifaceName) {
  12991. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12992. return;
  12993. }
  12994. try {
  12995. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12996. method: 'DELETE'
  12997. });
  12998. const data = await res.json();
  12999. if (!res.ok) {
  13000. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13001. return;
  13002. }
  13003. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13004. await loadDHCPClients();
  13005. fetchData();
  13006. } catch (err) {
  13007. showToast('Error', err.message, 'error');
  13008. }
  13009. }
  13010. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13011. async function loadDHCPServer(populate = true) {
  13012. try {
  13013. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13014. fetch(`${API_BASE}/dhcp-server/summary`),
  13015. fetch(`${API_BASE}/dhcp-server/servers`),
  13016. fetch(`${API_BASE}/dhcp-server/networks`),
  13017. fetch(`${API_BASE}/dhcp-server/leases`),
  13018. fetch(`${API_BASE}/dhcp-server/options`)
  13019. ]);
  13020. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13021. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13022. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13023. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13024. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13025. const sum = state.dhcpServerSummary || {};
  13026. const srvs = state.dhcpServers || [];
  13027. const nets = state.dhcpNetworks || [];
  13028. const leases = state.dhcpLeases || [];
  13029. const opts = state.dhcpOptions || [];
  13030. // KPI Cards
  13031. const statActive = document.getElementById('dhcp-server-stat-active');
  13032. if (statActive) {
  13033. const activeCount = srvs.filter(s => s.running).length;
  13034. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13035. }
  13036. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13037. if (statLeases) {
  13038. statLeases.innerText = leases.length;
  13039. }
  13040. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13041. if (statLeasesSub) {
  13042. const dyn = leases.filter(l => l.dynamic).length;
  13043. const st = leases.filter(l => !l.dynamic).length;
  13044. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13045. }
  13046. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13047. if (statNetworks) {
  13048. statNetworks.innerText = nets.length;
  13049. }
  13050. // Subtab Badges
  13051. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13052. if (bSrv) bSrv.innerText = srvs.length;
  13053. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13054. if (bNet) bNet.innerText = nets.length;
  13055. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13056. if (bLease) bLease.innerText = leases.length;
  13057. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13058. if (bOpt) bOpt.innerText = opts.length;
  13059. // Sidebar Badge
  13060. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13061. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13062. renderCurrentDHCPServerTab();
  13063. } catch (err) {
  13064. console.error('Failed to load DHCP Server:', err);
  13065. }
  13066. }
  13067. function switchDHCPServerTab(tab) {
  13068. state.dhcpServerTab = tab;
  13069. const tabs = ['servers', 'networks', 'leases', 'options'];
  13070. tabs.forEach(t => {
  13071. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13072. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13073. if (panel) {
  13074. if (t === tab) panel.classList.remove('hidden');
  13075. else panel.classList.add('hidden');
  13076. }
  13077. if (btn) {
  13078. if (t === tab) {
  13079. 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';
  13080. } else {
  13081. 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';
  13082. }
  13083. }
  13084. });
  13085. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13086. if (addBtn) {
  13087. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13088. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13089. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13090. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13091. }
  13092. renderCurrentDHCPServerTab();
  13093. }
  13094. function handleDHCPServerPrimaryAdd() {
  13095. const tab = state.dhcpServerTab || 'servers';
  13096. if (tab === 'servers') openAddDHCPServerModal();
  13097. else if (tab === 'networks') openAddDHCPNetworkModal();
  13098. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13099. else if (tab === 'options') openAddDHCPOptionModal();
  13100. }
  13101. function renderCurrentDHCPServerTab() {
  13102. const tab = state.dhcpServerTab || 'servers';
  13103. if (tab === 'servers') renderDHCPServers();
  13104. else if (tab === 'networks') renderDHCPNetworks();
  13105. else if (tab === 'leases') renderDHCPLeases();
  13106. else if (tab === 'options') renderDHCPOptions();
  13107. }
  13108. function renderDHCPServers() {
  13109. const tbody = document.getElementById('dhcp-server-tbody');
  13110. const empty = document.getElementById('dhcp-server-empty');
  13111. if (!tbody) return;
  13112. const servers = state.dhcpServers || [];
  13113. if (servers.length === 0) {
  13114. tbody.innerHTML = '';
  13115. empty?.classList.remove('hidden');
  13116. return;
  13117. }
  13118. empty?.classList.add('hidden');
  13119. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13120. if (tbody.dataset.sig === sig) return;
  13121. tbody.dataset.sig = sig;
  13122. tbody.innerHTML = '';
  13123. servers.forEach(s => {
  13124. const tr = document.createElement('tr');
  13125. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13126. tr.innerHTML = `
  13127. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13128. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13129. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13130. <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>
  13131. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13132. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13133. <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>
  13134. <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>
  13135. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13136. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13137. <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>
  13138. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13139. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13140. </td>
  13141. `;
  13142. tbody.appendChild(tr);
  13143. });
  13144. }
  13145. function renderDHCPNetworks() {
  13146. const tbody = document.getElementById('dhcp-networks-tbody');
  13147. const empty = document.getElementById('dhcp-networks-empty');
  13148. if (!tbody) return;
  13149. tbody.innerHTML = '';
  13150. const networks = state.dhcpNetworks || [];
  13151. if (networks.length === 0) {
  13152. empty?.classList.remove('hidden');
  13153. return;
  13154. }
  13155. empty?.classList.add('hidden');
  13156. networks.forEach(n => {
  13157. const tr = document.createElement('tr');
  13158. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13159. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13160. const optionsChips = (n.dhcp_options || []).map(optId => {
  13161. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13162. if (!opt) return '';
  13163. 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>`;
  13164. }).filter(Boolean).join('');
  13165. tr.innerHTML = `
  13166. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13167. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13168. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13169. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13170. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13171. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13172. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13173. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13174. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13175. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13176. </td>
  13177. `;
  13178. tbody.appendChild(tr);
  13179. });
  13180. }
  13181. function renderDHCPLeases() {
  13182. const tbody = document.getElementById('dhcp-leases-tbody');
  13183. const empty = document.getElementById('dhcp-leases-empty');
  13184. if (!tbody) return;
  13185. tbody.innerHTML = '';
  13186. const leases = state.dhcpLeases || [];
  13187. if (leases.length === 0) {
  13188. empty?.classList.remove('hidden');
  13189. return;
  13190. }
  13191. empty?.classList.add('hidden');
  13192. leases.forEach(l => {
  13193. const tr = document.createElement('tr');
  13194. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13195. 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>';
  13196. const statusBadge = l.status === 'bound'
  13197. ? '<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>'
  13198. : l.status === 'static'
  13199. ? '<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>'
  13200. : '<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>';
  13201. const makeStaticBtn = l.dynamic
  13202. ? `<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>`
  13203. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13204. tr.innerHTML = `
  13205. <td class="py-2.5 px-3 text-center">${flag}</td>
  13206. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13207. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13208. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13209. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13210. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13211. <td class="py-2.5 px-3">${statusBadge}</td>
  13212. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13213. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13214. ${makeStaticBtn}
  13215. </td>
  13216. `;
  13217. tbody.appendChild(tr);
  13218. });
  13219. }
  13220. function renderDHCPOptions() {
  13221. const tbody = document.getElementById('dhcp-options-tbody');
  13222. const empty = document.getElementById('dhcp-options-empty');
  13223. if (!tbody) return;
  13224. tbody.innerHTML = '';
  13225. const options = state.dhcpOptions || [];
  13226. if (options.length === 0) {
  13227. empty?.classList.remove('hidden');
  13228. return;
  13229. }
  13230. empty?.classList.add('hidden');
  13231. options.forEach(o => {
  13232. const tr = document.createElement('tr');
  13233. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13234. tr.innerHTML = `
  13235. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13236. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13237. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13238. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13239. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13240. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13241. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13242. </td>
  13243. `;
  13244. tbody.appendChild(tr);
  13245. });
  13246. }
  13247. // ==================== MODALS & ACTIONS: SERVER ====================
  13248. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13249. const sel = document.getElementById(elemId);
  13250. if (!sel) return;
  13251. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13252. const networks = state.dhcpNetworks || [];
  13253. networks.forEach(n => {
  13254. const opt = document.createElement('option');
  13255. opt.value = n.address;
  13256. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13257. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13258. opt.selected = true;
  13259. }
  13260. sel.appendChild(opt);
  13261. });
  13262. }
  13263. function onDHCPServerNetworkChange() {
  13264. const netSel = document.getElementById('dhcp-server-modal-network');
  13265. if (!netSel) return;
  13266. const netVal = netSel.value;
  13267. if (!netVal) return;
  13268. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13269. if (!poolInput) return;
  13270. // Auto-calculate suggested address pool based on subnet CIDR
  13271. const parts = netVal.split('/');
  13272. const ip = parts[0];
  13273. const cidr = parseInt(parts[1] || '24', 10);
  13274. if (cidr === 24) {
  13275. const octets = ip.split('.');
  13276. if (octets.length === 4) {
  13277. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13278. poolInput.value = `${base}.10-${base}.254`;
  13279. }
  13280. }
  13281. }
  13282. function openAddDHCPServerModal() {
  13283. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13284. document.getElementById('dhcp-server-modal-id').value = '';
  13285. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13286. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13287. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13288. document.getElementById('dhcp-server-modal-comment').value = '';
  13289. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13290. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13291. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13292. const networks = state.dhcpNetworks || [];
  13293. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13294. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13295. if (defaultNet) {
  13296. onDHCPServerNetworkChange();
  13297. }
  13298. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13299. }
  13300. function openEditDHCPServerModal(id) {
  13301. const s = (state.dhcpServers || []).find(item => item.id === id);
  13302. if (!s) return;
  13303. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13304. document.getElementById('dhcp-server-modal-id').value = s.id;
  13305. document.getElementById('dhcp-server-modal-name').value = s.name;
  13306. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13307. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13308. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13309. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13310. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13311. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13312. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13313. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13314. }
  13315. function closeDHCPServerModal() {
  13316. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13317. }
  13318. async function submitSaveDHCPServer(e) {
  13319. e.preventDefault();
  13320. const id = document.getElementById('dhcp-server-modal-id').value;
  13321. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13322. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13323. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13324. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13325. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13326. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13327. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13328. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13329. try {
  13330. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13331. method: 'POST',
  13332. headers: { 'Content-Type': 'application/json' },
  13333. body: JSON.stringify({
  13334. id,
  13335. name,
  13336. interface: iface,
  13337. network,
  13338. address_pool: pool,
  13339. lease_time: leaseTime,
  13340. authoritative,
  13341. disabled,
  13342. comment
  13343. })
  13344. });
  13345. if (res.ok) {
  13346. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13347. closeDHCPServerModal();
  13348. loadDHCPServer(false);
  13349. fetchData(false);
  13350. } else {
  13351. const err = await res.text();
  13352. showToast('Error', err, 'error');
  13353. }
  13354. } catch (err) {
  13355. showToast('Error', err.message, 'error');
  13356. }
  13357. }
  13358. async function toggleDHCPServerState(id, disabled) {
  13359. try {
  13360. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13361. method: 'POST',
  13362. headers: { 'Content-Type': 'application/json' },
  13363. body: JSON.stringify({ disabled })
  13364. });
  13365. if (res.ok) {
  13366. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13367. loadDHCPServer(false);
  13368. fetchData(false);
  13369. }
  13370. } catch (err) {
  13371. showToast('Error', err.message, 'error');
  13372. }
  13373. }
  13374. async function deleteDHCPServer(id, name) {
  13375. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13376. try {
  13377. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13378. if (res.ok) {
  13379. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13380. loadDHCPServer(false);
  13381. fetchData(false);
  13382. }
  13383. } catch (err) {
  13384. showToast('Error', err.message, 'error');
  13385. }
  13386. }
  13387. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13388. function openAddDHCPNetworkModal() {
  13389. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13390. document.getElementById('dhcp-network-modal-id').value = '';
  13391. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13392. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13393. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13394. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13395. document.getElementById('dhcp-network-modal-netmask').value = '';
  13396. document.getElementById('dhcp-network-modal-comment').value = '';
  13397. renderDHCPNetworkOptionsCheckboxes([]);
  13398. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13399. }
  13400. function openEditDHCPNetworkModal(id) {
  13401. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13402. if (!n) return;
  13403. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13404. document.getElementById('dhcp-network-modal-id').value = n.id;
  13405. document.getElementById('dhcp-network-modal-address').value = n.address;
  13406. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13407. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13408. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13409. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13410. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13411. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13412. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13413. }
  13414. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13415. const container = document.getElementById('dhcp-network-modal-options-list');
  13416. if (!container) return;
  13417. container.innerHTML = '';
  13418. const opts = state.dhcpOptions || [];
  13419. if (opts.length === 0) {
  13420. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13421. return;
  13422. }
  13423. opts.forEach(o => {
  13424. const isChecked = selectedIds.includes(o.id);
  13425. const label = document.createElement('label');
  13426. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13427. label.innerHTML = `
  13428. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13429. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13430. `;
  13431. container.appendChild(label);
  13432. });
  13433. }
  13434. function closeDHCPNetworkModal() {
  13435. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13436. }
  13437. async function submitSaveDHCPNetwork(e) {
  13438. e.preventDefault();
  13439. const id = document.getElementById('dhcp-network-modal-id').value;
  13440. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13441. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13442. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13443. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13444. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13445. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13446. const selectedOpts = [];
  13447. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13448. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13449. try {
  13450. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13451. method: 'POST',
  13452. headers: { 'Content-Type': 'application/json' },
  13453. body: JSON.stringify({
  13454. id,
  13455. address,
  13456. gateway,
  13457. netmask,
  13458. dns_servers: dnsServers,
  13459. domain,
  13460. dhcp_options: selectedOpts,
  13461. comment
  13462. })
  13463. });
  13464. if (res.ok) {
  13465. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13466. closeDHCPNetworkModal();
  13467. loadDHCPServer(false);
  13468. fetchData(false);
  13469. } else {
  13470. const err = await res.text();
  13471. showToast('Error', err, 'error');
  13472. }
  13473. } catch (err) {
  13474. showToast('Error', err.message, 'error');
  13475. }
  13476. }
  13477. async function deleteDHCPNetwork(id, addr) {
  13478. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13479. try {
  13480. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13481. if (res.ok) {
  13482. showToast('Deleted', `Network ${addr} removed`, 'success');
  13483. loadDHCPServer(false);
  13484. fetchData(false);
  13485. }
  13486. } catch (err) {
  13487. showToast('Error', err.message, 'error');
  13488. }
  13489. }
  13490. // ==================== MODALS & ACTIONS: LEASES ====================
  13491. function openAddDHCPStaticLeaseModal() {
  13492. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13493. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13494. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13495. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13496. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13497. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13498. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13499. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13500. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13501. }
  13502. function closeDHCPStaticLeaseModal() {
  13503. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13504. }
  13505. async function submitSaveDHCPStaticLease(e) {
  13506. e.preventDefault();
  13507. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13508. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13509. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13510. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13511. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13512. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13513. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13514. try {
  13515. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13516. method: 'POST',
  13517. headers: { 'Content-Type': 'application/json' },
  13518. body: JSON.stringify({
  13519. id,
  13520. mac_address: mac,
  13521. address: ip,
  13522. hostname,
  13523. server,
  13524. comment,
  13525. disabled
  13526. })
  13527. });
  13528. if (res.ok) {
  13529. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13530. closeDHCPStaticLeaseModal();
  13531. loadDHCPServer(false);
  13532. fetchData(false);
  13533. } else {
  13534. const err = await res.text();
  13535. showToast('Error', err, 'error');
  13536. }
  13537. } catch (err) {
  13538. showToast('Error', err.message, 'error');
  13539. }
  13540. }
  13541. async function deleteDHCPStaticLease(id) {
  13542. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13543. try {
  13544. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13545. if (res.ok) {
  13546. showToast('Deleted', 'Static lease removed', 'success');
  13547. loadDHCPServer(false);
  13548. fetchData(false);
  13549. }
  13550. } catch (err) {
  13551. showToast('Error', err.message, 'error');
  13552. }
  13553. }
  13554. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13555. try {
  13556. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13557. method: 'POST',
  13558. headers: { 'Content-Type': 'application/json' },
  13559. body: JSON.stringify({
  13560. mac_address: mac,
  13561. address: ip,
  13562. hostname,
  13563. comment: comment || 'Converted to static'
  13564. })
  13565. });
  13566. if (res.ok) {
  13567. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13568. loadDHCPServer(false);
  13569. fetchData(false);
  13570. } else {
  13571. const err = await res.text();
  13572. showToast('Error', err, 'error');
  13573. }
  13574. } catch (err) {
  13575. showToast('Error', err.message, 'error');
  13576. }
  13577. }
  13578. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13579. function openAddDHCPOptionModal() {
  13580. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13581. document.getElementById('dhcp-option-modal-id').value = '';
  13582. document.getElementById('dhcp-option-modal-name').value = '';
  13583. document.getElementById('dhcp-option-modal-code').value = '';
  13584. document.getElementById('dhcp-option-modal-value').value = '';
  13585. document.getElementById('dhcp-option-modal-comment').value = '';
  13586. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13587. }
  13588. function openEditDHCPOptionModal(id) {
  13589. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13590. if (!o) return;
  13591. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13592. document.getElementById('dhcp-option-modal-id').value = o.id;
  13593. document.getElementById('dhcp-option-modal-name').value = o.name;
  13594. document.getElementById('dhcp-option-modal-code').value = o.code;
  13595. document.getElementById('dhcp-option-modal-value').value = o.value;
  13596. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13597. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13598. }
  13599. function closeDHCPOptionModal() {
  13600. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13601. }
  13602. async function submitSaveDHCPOption(e) {
  13603. e.preventDefault();
  13604. const id = document.getElementById('dhcp-option-modal-id').value;
  13605. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13606. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13607. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13608. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13609. try {
  13610. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13611. method: 'POST',
  13612. headers: { 'Content-Type': 'application/json' },
  13613. body: JSON.stringify({ id, name, code, value, comment })
  13614. });
  13615. if (res.ok) {
  13616. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13617. closeDHCPOptionModal();
  13618. loadDHCPServer(false);
  13619. fetchData(false);
  13620. } else {
  13621. const err = await res.text();
  13622. showToast('Error', err, 'error');
  13623. }
  13624. } catch (err) {
  13625. showToast('Error', err.message, 'error');
  13626. }
  13627. }
  13628. async function deleteDHCPOption(id, name) {
  13629. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13630. try {
  13631. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13632. if (res.ok) {
  13633. showToast('Deleted', `Option ${name} removed`, 'success');
  13634. loadDHCPServer(false);
  13635. fetchData(false);
  13636. }
  13637. } catch (err) {
  13638. showToast('Error', err.message, 'error');
  13639. }
  13640. }
  13641. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13642. function openDHCPServerSetupModal() {
  13643. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13644. onDHCPWizardIfaceChange();
  13645. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13646. }
  13647. function closeDHCPServerSetupModal() {
  13648. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13649. }
  13650. function onDHCPWizardIfaceChange() {
  13651. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13652. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13653. let ip = '192.168.88.1';
  13654. let prefix = '24';
  13655. if (iface && iface.ip_address) {
  13656. const parts = iface.ip_address.split('/');
  13657. ip = parts[0];
  13658. if (parts.length > 1) prefix = parts[1];
  13659. }
  13660. // Calculate subnet base (e.g. 192.168.88.0/24)
  13661. const ipParts = ip.split('.');
  13662. if (ipParts.length === 4) {
  13663. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13664. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13665. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13666. document.getElementById('dhcp-wizard-gateway').value = ip;
  13667. document.getElementById('dhcp-wizard-pool').value = pool;
  13668. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13669. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13670. }
  13671. }
  13672. async function submitDHCPServerSetupWizard(e) {
  13673. e.preventDefault();
  13674. const iface = document.getElementById('dhcp-wizard-iface').value;
  13675. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13676. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13677. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13678. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13679. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13680. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13681. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13682. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13683. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13684. try {
  13685. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13686. method: 'POST',
  13687. headers: { 'Content-Type': 'application/json' },
  13688. body: JSON.stringify({
  13689. interface: iface,
  13690. address_space: space,
  13691. gateway: gw,
  13692. address_pool: pool,
  13693. dns_servers: dnsServers,
  13694. lease_time: leaseTime,
  13695. ntp_servers: ntpServers,
  13696. next_server: tftp
  13697. })
  13698. });
  13699. if (res.ok) {
  13700. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13701. closeDHCPServerSetupModal();
  13702. loadDHCPServer(false);
  13703. fetchData(false);
  13704. } else {
  13705. const err = await res.text();
  13706. showToast('Error', err, 'error');
  13707. }
  13708. } catch (err) {
  13709. showToast('Error', err.message, 'error');
  13710. }
  13711. }
  13712. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13713. const sel = document.getElementById(elemId);
  13714. if (!sel) return;
  13715. sel.innerHTML = '<option value="">Select interface...</option>';
  13716. const ifaces = state.interfaces || [];
  13717. ifaces.forEach(i => {
  13718. if (i.name === 'lo') return;
  13719. const opt = document.createElement('option');
  13720. opt.value = i.name;
  13721. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13722. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13723. if (i.name === selectedVal) opt.selected = true;
  13724. sel.appendChild(opt);
  13725. });
  13726. }
  13727. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13728. function initTableSorting() {
  13729. document.querySelectorAll('table').forEach(setupSortableTable);
  13730. }
  13731. function setupSortableTable(table) {
  13732. const thead = table.querySelector('thead');
  13733. const tbody = table.querySelector('tbody');
  13734. if (!thead || !tbody) return;
  13735. const headerRows = thead.querySelectorAll('tr');
  13736. if (headerRows.length === 0) return;
  13737. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13738. ths.forEach((th, colIdx) => {
  13739. if (th._sortBound) return;
  13740. th._sortBound = true;
  13741. const rawText = th.innerText.trim().toLowerCase();
  13742. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13743. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13744. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13745. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13746. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13747. return;
  13748. }
  13749. th.classList.add('table-sortable', 'group');
  13750. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13751. let icon = th.querySelector('.table-sort-icon');
  13752. if (!icon) {
  13753. icon = document.createElement('span');
  13754. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13755. icon.innerHTML = '⇅';
  13756. th.appendChild(icon);
  13757. }
  13758. th.addEventListener('click', (e) => {
  13759. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13760. handleHeaderClick(table, th, colIdx);
  13761. });
  13762. });
  13763. if (!tbody._sortObserved) {
  13764. tbody._sortObserved = true;
  13765. let sortDebounceTimer = null;
  13766. const observer = new MutationObserver((mutations) => {
  13767. if (tbody._isSorting) return;
  13768. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13769. if (!hasChildChanges) return;
  13770. clearTimeout(sortDebounceTimer);
  13771. sortDebounceTimer = setTimeout(() => {
  13772. if (tbody._isSorting) return;
  13773. if (table._activeSort && table._activeSort.dir !== 'none') {
  13774. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13775. } else {
  13776. tagOriginalRowOrder(tbody);
  13777. }
  13778. }, 50);
  13779. });
  13780. tbody._sortObserver = observer;
  13781. observer.observe(tbody, { childList: true });
  13782. }
  13783. tagOriginalRowOrder(tbody);
  13784. }
  13785. function tagOriginalRowOrder(tbody) {
  13786. let idx = 0;
  13787. Array.from(tbody.children).forEach(tr => {
  13788. if (!tr.querySelector('td[colspan]')) {
  13789. if (!tr.hasAttribute('data-orig-idx')) {
  13790. tr.setAttribute('data-orig-idx', idx++);
  13791. }
  13792. }
  13793. });
  13794. }
  13795. function handleHeaderClick(table, th, colIdx) {
  13796. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13797. let newDir = 'asc';
  13798. if (currentSort.colIdx === colIdx) {
  13799. if (currentSort.dir === 'asc') newDir = 'desc';
  13800. else if (currentSort.dir === 'desc') newDir = 'none';
  13801. else newDir = 'asc';
  13802. } else {
  13803. newDir = 'asc';
  13804. }
  13805. table._activeSort = { colIdx, dir: newDir };
  13806. updateHeaderIcons(table, colIdx, newDir);
  13807. applyTableSort(table, colIdx, newDir, true);
  13808. }
  13809. function updateHeaderIcons(table, activeColIdx, dir) {
  13810. const thead = table.querySelector('thead');
  13811. if (!thead) return;
  13812. const ths = thead.querySelectorAll('th');
  13813. ths.forEach((th, idx) => {
  13814. const icon = th.querySelector('.table-sort-icon');
  13815. if (!icon) return;
  13816. if (idx === activeColIdx && dir !== 'none') {
  13817. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13818. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13819. th.classList.add('table-sorted-active');
  13820. } else {
  13821. icon.innerHTML = '⇅';
  13822. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13823. th.classList.remove('table-sorted-active');
  13824. }
  13825. });
  13826. }
  13827. function applyTableSort(table, colIdx, dir, userInitiated) {
  13828. const tbody = table.querySelector('tbody');
  13829. if (!tbody || tbody.children.length <= 1) return;
  13830. tbody._isSorting = true;
  13831. tagOriginalRowOrder(tbody);
  13832. // Group parent rows and any attached drawer/sub-rows
  13833. const groups = [];
  13834. let currentGroup = null;
  13835. Array.from(tbody.children).forEach(tr => {
  13836. if (tr.querySelector('td[colspan]')) {
  13837. if (currentGroup) {
  13838. currentGroup.subRows.push(tr);
  13839. } else {
  13840. groups.push({ mainRow: tr, subRows: [] });
  13841. }
  13842. } else {
  13843. currentGroup = { mainRow: tr, subRows: [] };
  13844. groups.push(currentGroup);
  13845. }
  13846. });
  13847. if (dir === 'none') {
  13848. groups.sort((a, b) => {
  13849. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13850. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13851. return idxA - idxB;
  13852. });
  13853. } else {
  13854. groups.sort((a, b) => {
  13855. const cellA = a.mainRow.children[colIdx];
  13856. const cellB = b.mainRow.children[colIdx];
  13857. const res = compareTableCells(cellA, cellB);
  13858. return dir === 'asc' ? res : -res;
  13859. });
  13860. }
  13861. // Check if rows are already in correct order to avoid modifying DOM
  13862. let alreadyOrdered = true;
  13863. let childIdx = 0;
  13864. for (const g of groups) {
  13865. if (tbody.children[childIdx] !== g.mainRow) {
  13866. alreadyOrdered = false;
  13867. break;
  13868. }
  13869. childIdx++;
  13870. for (const sub of g.subRows) {
  13871. if (tbody.children[childIdx] !== sub) {
  13872. alreadyOrdered = false;
  13873. break;
  13874. }
  13875. childIdx++;
  13876. }
  13877. }
  13878. if (alreadyOrdered) {
  13879. tbody._isSorting = false;
  13880. return;
  13881. }
  13882. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13883. if (tbody._sortObserver) {
  13884. tbody._sortObserver.disconnect();
  13885. }
  13886. // Re-append rows in sorted order
  13887. groups.forEach(g => {
  13888. tbody.appendChild(g.mainRow);
  13889. g.subRows.forEach(sub => tbody.appendChild(sub));
  13890. });
  13891. // Drain any queued mutations and re-connect observer
  13892. if (tbody._sortObserver) {
  13893. tbody._sortObserver.takeRecords();
  13894. tbody._sortObserver.observe(tbody, { childList: true });
  13895. }
  13896. tbody._isSorting = false;
  13897. }
  13898. function getCellRawText(cell) {
  13899. if (!cell) return '';
  13900. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13901. const input = cell.querySelector('input, select');
  13902. if (input) {
  13903. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13904. return input.value;
  13905. }
  13906. return cell.innerText.trim();
  13907. }
  13908. function parseTrafficToNumber(str) {
  13909. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13910. if (!m) return null;
  13911. const num = parseFloat(m[1].replace(/,/g, ''));
  13912. if (isNaN(num)) return null;
  13913. const unit = m[2].toUpperCase();
  13914. let mult = 1;
  13915. if (unit.startsWith('K')) mult = 1024;
  13916. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13917. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13918. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13919. return num * mult;
  13920. }
  13921. function parseIpToNumber(str) {
  13922. const clean = str.replace(/^[!~]/, '').trim();
  13923. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13924. if (!m) return null;
  13925. const o1 = parseInt(m[1], 10);
  13926. const o2 = parseInt(m[2], 10);
  13927. const o3 = parseInt(m[3], 10);
  13928. const o4 = parseInt(m[4], 10);
  13929. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13930. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13931. }
  13932. function parseCompoundPackets(str) {
  13933. const m = str.match(/^([\d,]+)p/);
  13934. if (!m) return null;
  13935. return parseInt(m[1].replace(/,/g, ''), 10);
  13936. }
  13937. function compareTableCells(cellA, cellB) {
  13938. const a = getCellRawText(cellA);
  13939. const b = getCellRawText(cellB);
  13940. if (a === '' && b !== '') return 1;
  13941. if (b === '' && a !== '') return -1;
  13942. if (a === b) return 0;
  13943. // 1. IP Addresses / CIDR
  13944. const ipA = parseIpToNumber(a);
  13945. const ipB = parseIpToNumber(b);
  13946. if (ipA !== null && ipB !== null) return ipA - ipB;
  13947. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13948. const pktA = parseCompoundPackets(a);
  13949. const pktB = parseCompoundPackets(b);
  13950. if (pktA !== null && pktB !== null) return pktA - pktB;
  13951. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13952. const trafA = parseTrafficToNumber(a);
  13953. const trafB = parseTrafficToNumber(b);
  13954. if (trafA !== null && trafB !== null) return trafA - trafB;
  13955. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13956. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13957. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13958. const numA = Number(cleanNumA);
  13959. const numB = Number(cleanNumB);
  13960. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13961. return numA - numB;
  13962. }
  13963. // 5. Natural case-insensitive string compare
  13964. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13965. }
  13966. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13967. async function loadVRRP(showToastNotification = false) {
  13968. try {
  13969. const [instRes, sumRes] = await Promise.all([
  13970. fetch(`${API_BASE}/vrrp/instances`),
  13971. fetch(`${API_BASE}/vrrp/summary`)
  13972. ]);
  13973. if (instRes.ok) {
  13974. state.vrrpInstances = await instRes.json();
  13975. renderVRRP();
  13976. }
  13977. if (sumRes.ok) {
  13978. state.vrrpSummary = await sumRes.json();
  13979. renderVRRPSummary();
  13980. }
  13981. if (showToastNotification) {
  13982. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13983. }
  13984. } catch (err) {
  13985. console.error('Failed to load VRRP:', err);
  13986. }
  13987. }
  13988. function renderVRRPSummary() {
  13989. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13990. const elTotal = document.getElementById('vrrp-stat-total');
  13991. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13992. const elMaster = document.getElementById('vrrp-stat-master');
  13993. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13994. const elBackup = document.getElementById('vrrp-stat-backup');
  13995. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13996. const bCount = document.getElementById('badge-vrrp-count');
  13997. if (bCount) bCount.innerText = s.total_instances || 0;
  13998. const dot = document.getElementById('badge-vrrp-dot');
  13999. if (dot) {
  14000. if (s.master_instances > 0) {
  14001. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14002. } else if (s.backup_instances > 0) {
  14003. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14004. } else {
  14005. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14006. }
  14007. }
  14008. }
  14009. function renderVRRP() {
  14010. const tbody = document.getElementById('vrrp-table-tbody');
  14011. const empty = document.getElementById('vrrp-table-empty');
  14012. if (!tbody) return;
  14013. tbody.innerHTML = '';
  14014. const instances = state.vrrpInstances || [];
  14015. if (instances.length === 0) {
  14016. empty?.classList.remove('hidden');
  14017. return;
  14018. }
  14019. empty?.classList.add('hidden');
  14020. instances.forEach(inst => {
  14021. const tr = document.createElement('tr');
  14022. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14023. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14024. 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>`;
  14025. if (inst.disabled) {
  14026. 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>`;
  14027. } else if (inst.state === 'MASTER') {
  14028. 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>`;
  14029. } else if (inst.state === 'BACKUP') {
  14030. 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>`;
  14031. } else if (inst.state === 'FAULT') {
  14032. 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>`;
  14033. }
  14034. // Render State Badge
  14035. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14036. if (!inst.disabled) {
  14037. if (inst.state === 'MASTER') {
  14038. 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>`;
  14039. } else if (inst.state === 'BACKUP') {
  14040. 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>`;
  14041. } else if (inst.state === 'FAULT') {
  14042. 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>`;
  14043. }
  14044. }
  14045. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14046. tr.innerHTML = `
  14047. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14048. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14049. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14050. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14051. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14052. <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>
  14053. <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>
  14054. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14055. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14056. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14057. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14058. <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>
  14059. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14060. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14061. </td>
  14062. `;
  14063. tbody.appendChild(tr);
  14064. });
  14065. }
  14066. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14067. const sel = document.getElementById(elemId);
  14068. if (!sel) return;
  14069. sel.innerHTML = '<option value="">Select interface...</option>';
  14070. const ifaces = state.interfaces || [];
  14071. ifaces.forEach(i => {
  14072. const opt = document.createElement('option');
  14073. opt.value = i.name;
  14074. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14075. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14076. sel.appendChild(opt);
  14077. });
  14078. }
  14079. function openAddVRRPModal() {
  14080. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14081. document.getElementById('modal-vrrp-id').value = '';
  14082. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14083. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14084. document.getElementById('modal-vrrp-priority').value = 100;
  14085. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14086. document.getElementById('modal-vrrp-version').value = '3';
  14087. document.getElementById('modal-vrrp-interval').value = 1;
  14088. document.getElementById('modal-vrrp-authtype').value = 'none';
  14089. document.getElementById('modal-vrrp-authpass').value = '';
  14090. document.getElementById('modal-vrrp-comment').value = '';
  14091. document.getElementById('modal-vrrp-preempt').checked = true;
  14092. document.getElementById('modal-vrrp-disabled').checked = false;
  14093. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14094. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14095. }
  14096. function openEditVRRPModal(id) {
  14097. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14098. if (!inst) return;
  14099. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14100. document.getElementById('modal-vrrp-id').value = inst.id;
  14101. document.getElementById('modal-vrrp-name').value = inst.name;
  14102. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14103. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14104. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14105. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14106. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14107. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14108. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14109. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14110. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14111. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14112. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14113. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14114. }
  14115. function closeVRRPModal() {
  14116. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14117. }
  14118. async function submitSaveVRRP(e) {
  14119. e.preventDefault();
  14120. const id = document.getElementById('modal-vrrp-id').value;
  14121. const name = document.getElementById('modal-vrrp-name').value.trim();
  14122. const iface = document.getElementById('modal-vrrp-iface').value;
  14123. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14124. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14125. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14126. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14127. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14128. const authType = document.getElementById('modal-vrrp-authtype').value;
  14129. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14130. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14131. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14132. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14133. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14134. try {
  14135. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14136. method: 'POST',
  14137. headers: { 'Content-Type': 'application/json' },
  14138. body: JSON.stringify({
  14139. id,
  14140. name,
  14141. interface: iface,
  14142. vrid,
  14143. priority,
  14144. virtual_ips: vips,
  14145. version,
  14146. interval,
  14147. auth_type: authType,
  14148. auth_password: authPass,
  14149. comment,
  14150. preempt,
  14151. disabled
  14152. })
  14153. });
  14154. if (res.ok) {
  14155. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14156. closeVRRPModal();
  14157. loadVRRP(false);
  14158. fetchData(false);
  14159. } else {
  14160. const err = await res.text();
  14161. showToast('Error', err, 'error');
  14162. }
  14163. } catch (err) {
  14164. showToast('Error', err.message, 'error');
  14165. }
  14166. }
  14167. async function deleteVRRP(id, name) {
  14168. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14169. try {
  14170. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14171. if (res.ok) {
  14172. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14173. loadVRRP(false);
  14174. fetchData(false);
  14175. } else {
  14176. const err = await res.text();
  14177. showToast('Error', err, 'error');
  14178. }
  14179. } catch (err) {
  14180. showToast('Error', err.message, 'error');
  14181. }
  14182. }
  14183. async function toggleVRRPState(id, disabled) {
  14184. try {
  14185. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14186. method: 'POST',
  14187. headers: { 'Content-Type': 'application/json' },
  14188. body: JSON.stringify({ disabled })
  14189. });
  14190. if (res.ok) {
  14191. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14192. loadVRRP(false);
  14193. fetchData(false);
  14194. } else {
  14195. const err = await res.text();
  14196. showToast('Error', err, 'error');
  14197. }
  14198. } catch (err) {
  14199. showToast('Error', err.message, 'error');
  14200. }
  14201. }
  14202. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14203. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14204. let docSortDebounce = null;
  14205. const docTableObserver = new MutationObserver((mutations) => {
  14206. let needsInit = false;
  14207. for (const m of mutations) {
  14208. for (const node of m.addedNodes) {
  14209. if (node.nodeType === 1) {
  14210. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14211. needsInit = true;
  14212. break;
  14213. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14214. needsInit = true;
  14215. break;
  14216. }
  14217. }
  14218. }
  14219. if (needsInit) break;
  14220. }
  14221. if (needsInit) {
  14222. clearTimeout(docSortDebounce);
  14223. docSortDebounce = setTimeout(initTableSorting, 100);
  14224. }
  14225. });
  14226. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14227. }
  14228. // =========================================================================
  14229. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14230. // =========================================================================
  14231. const bwtestState = {
  14232. running: false,
  14233. pollTimer: null,
  14234. eventSource: null,
  14235. chartPoints: [],
  14236. maxChartPoints: 60,
  14237. serverConfig: null,
  14238. peakTx: 0,
  14239. peakRx: 0,
  14240. targetDuration: 10,
  14241. lastSampleElapsed: -1,
  14242. sessionID: null
  14243. };
  14244. async function loadBwTestView() {
  14245. resizeBwTestCanvas();
  14246. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14247. }
  14248. async function fetchBwTestServerStatus() {
  14249. try {
  14250. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14251. if (!res.ok) return;
  14252. const s = await res.json();
  14253. bwtestState.serverConfig = s;
  14254. // Update indicator and badges
  14255. const indicator = document.getElementById('bwtest-server-indicator');
  14256. const badge = document.getElementById('bwtest-server-badge');
  14257. const sideBadge = document.getElementById('badge-bwtest-server');
  14258. if (s.enabled && s.running) {
  14259. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14260. if (badge) {
  14261. badge.innerText = `Port ${s.port} (Active)`;
  14262. badge.className = 'text-emerald-400 font-bold';
  14263. }
  14264. if (sideBadge) {
  14265. sideBadge.innerText = s.port;
  14266. 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';
  14267. }
  14268. } else {
  14269. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14270. if (badge) {
  14271. badge.innerText = `Disabled`;
  14272. badge.className = 'text-slate-500 font-bold';
  14273. }
  14274. if (sideBadge) {
  14275. sideBadge.innerText = 'Off';
  14276. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14277. }
  14278. }
  14279. // Modal fields
  14280. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14281. const serverModal = document.getElementById('modal-bwtest-server');
  14282. const editing = serverModal && !serverModal.classList.contains('hidden');
  14283. if (toggle && !editing) toggle.checked = !!s.enabled;
  14284. const portInp = document.getElementById('bwtest-server-port-input');
  14285. if (portInp && !editing) portInp.value = s.port || 2000;
  14286. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14287. if (actSess) actSess.innerText = s.active_sessions || 0;
  14288. const totServ = document.getElementById('bwtest-modal-total-served');
  14289. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14290. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14291. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14292. } catch (err) {
  14293. console.error('Failed to fetch BwTest server status:', err);
  14294. }
  14295. }
  14296. function openBwTestServerModal() {
  14297. const cfg = bwtestState.serverConfig;
  14298. if (cfg) {
  14299. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14300. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14301. }
  14302. fetchBwTestServerStatus();
  14303. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14304. }
  14305. function closeBwTestServerModal() {
  14306. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14307. }
  14308. async function submitBwTestServerSettings(e) {
  14309. e.preventDefault();
  14310. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14311. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14312. try {
  14313. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14314. method: 'POST',
  14315. headers: { 'Content-Type': 'application/json' },
  14316. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14317. });
  14318. if (!res.ok) {
  14319. const err = await res.json();
  14320. throw new Error(err.error || 'Failed to update server configuration');
  14321. }
  14322. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14323. closeBwTestServerModal();
  14324. fetchBwTestServerStatus();
  14325. } catch (err) {
  14326. showToast('Server Configuration Error', err.message, 'error');
  14327. }
  14328. }
  14329. function setBwTestTarget(target) {
  14330. const inp = document.getElementById('bwtest-input-target');
  14331. if (inp) inp.value = target;
  14332. }
  14333. function setBwTestProtocol(proto) {
  14334. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14335. if (hiddenInp) hiddenInp.value = proto;
  14336. const btnUdp = document.getElementById('bwtest-proto-udp');
  14337. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14338. const badge = document.getElementById('bwtest-proto-badge');
  14339. const pktField = document.getElementById('bwtest-field-pktsize');
  14340. 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';
  14341. 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';
  14342. 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';
  14343. if (proto === 'udp') {
  14344. if (btnUdp) {
  14345. btnUdp.className = activeUdpCls;
  14346. const dot = btnUdp.querySelector('span');
  14347. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14348. }
  14349. if (btnTcp) {
  14350. btnTcp.className = inactiveCls;
  14351. const dot = btnTcp.querySelector('span');
  14352. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14353. }
  14354. if (badge) {
  14355. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14356. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14357. }
  14358. if (pktField) pktField.classList.remove('opacity-40');
  14359. } else {
  14360. if (btnUdp) {
  14361. btnUdp.className = inactiveCls;
  14362. const dot = btnUdp.querySelector('span');
  14363. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14364. }
  14365. if (btnTcp) {
  14366. btnTcp.className = activeTcpCls;
  14367. const dot = btnTcp.querySelector('span');
  14368. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14369. }
  14370. if (badge) {
  14371. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14372. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14373. }
  14374. if (pktField) pktField.classList.add('opacity-40');
  14375. }
  14376. }
  14377. function setBwTestDirection(dir) {
  14378. const hiddenInp = document.getElementById('bwtest-input-direction');
  14379. if (hiddenInp) hiddenInp.value = dir;
  14380. const btnBoth = document.getElementById('bwtest-dir-both');
  14381. const btnTx = document.getElementById('bwtest-dir-tx');
  14382. const btnRx = document.getElementById('bwtest-dir-rx');
  14383. 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';
  14384. 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';
  14385. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14386. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14387. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14388. }
  14389. function setBwTestLimit(bps) {
  14390. const sel = document.getElementById('bwtest-input-limit');
  14391. if (sel) sel.value = String(bps);
  14392. }
  14393. async function checkActiveBwTest() {
  14394. try {
  14395. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14396. if (!res.ok) return;
  14397. const st = await res.json();
  14398. if (st.running) {
  14399. setBwTestRunningUI(true);
  14400. processBwTestStatus(st);
  14401. startBwTestTelemetry();
  14402. }
  14403. } catch (err) {
  14404. console.error('Failed to check active BwTest:', err);
  14405. }
  14406. }
  14407. async function startBwTest(e) {
  14408. if (e && e.preventDefault) e.preventDefault();
  14409. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14410. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14411. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14412. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14413. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14414. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14415. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14416. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14417. bwtestState.targetDuration = duration;
  14418. bwtestState.chartPoints = [];
  14419. bwtestState.peakTx = 0;
  14420. bwtestState.peakRx = 0;
  14421. bwtestState.lastSampleElapsed = -1;
  14422. bwtestState.sessionID = null;
  14423. // Clear UI elements
  14424. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14425. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14426. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14427. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14428. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14429. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14430. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14431. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14432. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14433. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14434. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14435. const tbody = document.getElementById('bwtest-samples-tbody');
  14436. if (tbody) tbody.innerHTML = '';
  14437. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14438. setBwTestRunningUI(true);
  14439. try {
  14440. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14441. method: 'POST',
  14442. headers: { 'Content-Type': 'application/json' },
  14443. body: JSON.stringify({
  14444. target,
  14445. port,
  14446. direction,
  14447. protocol,
  14448. bandwidth_limit,
  14449. packet_size,
  14450. streams,
  14451. duration
  14452. })
  14453. });
  14454. if (!res.ok) {
  14455. const err = await res.json();
  14456. throw new Error(err.error || 'Failed to start bandwidth test');
  14457. }
  14458. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14459. startBwTestTelemetry();
  14460. } catch (err) {
  14461. setBwTestRunningUI(false);
  14462. showToast('Start Failed', err.message, 'error');
  14463. }
  14464. }
  14465. function setBwTestRunningUI(running) {
  14466. bwtestState.running = running;
  14467. const startBtn = document.getElementById('bwtest-btn-start');
  14468. const stopBtn = document.getElementById('bwtest-btn-stop');
  14469. const badge = document.getElementById('bwtest-run-status-badge');
  14470. const ph = document.getElementById('bwtest-chart-placeholder');
  14471. if (running) {
  14472. if (startBtn) {
  14473. startBtn.disabled = true;
  14474. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14475. }
  14476. if (stopBtn) {
  14477. stopBtn.disabled = false;
  14478. stopBtn.classList.remove('opacity-40');
  14479. }
  14480. if (badge) {
  14481. badge.innerText = 'TESTING...';
  14482. 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';
  14483. }
  14484. if (ph) ph.style.display = 'none';
  14485. } else {
  14486. if (startBtn) {
  14487. startBtn.disabled = false;
  14488. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14489. }
  14490. if (stopBtn) {
  14491. stopBtn.disabled = true;
  14492. stopBtn.classList.add('opacity-40');
  14493. }
  14494. if (badge) {
  14495. badge.innerText = 'IDLE';
  14496. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14497. }
  14498. }
  14499. }
  14500. async function stopBwTest() {
  14501. try {
  14502. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14503. if (!res.ok) throw new Error(await responseError(res));
  14504. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14505. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14506. } catch (err) {
  14507. showToast('Stop Failed', err.message, 'error');
  14508. }
  14509. }
  14510. async function responseError(res) {
  14511. const text = await res.text();
  14512. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14513. catch { return text || `HTTP ${res.status}`; }
  14514. }
  14515. function processBwTestStatus(st) {
  14516. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14517. bwtestState.sessionID = st.session_id;
  14518. bwtestState.lastSampleElapsed = -1;
  14519. }
  14520. for (const sample of st.recent_samples || []) {
  14521. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14522. handleBwTestSample(sample);
  14523. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14524. }
  14525. }
  14526. if (!st.running) {
  14527. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14528. bwtestState.pollTimer = null;
  14529. setBwTestRunningUI(false);
  14530. handleBwTestFinish(st.summary, st.error);
  14531. }
  14532. }
  14533. function startBwTestTelemetry() {
  14534. if (!state.currentUser) return;
  14535. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14536. let busy = false;
  14537. const poll = async () => {
  14538. if (busy || !state.currentUser || document.hidden) return;
  14539. busy = true;
  14540. try {
  14541. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14542. if (!res.ok) throw new Error(await responseError(res));
  14543. processBwTestStatus(await res.json());
  14544. } catch (err) {
  14545. console.error('BwTest polling error:', err);
  14546. } finally { busy = false; }
  14547. };
  14548. bwtestState.pollTimer = setInterval(poll, 400);
  14549. poll();
  14550. }
  14551. function handleBwTestSample(s) {
  14552. if (!s) return;
  14553. const payloadHint = document.getElementById('bwtest-effective-payload');
  14554. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14555. const txMbps = s.tx_mbps || 0;
  14556. const rxMbps = s.rx_mbps || 0;
  14557. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14558. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14559. // KPI updates
  14560. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14561. if (elTx) {
  14562. elTx.innerText = txMbps.toFixed(2);
  14563. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14564. }
  14565. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14566. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14567. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14568. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14569. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14570. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14571. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14572. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14573. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14574. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14575. const elLoss = document.getElementById('bwtest-stat-loss');
  14576. if (elLoss) {
  14577. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14578. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14579. }
  14580. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14581. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14582. const elJitter = document.getElementById('bwtest-stat-jitter');
  14583. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14584. const elTime = document.getElementById('bwtest-stat-time');
  14585. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14586. const elData = document.getElementById('bwtest-stat-data');
  14587. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14588. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14589. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14590. // Append point to chart buffer
  14591. bwtestState.chartPoints.push({
  14592. elapsed: s.elapsed_sec || 0,
  14593. tx: txMbps,
  14594. rx: rxMbps
  14595. });
  14596. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14597. bwtestState.chartPoints.shift();
  14598. }
  14599. drawBwTestChart();
  14600. // Add row to breakdown table
  14601. const tbody = document.getElementById('bwtest-samples-tbody');
  14602. if (tbody) {
  14603. const tr = document.createElement('tr');
  14604. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14605. tr.innerHTML = `
  14606. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14607. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14608. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14609. <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>
  14610. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14611. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14612. `;
  14613. tbody.insertBefore(tr, tbody.firstChild);
  14614. const countEl = document.getElementById('bwtest-sample-count');
  14615. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14616. }
  14617. }
  14618. function handleBwTestFinish(summary, error) {
  14619. const badge = document.getElementById('bwtest-run-status-badge');
  14620. if (error) {
  14621. showToast('Benchmark Error', error, 'error');
  14622. if (badge) {
  14623. badge.innerText = 'ERROR';
  14624. 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';
  14625. }
  14626. } else if (summary) {
  14627. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14628. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14629. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14630. if (badge) {
  14631. badge.innerText = 'COMPLETED';
  14632. 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';
  14633. }
  14634. }
  14635. loadBwTestHistory();
  14636. fetchBwTestServerStatus();
  14637. }
  14638. function resizeBwTestCanvas() {
  14639. const canvas = document.getElementById('bwtest-chart');
  14640. if (!canvas || !canvas.parentElement) return;
  14641. const rect = canvas.parentElement.getBoundingClientRect();
  14642. const dpr = window.devicePixelRatio || 1;
  14643. canvas.width = rect.width * dpr;
  14644. canvas.height = rect.height * dpr;
  14645. const ctx = canvas.getContext('2d');
  14646. ctx.scale(dpr, dpr);
  14647. drawBwTestChart();
  14648. }
  14649. window.addEventListener('resize', () => {
  14650. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14651. });
  14652. function drawBwTestChart() {
  14653. const canvas = document.getElementById('bwtest-chart');
  14654. if (!canvas) return;
  14655. const ctx = canvas.getContext('2d');
  14656. const dpr = window.devicePixelRatio || 1;
  14657. const width = canvas.width / dpr;
  14658. const height = canvas.height / dpr;
  14659. ctx.clearRect(0, 0, width, height);
  14660. const points = bwtestState.chartPoints;
  14661. if (!points || points.length === 0) return;
  14662. // Determine scale ceiling
  14663. let maxRate = 10;
  14664. for (const p of points) {
  14665. if (p.tx > maxRate) maxRate = p.tx;
  14666. if (p.rx > maxRate) maxRate = p.rx;
  14667. }
  14668. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14669. const paddingLeft = 55;
  14670. const paddingBottom = 24;
  14671. const paddingTop = 12;
  14672. const paddingRight = 16;
  14673. const chartW = width - paddingLeft - paddingRight;
  14674. const chartH = height - paddingTop - paddingBottom;
  14675. // Grid Lines and Y-Axis labels
  14676. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14677. ctx.lineWidth = 1;
  14678. ctx.fillStyle = '#94a3b8';
  14679. ctx.font = '10px monospace';
  14680. ctx.textAlign = 'right';
  14681. const gridSteps = 4;
  14682. for (let i = 0; i <= gridSteps; i++) {
  14683. const val = (maxRate / gridSteps) * i;
  14684. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14685. ctx.beginPath();
  14686. ctx.moveTo(paddingLeft, y);
  14687. ctx.lineTo(width - paddingRight, y);
  14688. ctx.stroke();
  14689. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14690. }
  14691. // Draw TX Line (Cyan #22d3ee)
  14692. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14693. // Draw RX Line (Purple #a855f7)
  14694. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14695. }
  14696. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14697. if (points.length < 2) return;
  14698. const stepX = w / Math.max(points.length - 1, 1);
  14699. // Gradient area fill
  14700. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14701. grad.addColorStop(0, fillColor);
  14702. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14703. ctx.beginPath();
  14704. points.forEach((p, idx) => {
  14705. const x = left + idx * stepX;
  14706. const val = valFn(p);
  14707. const y = top + h - (val / maxVal) * h;
  14708. if (idx === 0) {
  14709. ctx.moveTo(x, y);
  14710. } else {
  14711. ctx.lineTo(x, y);
  14712. }
  14713. });
  14714. // Complete path for fill
  14715. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14716. ctx.lineTo(left, top + h);
  14717. ctx.closePath();
  14718. ctx.fillStyle = grad;
  14719. ctx.fill();
  14720. // Draw line stroke
  14721. ctx.beginPath();
  14722. ctx.lineWidth = 2.5;
  14723. ctx.strokeStyle = strokeColor;
  14724. points.forEach((p, idx) => {
  14725. const x = left + idx * stepX;
  14726. const val = valFn(p);
  14727. const y = top + h - (val / maxVal) * h;
  14728. if (idx === 0) {
  14729. ctx.moveTo(x, y);
  14730. } else {
  14731. ctx.lineTo(x, y);
  14732. }
  14733. });
  14734. ctx.stroke();
  14735. // Draw end point halo
  14736. const lastP = points[points.length - 1];
  14737. const lastX = left + (points.length - 1) * stepX;
  14738. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14739. ctx.fillStyle = strokeColor;
  14740. ctx.beginPath();
  14741. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14742. ctx.fill();
  14743. }
  14744. async function loadBwTestHistory() {
  14745. try {
  14746. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14747. if (!res.ok) return;
  14748. const list = await res.json();
  14749. renderBwTestHistory(Array.isArray(list) ? list : []);
  14750. } catch (err) {
  14751. console.error('Failed to load BwTest history:', err);
  14752. }
  14753. }
  14754. function renderBwTestHistory(list) {
  14755. const tbody = document.getElementById('bwtest-history-tbody');
  14756. if (!tbody) return;
  14757. if (list.length === 0) {
  14758. 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>`;
  14759. return;
  14760. }
  14761. tbody.innerHTML = '';
  14762. list.forEach(item => {
  14763. const s = item.summary || {};
  14764. const tr = document.createElement('tr');
  14765. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14766. const dirBadge = item.direction === 'both'
  14767. ? `<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>`
  14768. : item.direction === 'tx'
  14769. ? `<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>`
  14770. : `<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>`;
  14771. const protoBadge = item.protocol === 'tcp'
  14772. ? `<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>`
  14773. : `<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>`;
  14774. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14775. tr.innerHTML = `
  14776. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14777. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14778. <td class="py-2.5 px-4">${protoBadge}</td>
  14779. <td class="py-2.5 px-4">${dirBadge}</td>
  14780. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14781. <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>
  14782. <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>
  14783. <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>
  14784. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14785. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14786. `;
  14787. tbody.appendChild(tr);
  14788. });
  14789. }
  14790. // ======================== SETTINGS & ROUTER DNS ========================
  14791. state.settingsSubTab = 'dns';
  14792. state.dnsSettings = null;
  14793. state.dnsStaticRecords = [];
  14794. state.dnsStatus = null;
  14795. function switchSettingsSubTab(sub) {
  14796. state.settingsSubTab = sub;
  14797. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14798. const btnSys = document.getElementById('btn-settings-subtab-system');
  14799. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14800. const tabDns = document.getElementById('settings-subtab-dns');
  14801. const tabSys = document.getElementById('settings-subtab-system');
  14802. const tabBak = document.getElementById('settings-subtab-backup');
  14803. 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';
  14804. 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';
  14805. if (btnDns) btnDns.className = inactiveClass;
  14806. if (btnSys) btnSys.className = inactiveClass;
  14807. if (btnBak) btnBak.className = inactiveClass;
  14808. tabDns?.classList.add('hidden');
  14809. tabSys?.classList.add('hidden');
  14810. tabBak?.classList.add('hidden');
  14811. if (sub === 'dns') {
  14812. if (btnDns) btnDns.className = activeClass;
  14813. tabDns?.classList.remove('hidden');
  14814. loadDNSSettings();
  14815. } else if (sub === 'system') {
  14816. if (btnSys) btnSys.className = activeClass;
  14817. tabSys?.classList.remove('hidden');
  14818. loadSystemSettings();
  14819. } else if (sub === 'backup') {
  14820. if (btnBak) btnBak.className = activeClass;
  14821. tabBak?.classList.remove('hidden');
  14822. loadBackupList();
  14823. }
  14824. }
  14825. async function loadSettingsData(showLoading = false) {
  14826. if (state.settingsSubTab === 'system') {
  14827. await loadSystemSettings();
  14828. } else if (state.settingsSubTab === 'backup') {
  14829. await loadBackupList();
  14830. } else {
  14831. await loadDNSSettings();
  14832. }
  14833. }
  14834. async function loadDNSSettings() {
  14835. try {
  14836. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14837. fetch(`${API_BASE}/dns/settings`),
  14838. fetch(`${API_BASE}/dns/static`),
  14839. fetch(`${API_BASE}/dns/status`)
  14840. ]);
  14841. if (settingsRes.ok) {
  14842. state.dnsSettings = await settingsRes.json();
  14843. populateDNSSettingsForm(state.dnsSettings);
  14844. }
  14845. if (staticRes.ok) {
  14846. state.dnsStaticRecords = await staticRes.json();
  14847. renderStaticDNSList();
  14848. }
  14849. if (statusRes.ok) {
  14850. state.dnsStatus = await statusRes.json();
  14851. updateDNSStatusView(state.dnsStatus);
  14852. }
  14853. } catch (err) {
  14854. console.error('Failed to load DNS settings:', err);
  14855. }
  14856. }
  14857. function populateDNSSettingsForm(s) {
  14858. if (!s) return;
  14859. const dnsForm = document.getElementById('form-dns-settings');
  14860. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14861. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14862. if (dynamicEl) {
  14863. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14864. 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(' ');
  14865. } else {
  14866. dynamicEl.innerText = 'None';
  14867. }
  14868. }
  14869. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14870. if (isEditing) return;
  14871. const serversInput = document.getElementById('dns-servers-input');
  14872. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14873. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14874. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14875. const domainInput = document.getElementById('dns-domain-input');
  14876. if (domainInput) domainInput.value = s.domain || '';
  14877. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14878. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14879. }
  14880. function updateDNSStatusView(st) {
  14881. if (!st) return;
  14882. const preview = document.getElementById('dns-resolv-preview');
  14883. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14884. const pillText = document.getElementById('dns-live-status-text');
  14885. const pill = document.getElementById('dns-live-status-pill');
  14886. if (pill && pillText) {
  14887. if (st.service_running) {
  14888. 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';
  14889. pillText.innerText = 'DNS Service Active';
  14890. } else {
  14891. 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';
  14892. pillText.innerText = 'DNS Service Inactive';
  14893. }
  14894. }
  14895. }
  14896. function appendDNSPreset(preset) {
  14897. const input = document.getElementById('dns-servers-input');
  14898. if (!input) return;
  14899. const dnsForm = document.getElementById('form-dns-settings');
  14900. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14901. const current = input.value.trim();
  14902. if (!current) {
  14903. input.value = preset;
  14904. } else {
  14905. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14906. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14907. toAdd.forEach(ip => {
  14908. if (!existing.includes(ip)) existing.push(ip);
  14909. });
  14910. input.value = existing.join(', ');
  14911. }
  14912. }
  14913. async function saveDNSSettings(e) {
  14914. e.preventDefault();
  14915. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14916. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14917. if (servers.length === 0) {
  14918. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14919. return;
  14920. }
  14921. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14922. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14923. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14924. try {
  14925. const res = await fetch(`${API_BASE}/dns/settings`, {
  14926. method: 'POST',
  14927. headers: { 'Content-Type': 'application/json' },
  14928. body: JSON.stringify({
  14929. servers: servers,
  14930. cache_size: cacheSize,
  14931. domain: domain,
  14932. allow_remote_requests: allowRemote
  14933. })
  14934. });
  14935. const data = await res.json();
  14936. if (res.ok) {
  14937. const dnsForm = document.getElementById('form-dns-settings');
  14938. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14939. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14940. loadDNSSettings();
  14941. } else {
  14942. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14943. }
  14944. } catch (err) {
  14945. showToast('Error', err.message, 'error');
  14946. }
  14947. }
  14948. async function flushDNSCache() {
  14949. try {
  14950. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14951. if (res.ok) {
  14952. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14953. loadDNSSettings();
  14954. } else {
  14955. const err = await res.json();
  14956. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14957. }
  14958. } catch (err) {
  14959. showToast('Error', err.message, 'error');
  14960. }
  14961. }
  14962. function renderStaticDNSList() {
  14963. const tbody = document.getElementById('dns-static-tbody');
  14964. const empty = document.getElementById('dns-static-empty');
  14965. const badge = document.getElementById('dns-static-count-badge');
  14966. if (!tbody) return;
  14967. tbody.innerHTML = '';
  14968. const records = state.dnsStaticRecords || [];
  14969. if (badge) badge.innerText = `${records.length} Records`;
  14970. if (records.length === 0) {
  14971. empty?.classList.remove('hidden');
  14972. return;
  14973. }
  14974. empty?.classList.add('hidden');
  14975. records.forEach(rec => {
  14976. const tr = document.createElement('tr');
  14977. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14978. tr.innerHTML = `
  14979. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14980. <td class="py-2.5 px-4">
  14981. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14982. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14983. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14984. }">
  14985. ${rec.type || 'A'}
  14986. </span>
  14987. </td>
  14988. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14989. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14990. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14991. <td class="py-2.5 px-4">
  14992. <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'}">
  14993. ${rec.disabled ? 'Disabled' : 'Active'}
  14994. </span>
  14995. </td>
  14996. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14997. <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>
  14998. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14999. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15000. </td>
  15001. `;
  15002. tbody.appendChild(tr);
  15003. });
  15004. }
  15005. function openStaticDNSModal(id = null) {
  15006. const modal = document.getElementById('modal-static-dns');
  15007. const title = document.getElementById('modal-static-dns-title');
  15008. const form = document.getElementById('form-static-dns');
  15009. if (!modal || !form) return;
  15010. form.reset();
  15011. document.getElementById('modal-static-dns-id').value = '';
  15012. if (id) {
  15013. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15014. if (rec) {
  15015. if (title) title.innerText = 'Edit Static DNS Record';
  15016. document.getElementById('modal-static-dns-id').value = rec.id;
  15017. document.getElementById('modal-static-dns-name').value = rec.name;
  15018. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15019. document.getElementById('modal-static-dns-addr').value = rec.address;
  15020. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15021. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15022. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15023. }
  15024. } else {
  15025. if (title) title.innerText = 'Add Static DNS Record';
  15026. }
  15027. modal.classList.remove('hidden');
  15028. }
  15029. function closeStaticDNSModal() {
  15030. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15031. }
  15032. async function submitSaveStaticDNS(e) {
  15033. e.preventDefault();
  15034. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15035. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15036. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15037. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15038. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15039. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15040. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15041. if (!name || !address) {
  15042. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15043. return;
  15044. }
  15045. try {
  15046. const res = await fetch(`${API_BASE}/dns/static`, {
  15047. method: 'POST',
  15048. headers: { 'Content-Type': 'application/json' },
  15049. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15050. });
  15051. const data = await res.json();
  15052. if (res.ok) {
  15053. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15054. closeStaticDNSModal();
  15055. loadDNSSettings();
  15056. } else {
  15057. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15058. }
  15059. } catch (err) {
  15060. showToast('Error', err.message, 'error');
  15061. }
  15062. }
  15063. async function deleteStaticDNS(id) {
  15064. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15065. try {
  15066. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15067. if (res.ok) {
  15068. showToast('Deleted', 'Static DNS record deleted', 'success');
  15069. loadDNSSettings();
  15070. }
  15071. } catch (err) {
  15072. showToast('Error', err.message, 'error');
  15073. }
  15074. }
  15075. async function toggleStaticDNS(id, disabled) {
  15076. try {
  15077. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15078. method: 'POST',
  15079. headers: { 'Content-Type': 'application/json' },
  15080. body: JSON.stringify({ disabled })
  15081. });
  15082. if (res.ok) {
  15083. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15084. loadDNSSettings();
  15085. }
  15086. } catch (err) {
  15087. showToast('Error', err.message, 'error');
  15088. }
  15089. }
  15090. async function loadSystemSettings() {
  15091. try {
  15092. const sysForm = document.getElementById('form-system-settings');
  15093. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15094. const res = await fetch(`${API_BASE}/system/settings`);
  15095. if (res.ok) {
  15096. const data = await res.json();
  15097. if (!isEditing) {
  15098. const hostInput = document.getElementById('system-hostname-input');
  15099. if (hostInput) hostInput.value = data.hostname || '';
  15100. const tzInput = document.getElementById('system-timezone-input');
  15101. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15102. }
  15103. }
  15104. } catch (err) {
  15105. console.error('Failed to load system settings:', err);
  15106. }
  15107. }
  15108. async function saveSystemSettings(e) {
  15109. e.preventDefault();
  15110. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15111. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15112. try {
  15113. const res = await fetch(`${API_BASE}/system/settings`, {
  15114. method: 'POST',
  15115. headers: { 'Content-Type': 'application/json' },
  15116. body: JSON.stringify({ hostname, timezone })
  15117. });
  15118. const data = await res.json();
  15119. if (res.ok) {
  15120. const sysForm = document.getElementById('form-system-settings');
  15121. if (sysForm) sysForm.dataset.dirty = 'false';
  15122. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15123. const sideH = document.getElementById('side-hostname');
  15124. if (sideH) sideH.innerText = data.hostname;
  15125. } else {
  15126. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15127. }
  15128. } catch (err) {
  15129. showToast('Error', err.message, 'error');
  15130. }
  15131. }
  15132. // =============================================================================
  15133. // BACKUP & RESTORE MANAGER
  15134. // =============================================================================
  15135. state.selectedBackupFile = null;
  15136. state.inspectedBackupManifest = null;
  15137. state.pendingRestoreTarget = null;
  15138. state.backupsList = [];
  15139. async function exportBackupDownload() {
  15140. const btn = document.getElementById('btn-export-backup');
  15141. const commentInput = document.getElementById('backup-export-comment');
  15142. const comment = (commentInput?.value || '').trim();
  15143. const originalHtml = btn ? btn.innerHTML : '';
  15144. if (btn) {
  15145. btn.disabled = true;
  15146. 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...`;
  15147. }
  15148. try {
  15149. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15150. if (!res.ok) {
  15151. const err = await res.json().catch(() => ({}));
  15152. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15153. return;
  15154. }
  15155. const blob = await res.blob();
  15156. const disposition = res.headers.get('Content-Disposition') || '';
  15157. let filename = 'debtik-backup.zip';
  15158. const match = disposition.match(/filename="?([^";]+)"?/);
  15159. if (match && match[1]) {
  15160. filename = match[1];
  15161. }
  15162. const blobUrl = window.URL.createObjectURL(blob);
  15163. const a = document.createElement('a');
  15164. a.href = blobUrl;
  15165. a.download = filename;
  15166. document.body.appendChild(a);
  15167. a.click();
  15168. setTimeout(() => {
  15169. window.URL.revokeObjectURL(blobUrl);
  15170. a.remove();
  15171. }, 1000);
  15172. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15173. } catch (err) {
  15174. showToast('Export Error', err.message || 'Network error during download', 'error');
  15175. } finally {
  15176. if (btn) {
  15177. btn.disabled = false;
  15178. btn.innerHTML = originalHtml;
  15179. }
  15180. }
  15181. }
  15182. async function onBackupFileSelected(e) {
  15183. const file = e.target.files?.[0];
  15184. if (!file) return;
  15185. const label = document.getElementById('backup-file-label');
  15186. if (label) {
  15187. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15188. }
  15189. await inspectBackupFile(file);
  15190. }
  15191. async function inspectBackupFile(file) {
  15192. const preview = document.getElementById('backup-inspect-preview');
  15193. const restoreBtn = document.getElementById('btn-restore-backup');
  15194. const formData = new FormData();
  15195. formData.append('backup', file);
  15196. try {
  15197. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15198. method: 'POST',
  15199. body: formData
  15200. });
  15201. const data = await res.json();
  15202. if (!res.ok || !data.success || !data.manifest) {
  15203. if (preview) preview.classList.add('hidden');
  15204. if (restoreBtn) restoreBtn.disabled = true;
  15205. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15206. return;
  15207. }
  15208. const mf = data.manifest;
  15209. state.selectedBackupFile = file;
  15210. state.inspectedBackupManifest = mf;
  15211. const vEl = document.getElementById('backup-inspect-version');
  15212. const hEl = document.getElementById('backup-inspect-hostname');
  15213. const fEl = document.getElementById('backup-inspect-files');
  15214. const dEl = document.getElementById('backup-inspect-date');
  15215. const cEl = document.getElementById('backup-inspect-comment');
  15216. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15217. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15218. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15219. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15220. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15221. if (preview) preview.classList.remove('hidden');
  15222. if (restoreBtn) restoreBtn.disabled = false;
  15223. } catch (err) {
  15224. if (preview) preview.classList.add('hidden');
  15225. if (restoreBtn) restoreBtn.disabled = true;
  15226. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15227. }
  15228. }
  15229. function confirmRestoreBackup(localFilename = null) {
  15230. const modal = document.getElementById('modal-restore-confirm');
  15231. const details = document.getElementById('modal-restore-details');
  15232. const progress = document.getElementById('modal-restore-progress');
  15233. const cancelBtn = document.getElementById('btn-cancel-restore');
  15234. const execBtn = document.getElementById('btn-execute-restore');
  15235. if (progress) progress.classList.add('hidden');
  15236. if (cancelBtn) cancelBtn.disabled = false;
  15237. if (execBtn) {
  15238. execBtn.disabled = false;
  15239. execBtn.innerText = 'Yes, Restore & Reload';
  15240. }
  15241. if (localFilename) {
  15242. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15243. if (details) {
  15244. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15245. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15246. }
  15247. } else {
  15248. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15249. showToast('Error', 'Please select a valid backup archive first', 'error');
  15250. return;
  15251. }
  15252. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15253. const mf = state.inspectedBackupManifest;
  15254. if (details) {
  15255. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15256. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15257. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15258. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15259. }
  15260. }
  15261. if (modal) modal.classList.remove('hidden');
  15262. }
  15263. function closeRestoreModal() {
  15264. const modal = document.getElementById('modal-restore-confirm');
  15265. if (modal) modal.classList.add('hidden');
  15266. }
  15267. async function executeRestoreBackup() {
  15268. const target = state.pendingRestoreTarget;
  15269. if (!target) return;
  15270. const progress = document.getElementById('modal-restore-progress');
  15271. const progressText = document.getElementById('modal-restore-progress-text');
  15272. const cancelBtn = document.getElementById('btn-cancel-restore');
  15273. const execBtn = document.getElementById('btn-execute-restore');
  15274. if (cancelBtn) cancelBtn.disabled = true;
  15275. if (execBtn) execBtn.disabled = true;
  15276. if (progress) progress.classList.remove('hidden');
  15277. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15278. try {
  15279. let res;
  15280. if (target.type === 'file') {
  15281. const formData = new FormData();
  15282. formData.append('backup', target.file);
  15283. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15284. method: 'POST',
  15285. body: formData
  15286. });
  15287. } else {
  15288. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15289. method: 'POST'
  15290. });
  15291. }
  15292. const data = await res.json();
  15293. if (!res.ok || !data.success) {
  15294. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15295. if (cancelBtn) cancelBtn.disabled = false;
  15296. if (execBtn) execBtn.disabled = false;
  15297. if (progress) progress.classList.add('hidden');
  15298. return;
  15299. }
  15300. if (progressText) {
  15301. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15302. }
  15303. pollAfterRestoreReconnect();
  15304. } catch (err) {
  15305. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15306. if (cancelBtn) cancelBtn.disabled = false;
  15307. if (execBtn) execBtn.disabled = false;
  15308. if (progress) progress.classList.add('hidden');
  15309. }
  15310. }
  15311. function pollAfterRestoreReconnect() {
  15312. let attempts = 0;
  15313. const maxAttempts = 25;
  15314. const timer = setInterval(async () => {
  15315. attempts++;
  15316. try {
  15317. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15318. if (res.ok) {
  15319. clearInterval(timer);
  15320. closeRestoreModal();
  15321. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15322. setTimeout(() => {
  15323. window.location.reload();
  15324. }, 1200);
  15325. }
  15326. } catch (_) {
  15327. // Still restarting, retry
  15328. }
  15329. if (attempts >= maxAttempts) {
  15330. clearInterval(timer);
  15331. closeRestoreModal();
  15332. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15333. }
  15334. }, 1500);
  15335. }
  15336. async function loadBackupList() {
  15337. const tbody = document.getElementById('backups-table-tbody');
  15338. const empty = document.getElementById('backups-empty-state');
  15339. if (!tbody) return;
  15340. try {
  15341. const res = await fetch(`${API_BASE}/system/backups`);
  15342. if (!res.ok) return;
  15343. const list = await res.json();
  15344. state.backupsList = list || [];
  15345. renderBackupsTable(state.backupsList);
  15346. } catch (err) {
  15347. console.error('Failed to load backup list:', err);
  15348. }
  15349. }
  15350. function renderBackupsTable(backups) {
  15351. const tbody = document.getElementById('backups-table-tbody');
  15352. const empty = document.getElementById('backups-empty-state');
  15353. if (!tbody) return;
  15354. if (!backups || backups.length === 0) {
  15355. tbody.innerHTML = '';
  15356. if (empty) empty.classList.remove('hidden');
  15357. return;
  15358. }
  15359. if (empty) empty.classList.add('hidden');
  15360. tbody.innerHTML = backups.map(bk => {
  15361. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15362. const badge = isAuto
  15363. ? `<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>`
  15364. : `<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>`;
  15365. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15366. return `<tr class="hover:bg-slate-800/40 transition">
  15367. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15368. ${badge}
  15369. <span>${escapeHtml(bk.filename)}</span>
  15370. </td>
  15371. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15372. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15373. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15374. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15375. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15376. <td class="py-3 px-4 text-right space-x-2">
  15377. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15378. 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">
  15379. Download
  15380. </button>
  15381. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15382. 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">
  15383. Restore
  15384. </button>
  15385. </td>
  15386. </tr>`;
  15387. }).join('');
  15388. }
  15389. async function downloadLocalBackup(filename) {
  15390. try {
  15391. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15392. if (!res.ok) {
  15393. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15394. return;
  15395. }
  15396. const blob = await res.blob();
  15397. const blobUrl = window.URL.createObjectURL(blob);
  15398. const a = document.createElement('a');
  15399. a.href = blobUrl;
  15400. a.download = filename;
  15401. document.body.appendChild(a);
  15402. a.click();
  15403. setTimeout(() => {
  15404. window.URL.revokeObjectURL(blobUrl);
  15405. a.remove();
  15406. }, 1000);
  15407. } catch (err) {
  15408. showToast('Download Error', err.message, 'error');
  15409. }
  15410. }
  15411. // =============================================================================
  15412. // AUTHENTICATION & USER MANAGER
  15413. // =============================================================================
  15414. async function checkAuthStatus() {
  15415. try {
  15416. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15417. headers: {
  15418. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15419. }
  15420. });
  15421. if (res.ok) {
  15422. const user = await res.json();
  15423. state.currentUser = user;
  15424. updateUserProfileHeader(user);
  15425. hideLoginScreen();
  15426. state.isPolling = true;
  15427. fetchData();
  15428. initLiveTrafficStream();
  15429. return true;
  15430. } else {
  15431. showLoginScreen(false);
  15432. return false;
  15433. }
  15434. } catch (err) {
  15435. showLoginScreen(false);
  15436. return false;
  15437. }
  15438. }
  15439. function showLoginScreen(isExpired = false) {
  15440. const el = document.getElementById('login-screen');
  15441. if (el) el.classList.remove('hidden');
  15442. const errEl = document.getElementById('login-error');
  15443. const errTxt = document.getElementById('login-error-text');
  15444. if (isExpired && errEl && errTxt) {
  15445. errTxt.innerText = 'Session expired. Please sign in again.';
  15446. errEl.classList.remove('hidden');
  15447. } else if (errEl) {
  15448. errEl.classList.add('hidden');
  15449. }
  15450. const pwInput = document.getElementById('login-password');
  15451. if (pwInput) pwInput.value = '';
  15452. const userInput = document.getElementById('login-username');
  15453. if (userInput && !userInput.value) userInput.focus();
  15454. else if (pwInput) pwInput.focus();
  15455. }
  15456. function hideLoginScreen() {
  15457. const el = document.getElementById('login-screen');
  15458. if (el) el.classList.add('hidden');
  15459. const errEl = document.getElementById('login-error');
  15460. if (errEl) errEl.classList.add('hidden');
  15461. }
  15462. async function handleLoginSubmit(event) {
  15463. event.preventDefault();
  15464. const username = (document.getElementById('login-username')?.value || '').trim();
  15465. const password = document.getElementById('login-password')?.value || '';
  15466. const errEl = document.getElementById('login-error');
  15467. const errTxt = document.getElementById('login-error-text');
  15468. const btn = document.getElementById('login-submit-btn');
  15469. const btnText = document.getElementById('login-btn-text');
  15470. const spinner = document.getElementById('login-btn-spinner');
  15471. if (!username || !password) {
  15472. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15473. if (errEl) errEl.classList.remove('hidden');
  15474. return;
  15475. }
  15476. if (errEl) errEl.classList.add('hidden');
  15477. if (btn) btn.disabled = true;
  15478. if (btnText) btnText.innerText = 'Authenticating...';
  15479. if (spinner) spinner.classList.remove('hidden');
  15480. try {
  15481. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15482. method: 'POST',
  15483. headers: { 'Content-Type': 'application/json' },
  15484. body: JSON.stringify({ username, password })
  15485. });
  15486. const data = await res.json();
  15487. if (res.ok && data.success) {
  15488. localStorage.setItem('debtik_token', data.token);
  15489. state.currentUser = data.user;
  15490. updateUserProfileHeader(data.user);
  15491. hideLoginScreen();
  15492. state.isPolling = true;
  15493. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15494. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15495. navigate(hash);
  15496. fetchData();
  15497. initLiveTrafficStream();
  15498. // Ensure background telemetry polling is active
  15499. if (!window._telemetryInterval) {
  15500. window._telemetryInterval = setInterval(() => {
  15501. if (state.isPolling && state.currentUser && !document.hidden) {
  15502. fetchData(false);
  15503. }
  15504. }, 5000);
  15505. }
  15506. } else {
  15507. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15508. if (errEl) errEl.classList.remove('hidden');
  15509. }
  15510. } catch (err) {
  15511. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15512. if (errEl) errEl.classList.remove('hidden');
  15513. } finally {
  15514. if (btn) btn.disabled = false;
  15515. if (btnText) btnText.innerText = 'Sign In to Controller';
  15516. if (spinner) spinner.classList.add('hidden');
  15517. }
  15518. }
  15519. async function handleLogoutClick() {
  15520. try {
  15521. await originalFetch(`${API_BASE}/auth/logout`, {
  15522. method: 'POST',
  15523. headers: {
  15524. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15525. }
  15526. });
  15527. } catch (e) {}
  15528. stopSessionPolling();
  15529. localStorage.removeItem('debtik_token');
  15530. state.currentUser = null;
  15531. state.isPolling = false;
  15532. if (window._telemetryInterval) {
  15533. clearInterval(window._telemetryInterval);
  15534. window._telemetryInterval = null;
  15535. }
  15536. if (trafficEventSource) {
  15537. trafficEventSource.close();
  15538. trafficEventSource = null;
  15539. }
  15540. if (trafficPollFallback) {
  15541. clearInterval(trafficPollFallback);
  15542. trafficPollFallback = null;
  15543. }
  15544. showLoginScreen(false);
  15545. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15546. }
  15547. function togglePasswordVisibility(id) {
  15548. const input = document.getElementById(id);
  15549. if (!input) return;
  15550. input.type = input.type === 'password' ? 'text' : 'password';
  15551. }
  15552. function toggleUserMenu() {
  15553. const menu = document.getElementById('user-menu-dropdown');
  15554. if (menu) menu.classList.toggle('hidden');
  15555. }
  15556. function closeUserMenu() {
  15557. const menu = document.getElementById('user-menu-dropdown');
  15558. if (menu) menu.classList.add('hidden');
  15559. }
  15560. // Close user menu on outside click
  15561. document.addEventListener('click', (e) => {
  15562. const menu = document.getElementById('user-menu-dropdown');
  15563. if (!menu || menu.classList.contains('hidden')) return;
  15564. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15565. menu.classList.add('hidden');
  15566. }
  15567. });
  15568. function updateUserProfileHeader(user) {
  15569. if (!user) return;
  15570. const navName = document.getElementById('nav-user-name');
  15571. if (navName) navName.innerText = user.username;
  15572. const dropName = document.getElementById('dropdown-user-name');
  15573. if (dropName) dropName.innerText = user.username;
  15574. const navRole = document.getElementById('nav-user-role');
  15575. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15576. const navAvatar = document.getElementById('nav-user-avatar');
  15577. if (navAvatar) {
  15578. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15579. navAvatar.innerText = initials;
  15580. }
  15581. const statCurUser = document.getElementById('stat-current-user');
  15582. if (statCurUser) statCurUser.innerText = user.username;
  15583. const statCurRole = document.getElementById('stat-current-role');
  15584. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15585. // Role permissions UI visibility: hide user management for non-admins
  15586. const isFullAdmin = user.role === 'full';
  15587. const navUsers = document.getElementById('nav-users');
  15588. if (navUsers) {
  15589. if (isFullAdmin) navUsers.classList.remove('hidden');
  15590. else navUsers.classList.add('hidden');
  15591. }
  15592. const dropdownUsers = document.getElementById('dropdown-item-users');
  15593. if (dropdownUsers) {
  15594. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15595. else dropdownUsers.classList.add('hidden');
  15596. }
  15597. }
  15598. // ================= User Management CRUD =================
  15599. async function loadUsers(isManual = false) {
  15600. try {
  15601. const res = await fetch(`${API_BASE}/users`);
  15602. if (res.status === 403) {
  15603. const tbody = document.getElementById('users-table-tbody');
  15604. if (tbody) {
  15605. tbody.innerHTML = `
  15606. <tr>
  15607. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15608. <div class="inline-flex items-center gap-2">
  15609. <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>
  15610. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15611. </div>
  15612. </td>
  15613. </tr>
  15614. `;
  15615. }
  15616. return;
  15617. }
  15618. if (res.ok) {
  15619. state.users = await res.json();
  15620. renderUsersTable();
  15621. const totalUsers = document.getElementById('stat-total-users');
  15622. if (totalUsers) totalUsers.innerText = state.users.length;
  15623. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15624. const adminUsers = document.getElementById('stat-admin-users');
  15625. if (adminUsers) adminUsers.innerText = adminCount;
  15626. const badgeCount = document.getElementById('badge-users-count');
  15627. if (badgeCount) badgeCount.innerText = state.users.length;
  15628. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15629. }
  15630. } catch (err) {
  15631. console.error('Failed to load users:', err);
  15632. }
  15633. }
  15634. function renderUsersTable() {
  15635. const tbody = document.getElementById('users-table-tbody');
  15636. const emptyState = document.getElementById('users-empty-state');
  15637. if (!tbody) return;
  15638. tbody.innerHTML = '';
  15639. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15640. const filtered = (state.users || []).filter(u => {
  15641. if (!query) return true;
  15642. return u.username.toLowerCase().includes(query) ||
  15643. (u.role || '').toLowerCase().includes(query) ||
  15644. (u.comment || '').toLowerCase().includes(query);
  15645. });
  15646. if (filtered.length === 0) {
  15647. if (emptyState) emptyState.classList.remove('hidden');
  15648. return;
  15649. }
  15650. if (emptyState) emptyState.classList.add('hidden');
  15651. const currentAuthUser = state.currentUser?.username || '';
  15652. filtered.forEach(u => {
  15653. const isSelf = u.username === currentAuthUser;
  15654. const isFull = u.role === 'full';
  15655. const isWrite = u.role === 'write';
  15656. 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>`;
  15657. if (isFull) {
  15658. 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>`;
  15659. } else if (isWrite) {
  15660. 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>`;
  15661. }
  15662. const statusBadge = u.disabled
  15663. ? `<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>`
  15664. : `<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>`;
  15665. let lastLoginText = 'Never';
  15666. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15667. const dt = new Date(u.last_login_at);
  15668. lastLoginText = dt.toLocaleString();
  15669. }
  15670. const initials = u.username.slice(0, 2).toUpperCase();
  15671. const tr = document.createElement('tr');
  15672. tr.className = 'hover:bg-slate-800/40 transition group';
  15673. tr.innerHTML = `
  15674. <td class="py-3 px-4">
  15675. <div class="flex items-center gap-3">
  15676. <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">
  15677. ${initials}
  15678. </div>
  15679. <div>
  15680. <div class="font-bold text-white text-xs flex items-center gap-2">
  15681. <span>${escapeHtml(u.username)}</span>
  15682. ${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>' : ''}
  15683. </div>
  15684. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15685. </div>
  15686. </div>
  15687. </td>
  15688. <td class="py-3 px-4 font-sans">
  15689. ${roleBadge}
  15690. </td>
  15691. <td class="py-3 px-4 font-sans">
  15692. ${statusBadge}
  15693. </td>
  15694. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15695. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15696. </td>
  15697. <td class="py-3 px-4 text-slate-400 text-xs">
  15698. ${lastLoginText}
  15699. </td>
  15700. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15701. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15702. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15703. <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>
  15704. </button>
  15705. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15706. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15707. <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>
  15708. </button>
  15709. ${!isSelf ? `
  15710. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15711. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15712. <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>
  15713. </button>
  15714. ` : ''}
  15715. </td>
  15716. `;
  15717. tbody.appendChild(tr);
  15718. });
  15719. }
  15720. function openAddUserModal() {
  15721. document.getElementById('user-add-username').value = '';
  15722. document.getElementById('user-add-password').value = '';
  15723. document.getElementById('user-add-confirm').value = '';
  15724. document.getElementById('user-add-role').value = 'full';
  15725. document.getElementById('user-add-comment').value = '';
  15726. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15727. document.getElementById('user-add-username')?.focus();
  15728. }
  15729. function closeAddUserModal() {
  15730. document.getElementById('modal-add-user')?.classList.add('hidden');
  15731. }
  15732. async function submitAddUser(event) {
  15733. event.preventDefault();
  15734. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15735. const password = document.getElementById('user-add-password')?.value || '';
  15736. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15737. const role = document.getElementById('user-add-role')?.value || 'full';
  15738. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15739. if (password !== confirm) {
  15740. showToast('Validation Error', 'Passwords do not match', 'warning');
  15741. return;
  15742. }
  15743. if (password.length < 4) {
  15744. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15745. return;
  15746. }
  15747. try {
  15748. const res = await fetch(`${API_BASE}/users`, {
  15749. method: 'POST',
  15750. headers: { 'Content-Type': 'application/json' },
  15751. body: JSON.stringify({ username, password, role, comment })
  15752. });
  15753. const data = await res.json();
  15754. if (res.ok) {
  15755. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15756. closeAddUserModal();
  15757. loadUsers(false);
  15758. } else {
  15759. showToast('Error', data.message || 'Failed to create user', 'error');
  15760. }
  15761. } catch (err) {
  15762. showToast('Error', err.message, 'error');
  15763. }
  15764. }
  15765. function openEditUserModal(username) {
  15766. const user = (state.users || []).find(u => u.username === username);
  15767. if (!user) return;
  15768. document.getElementById('user-edit-username').value = user.username;
  15769. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15770. document.getElementById('user-edit-role').value = user.role || 'read';
  15771. document.getElementById('user-edit-comment').value = user.comment || '';
  15772. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15773. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15774. }
  15775. function closeEditUserModal() {
  15776. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15777. }
  15778. async function submitEditUser(event) {
  15779. event.preventDefault();
  15780. const username = document.getElementById('user-edit-username')?.value;
  15781. const role = document.getElementById('user-edit-role')?.value || 'read';
  15782. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15783. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15784. try {
  15785. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15786. method: 'PUT',
  15787. headers: { 'Content-Type': 'application/json' },
  15788. body: JSON.stringify({ role, comment, disabled })
  15789. });
  15790. const data = await res.json();
  15791. if (res.ok) {
  15792. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15793. closeEditUserModal();
  15794. loadUsers(false);
  15795. // If updated own role/disabled status, refresh self profile
  15796. if (username === state.currentUser?.username) {
  15797. checkAuthStatus();
  15798. }
  15799. } else {
  15800. showToast('Error', data.message || 'Failed to update user', 'error');
  15801. }
  15802. } catch (err) {
  15803. showToast('Error', err.message, 'error');
  15804. }
  15805. }
  15806. function openAdminResetPasswordModal(username) {
  15807. document.getElementById('admin-reset-username').value = username;
  15808. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15809. document.getElementById('admin-reset-new-pw').value = '';
  15810. document.getElementById('admin-reset-confirm-pw').value = '';
  15811. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15812. document.getElementById('admin-reset-new-pw')?.focus();
  15813. }
  15814. function closeAdminResetPasswordModal() {
  15815. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15816. }
  15817. async function submitAdminResetPassword(event) {
  15818. event.preventDefault();
  15819. const username = document.getElementById('admin-reset-username')?.value;
  15820. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15821. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15822. if (newPassword !== confirm) {
  15823. showToast('Validation Error', 'Passwords do not match', 'warning');
  15824. return;
  15825. }
  15826. if (newPassword.length < 4) {
  15827. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15828. return;
  15829. }
  15830. try {
  15831. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15832. method: 'POST',
  15833. headers: { 'Content-Type': 'application/json' },
  15834. body: JSON.stringify({ new_password: newPassword })
  15835. });
  15836. const data = await res.json();
  15837. if (res.ok) {
  15838. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15839. closeAdminResetPasswordModal();
  15840. } else {
  15841. showToast('Error', data.message || 'Failed to reset password', 'error');
  15842. }
  15843. } catch (err) {
  15844. showToast('Error', err.message, 'error');
  15845. }
  15846. }
  15847. async function deleteUser(username) {
  15848. if (username === state.currentUser?.username) {
  15849. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15850. return;
  15851. }
  15852. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15853. return;
  15854. }
  15855. try {
  15856. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15857. method: 'DELETE'
  15858. });
  15859. const data = await res.json();
  15860. if (res.ok) {
  15861. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15862. loadUsers(false);
  15863. } else {
  15864. showToast('Error', data.message || 'Failed to delete user', 'error');
  15865. }
  15866. } catch (err) {
  15867. showToast('Error', err.message, 'error');
  15868. }
  15869. }
  15870. function openSelfPasswordModal() {
  15871. document.getElementById('self-current-password').value = '';
  15872. document.getElementById('self-new-password').value = '';
  15873. document.getElementById('self-confirm-password').value = '';
  15874. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15875. document.getElementById('self-current-password')?.focus();
  15876. }
  15877. function closeSelfPasswordModal() {
  15878. document.getElementById('modal-self-password')?.classList.add('hidden');
  15879. }
  15880. async function submitSelfPassword(event) {
  15881. event.preventDefault();
  15882. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15883. const newPassword = document.getElementById('self-new-password')?.value || '';
  15884. const confirm = document.getElementById('self-confirm-password')?.value || '';
  15885. if (newPassword !== confirm) {
  15886. showToast('Validation Error', 'New passwords do not match', 'warning');
  15887. return;
  15888. }
  15889. if (newPassword.length < 4) {
  15890. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15891. return;
  15892. }
  15893. try {
  15894. const res = await fetch(`${API_BASE}/auth/change-password`, {
  15895. method: 'POST',
  15896. headers: { 'Content-Type': 'application/json' },
  15897. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15898. });
  15899. const data = await res.json();
  15900. if (res.ok) {
  15901. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15902. closeSelfPasswordModal();
  15903. } else {
  15904. showToast('Error', data.message || 'Failed to change password', 'error');
  15905. }
  15906. } catch (err) {
  15907. showToast('Error', err.message, 'error');
  15908. }
  15909. }
  15910. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15911. state.services = [];
  15912. async function loadServices(manual = false) {
  15913. try {
  15914. const res = await fetch(`${API_BASE}/system/services`);
  15915. if (!res.ok) throw new Error('Failed to load services');
  15916. const data = await res.json();
  15917. state.services = data || [];
  15918. renderServicesTable();
  15919. updateCertificatesBadges();
  15920. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15921. } catch (err) {
  15922. if (manual) showToast('Error', err.message, 'error');
  15923. }
  15924. }
  15925. function renderServicesTable() {
  15926. const tbody = document.getElementById('services-table-body');
  15927. if (!tbody) return;
  15928. if (!state.services || state.services.length === 0) {
  15929. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15930. return;
  15931. }
  15932. tbody.innerHTML = state.services.map(s => {
  15933. const isOff = s.disabled;
  15934. const statusBadge = isOff
  15935. ? '<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>'
  15936. : '<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>';
  15937. const toggleBtn = isOff
  15938. ? `<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>`
  15939. : `<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>`;
  15940. let certBadge = '';
  15941. if (s.name === 'www-ssl') {
  15942. if (s.certificate) {
  15943. 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>`;
  15944. } else {
  15945. 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>`;
  15946. }
  15947. }
  15948. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15949. return `
  15950. <tr class="hover:bg-slate-800/40 transition">
  15951. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15952. <td class="py-3 px-4">
  15953. <div class="flex items-center gap-2">
  15954. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15955. <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">
  15956. <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>
  15957. </button>
  15958. </div>
  15959. </td>
  15960. <td class="py-3 px-4">${statusBadge}</td>
  15961. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  15962. <td class="py-3 px-4 text-right">
  15963. <div class="flex items-center justify-end gap-2">
  15964. <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">
  15965. <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>
  15966. <span>Edit</span>
  15967. </button>
  15968. ${toggleBtn}
  15969. </div>
  15970. </td>
  15971. </tr>
  15972. `;
  15973. }).join('');
  15974. }
  15975. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  15976. document.getElementById('modal-service-name').value = serviceName;
  15977. document.getElementById('modal-service-disabled').value = String(isDisabled);
  15978. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  15979. document.getElementById('modal-service-port').value = currentPort;
  15980. const hintEl = document.getElementById('modal-service-port-hint');
  15981. const warnEl = document.getElementById('modal-service-warning');
  15982. const certGroup = document.getElementById('modal-service-cert-group');
  15983. const certSelect = document.getElementById('modal-service-cert-select');
  15984. if (serviceName === 'www') {
  15985. hintEl.textContent = 'Default HTTP web port: 80';
  15986. warnEl.classList.remove('hidden');
  15987. certGroup.classList.add('hidden');
  15988. } else if (serviceName === 'www-ssl') {
  15989. hintEl.textContent = 'Default HTTPS web port: 443';
  15990. warnEl.classList.remove('hidden');
  15991. certGroup.classList.remove('hidden');
  15992. const populateCertOptions = (certs) => {
  15993. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15994. (certs || []).forEach(c => {
  15995. const opt = document.createElement('option');
  15996. opt.value = c.name;
  15997. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15998. if (c.name === currentCert) opt.selected = true;
  15999. certSelect.appendChild(opt);
  16000. });
  16001. };
  16002. if (state.certificates && state.certificates.length > 0) {
  16003. populateCertOptions(state.certificates);
  16004. } else {
  16005. loadCertificates(false).then(() => {
  16006. populateCertOptions(state.certificates);
  16007. });
  16008. }
  16009. } else if (serviceName === 'telnet') {
  16010. hintEl.textContent = 'Default Telnet console port: 8282';
  16011. warnEl.classList.add('hidden');
  16012. certGroup.classList.add('hidden');
  16013. } else if (serviceName === 'ssh') {
  16014. hintEl.textContent = 'Default SSH port: 2222';
  16015. warnEl.classList.add('hidden');
  16016. certGroup.classList.add('hidden');
  16017. } else {
  16018. hintEl.textContent = '';
  16019. warnEl.classList.add('hidden');
  16020. certGroup.classList.add('hidden');
  16021. }
  16022. const modal = document.getElementById('modal-service-edit');
  16023. modal.classList.remove('hidden');
  16024. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16025. }
  16026. function closeEditServiceModal() {
  16027. const modal = document.getElementById('modal-service-edit');
  16028. if (modal) modal.classList.add('hidden');
  16029. }
  16030. async function submitSaveServicePort(event) {
  16031. event.preventDefault();
  16032. const name = document.getElementById('modal-service-name').value;
  16033. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16034. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16035. if (isNaN(port) || port < 1 || port > 65535) {
  16036. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16037. return;
  16038. }
  16039. const certSelect = document.getElementById('modal-service-cert-select');
  16040. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16041. try {
  16042. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16043. method: 'POST',
  16044. headers: { 'Content-Type': 'application/json' },
  16045. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16046. });
  16047. if (!res.ok) {
  16048. const errData = await res.json();
  16049. throw new Error(errData.message || 'Failed to update service settings');
  16050. }
  16051. closeEditServiceModal();
  16052. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16053. await loadServices();
  16054. } catch (err) {
  16055. showToast('Error', err.message, 'error');
  16056. }
  16057. }
  16058. async function toggleServiceState(serviceName, newDisabled) {
  16059. if (serviceName === 'www' && newDisabled) {
  16060. 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?")) {
  16061. return;
  16062. }
  16063. }
  16064. if (serviceName === 'www-ssl' && !newDisabled) {
  16065. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16066. if (!sslSvc || !sslSvc.certificate) {
  16067. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16068. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16069. return;
  16070. }
  16071. }
  16072. try {
  16073. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16074. method: 'POST',
  16075. headers: { 'Content-Type': 'application/json' },
  16076. body: JSON.stringify({ disabled: newDisabled })
  16077. });
  16078. if (!res.ok) {
  16079. const errData = await res.json();
  16080. throw new Error(errData.message || 'Failed to update service');
  16081. }
  16082. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16083. await loadServices();
  16084. } catch (err) {
  16085. showToast('Error', err.message, 'error');
  16086. }
  16087. }
  16088. // ==================== SYSTEM LOGS (/log) ====================
  16089. state.logs = [];
  16090. let logsTimer = null;
  16091. async function loadLogs(manual = false) {
  16092. const limitEl = document.getElementById('logs-limit-select');
  16093. const limit = limitEl ? limitEl.value : '100';
  16094. try {
  16095. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16096. if (!res.ok) throw new Error('Failed to load logs');
  16097. const data = await res.json();
  16098. state.logs = data.logs || [];
  16099. renderLogsTable();
  16100. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16101. } catch (err) {
  16102. if (manual) showToast('Error', err.message, 'error');
  16103. }
  16104. // Setup auto-refresh if enabled and on logs tab
  16105. if (!logsTimer && state.currentUser) {
  16106. logsTimer = setInterval(() => {
  16107. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16108. const auto = document.getElementById('logs-auto-refresh');
  16109. if (auto && auto.checked) {
  16110. loadLogs(false);
  16111. }
  16112. }
  16113. }, 3000);
  16114. }
  16115. }
  16116. function renderLogsTable() {
  16117. const tbody = document.getElementById('logs-table-body');
  16118. if (!tbody) return;
  16119. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16120. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16121. const filtered = state.logs.filter(entry => {
  16122. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16123. return false;
  16124. }
  16125. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16126. return false;
  16127. }
  16128. return true;
  16129. });
  16130. if (filtered.length === 0) {
  16131. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16132. return;
  16133. }
  16134. tbody.innerHTML = filtered.map(l => {
  16135. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16136. const topLower = l.topics.toLowerCase();
  16137. if (topLower.includes('auth')) {
  16138. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16139. } else if (topLower.includes('dhcp')) {
  16140. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16141. } else if (topLower.includes('route')) {
  16142. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16143. } else if (topLower.includes('firewall')) {
  16144. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16145. } else if (topLower.includes('error')) {
  16146. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16147. } else if (topLower.includes('system')) {
  16148. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16149. }
  16150. const d = new Date(l.time);
  16151. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16152. return `
  16153. <tr class="hover:bg-slate-800/40 transition">
  16154. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16155. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16156. <td class="py-2 px-3 whitespace-nowrap">
  16157. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16158. </td>
  16159. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16160. </tr>
  16161. `;
  16162. }).join('');
  16163. }
  16164. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16165. state.certificates = [];
  16166. async function loadCertificates(manual = false) {
  16167. try {
  16168. const res = await fetch(`${API_BASE}/certificates`);
  16169. if (!res.ok) throw new Error('Failed to load certificates');
  16170. state.certificates = await res.json() || [];
  16171. updateCertificatesBadges();
  16172. renderCertificatesTable();
  16173. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16174. } catch (err) {
  16175. if (manual) showToast('Error', err.message, 'error');
  16176. }
  16177. }
  16178. function updateCertificatesBadges() {
  16179. const total = (state.certificates || []).length;
  16180. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16181. const bCount = document.getElementById('badge-certs-count');
  16182. if (bCount) bCount.innerText = total;
  16183. const kpiTotal = document.getElementById('kpi-certs-total');
  16184. if (kpiTotal) kpiTotal.innerText = total;
  16185. const kpiCA = document.getElementById('kpi-certs-ca');
  16186. if (kpiCA) kpiCA.innerText = caCount;
  16187. const kpiHttps = document.getElementById('kpi-https-status');
  16188. if (kpiHttps) {
  16189. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16190. if (sslSvc) {
  16191. if (!sslSvc.disabled) {
  16192. 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>`;
  16193. } else {
  16194. 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>`;
  16195. }
  16196. }
  16197. }
  16198. }
  16199. function renderCertificatesTable() {
  16200. const tbody = document.getElementById('certs-table-body');
  16201. if (!tbody) return;
  16202. if (!state.certificates || state.certificates.length === 0) {
  16203. 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>';
  16204. return;
  16205. }
  16206. tbody.innerHTML = state.certificates.map(c => {
  16207. let typeBadge = '';
  16208. if (c.is_ca) {
  16209. 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>';
  16210. } else if (c.type === 'acme') {
  16211. 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>';
  16212. } else if (c.issuer && c.issuer !== c.common_name) {
  16213. 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>';
  16214. } else {
  16215. 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>';
  16216. }
  16217. const sansHtml = (c.sans && c.sans.length > 0)
  16218. ? 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('')
  16219. : '<span class="text-slate-500">-</span>';
  16220. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16221. let validStr = '-';
  16222. let validBadge = '';
  16223. if (validTo && !isNaN(validTo.getTime())) {
  16224. const now = new Date();
  16225. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16226. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16227. if (daysLeft < 0) {
  16228. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16229. } else if (daysLeft < 30) {
  16230. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16231. } else {
  16232. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16233. }
  16234. }
  16235. return `
  16236. <tr class="hover:bg-slate-800/40 transition">
  16237. <td class="py-3 px-4">${typeBadge}</td>
  16238. <td class="py-3 px-4">
  16239. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16240. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16241. </td>
  16242. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16243. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16244. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16245. <span>${validStr}</span> ${validBadge}
  16246. ${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>` : ''}
  16247. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16248. </td>
  16249. <td class="py-3 px-4 text-right whitespace-nowrap">
  16250. <div class="flex items-center justify-end gap-1.5">
  16251. <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">
  16252. <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>
  16253. <span>View</span>
  16254. </button>
  16255. <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">
  16256. <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>
  16257. </button>
  16258. </div>
  16259. </td>
  16260. </tr>
  16261. `;
  16262. }).join('');
  16263. }
  16264. // Create CA
  16265. function openCreateCAModal() {
  16266. document.getElementById('form-create-ca').reset();
  16267. document.getElementById('ca-days').value = '3650';
  16268. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16269. document.getElementById('ca-country').value = 'GR';
  16270. document.getElementById('ca-key-type').value = 'RSA-2048';
  16271. document.getElementById('modal-create-ca').classList.remove('hidden');
  16272. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16273. }
  16274. function closeCreateCAModal() {
  16275. document.getElementById('modal-create-ca').classList.add('hidden');
  16276. }
  16277. async function submitCreateCA(event) {
  16278. event.preventDefault();
  16279. const payload = {
  16280. name: document.getElementById('ca-name').value.trim(),
  16281. common_name: document.getElementById('ca-cn').value.trim(),
  16282. organization: document.getElementById('ca-org').value.trim(),
  16283. country: document.getElementById('ca-country').value.trim(),
  16284. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16285. key_type: document.getElementById('ca-key-type').value
  16286. };
  16287. try {
  16288. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16289. method: 'POST',
  16290. headers: { 'Content-Type': 'application/json' },
  16291. body: JSON.stringify(payload)
  16292. });
  16293. if (!res.ok) {
  16294. const errData = await res.json();
  16295. throw new Error(errData.message || 'Failed to create CA');
  16296. }
  16297. closeCreateCAModal();
  16298. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16299. await loadCertificates();
  16300. } catch (err) {
  16301. showToast('Error', err.message, 'error');
  16302. }
  16303. }
  16304. // Create Cert
  16305. function openCreateCertModal() {
  16306. document.getElementById('form-create-cert').reset();
  16307. document.getElementById('cert-days').value = '730';
  16308. document.getElementById('cert-key-type').value = 'RSA-2048';
  16309. const caSelect = document.getElementById('cert-ca-select');
  16310. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16311. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16312. const opt = document.createElement('option');
  16313. opt.value = ca.name;
  16314. opt.textContent = `${ca.name} (${ca.common_name})`;
  16315. caSelect.appendChild(opt);
  16316. });
  16317. document.getElementById('modal-create-cert').classList.remove('hidden');
  16318. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16319. }
  16320. function closeCreateCertModal() {
  16321. document.getElementById('modal-create-cert').classList.add('hidden');
  16322. }
  16323. async function submitCreateCert(event) {
  16324. event.preventDefault();
  16325. const rawSans = document.getElementById('cert-sans').value;
  16326. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16327. const caName = document.getElementById('cert-ca-select').value;
  16328. const payload = {
  16329. name: document.getElementById('cert-name').value.trim(),
  16330. common_name: document.getElementById('cert-cn').value.trim(),
  16331. ca_name: caName,
  16332. sans: sansList,
  16333. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16334. key_type: document.getElementById('cert-key-type').value,
  16335. is_server: true
  16336. };
  16337. try {
  16338. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16339. method: 'POST',
  16340. headers: { 'Content-Type': 'application/json' },
  16341. body: JSON.stringify(payload)
  16342. });
  16343. if (!res.ok) {
  16344. const errData = await res.json();
  16345. throw new Error(errData.message || 'Failed to issue certificate');
  16346. }
  16347. closeCreateCertModal();
  16348. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16349. await loadCertificates();
  16350. } catch (err) {
  16351. showToast('Error', err.message, 'error');
  16352. }
  16353. }
  16354. // Let's Encrypt
  16355. function openLetsEncryptModal() {
  16356. document.getElementById('form-letsencrypt').reset();
  16357. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16358. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16359. }
  16360. function closeLetsEncryptModal() {
  16361. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16362. }
  16363. async function submitLetsEncrypt(event) {
  16364. event.preventDefault();
  16365. const domain = document.getElementById('le-domain').value.trim();
  16366. const email = document.getElementById('le-email').value.trim();
  16367. let name = document.getElementById('le-name').value.trim();
  16368. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16369. const staging = document.getElementById('le-staging').checked;
  16370. const btn = document.getElementById('btn-submit-letsencrypt');
  16371. const origBtnHtml = btn.innerHTML;
  16372. btn.disabled = true;
  16373. 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>`;
  16374. try {
  16375. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16376. method: 'POST',
  16377. headers: { 'Content-Type': 'application/json' },
  16378. body: JSON.stringify({
  16379. name: name,
  16380. domain: domain,
  16381. email: email,
  16382. staging: staging
  16383. })
  16384. });
  16385. if (!res.ok) {
  16386. const errData = await res.json();
  16387. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16388. }
  16389. closeLetsEncryptModal();
  16390. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16391. await loadCertificates();
  16392. } catch (err) {
  16393. showToast('Let\'s Encrypt Error', err.message, 'error');
  16394. } finally {
  16395. btn.disabled = false;
  16396. btn.innerHTML = origBtnHtml;
  16397. }
  16398. }
  16399. // Import Cert
  16400. function openImportCertModal() {
  16401. document.getElementById('form-import-cert').reset();
  16402. document.getElementById('modal-import-cert').classList.remove('hidden');
  16403. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16404. }
  16405. function closeImportCertModal() {
  16406. document.getElementById('modal-import-cert').classList.add('hidden');
  16407. }
  16408. async function submitImportCert(event) {
  16409. event.preventDefault();
  16410. const payload = {
  16411. name: document.getElementById('import-cert-name').value.trim(),
  16412. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16413. key_pem: document.getElementById('import-key-pem').value.trim()
  16414. };
  16415. try {
  16416. const res = await fetch(`${API_BASE}/certificates/import`, {
  16417. method: 'POST',
  16418. headers: { 'Content-Type': 'application/json' },
  16419. body: JSON.stringify(payload)
  16420. });
  16421. if (!res.ok) {
  16422. const errData = await res.json();
  16423. throw new Error(errData.message || 'Failed to import certificate');
  16424. }
  16425. closeImportCertModal();
  16426. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16427. await loadCertificates();
  16428. } catch (err) {
  16429. showToast('Error', err.message, 'error');
  16430. }
  16431. }
  16432. // View / Export Modal
  16433. async function openViewCertModal(name) {
  16434. const c = (state.certificates || []).find(x => x.name === name);
  16435. if (!c) return;
  16436. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16437. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16438. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16439. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16440. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16441. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16442. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16443. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16444. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16445. document.getElementById('modal-view-cert').classList.remove('hidden');
  16446. try {
  16447. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16448. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16449. const data = await res.json();
  16450. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16451. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16452. } catch (err) {
  16453. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16454. document.getElementById('view-key-pem-text').value = '';
  16455. }
  16456. }
  16457. function closeViewCertModal() {
  16458. document.getElementById('modal-view-cert').classList.add('hidden');
  16459. }
  16460. function copyCertPEM() {
  16461. const text = document.getElementById('view-cert-pem-text').value;
  16462. if (!text) return;
  16463. navigator.clipboard.writeText(text).then(() => {
  16464. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16465. }).catch(() => {
  16466. showToast('Error', 'Failed to copy to clipboard', 'error');
  16467. });
  16468. }
  16469. function copyKeyPEM() {
  16470. const text = document.getElementById('view-key-pem-text').value;
  16471. if (!text) return;
  16472. navigator.clipboard.writeText(text).then(() => {
  16473. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16474. }).catch(() => {
  16475. showToast('Error', 'Failed to copy to clipboard', 'error');
  16476. });
  16477. }
  16478. async function deleteCertificate(name) {
  16479. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16480. return;
  16481. }
  16482. try {
  16483. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16484. method: 'DELETE'
  16485. });
  16486. if (!res.ok) {
  16487. const errData = await res.json();
  16488. throw new Error(errData.message || 'Failed to delete certificate');
  16489. }
  16490. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16491. await loadCertificates();
  16492. } catch (err) {
  16493. showToast('Error', err.message, 'error');
  16494. }
  16495. }
  16496. // Refresh immediately when returning to a backgrounded controller tab.
  16497. document.addEventListener('visibilitychange', () => {
  16498. if (!state.currentUser) return;
  16499. if (document.hidden) {
  16500. if (trafficEventSource) trafficEventSource.close();
  16501. trafficEventSource = null;
  16502. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16503. trafficPollFallback = null;
  16504. } else {
  16505. fetchData(false);
  16506. initLiveTrafficStream();
  16507. if (state.activeTab === 'bwtest') loadBwTestView();
  16508. }
  16509. });
  16510. async function loadUpdateStatus(populate = true) {
  16511. try {
  16512. const res = await fetch(`${API_BASE}/update/status`);
  16513. if (!res.ok) throw new Error(await responseError(res));
  16514. const data = await res.json();
  16515. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16516. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16517. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16518. document.getElementById('update-state').textContent = data.state || 'idle';
  16519. document.getElementById('update-log').textContent = data.log || '';
  16520. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16521. }
  16522. async function saveUpdateConfig() {
  16523. try {
  16524. const repository = document.getElementById('update-repository').value.trim();
  16525. const branch = 'master';
  16526. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16527. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16528. if (!res.ok) throw new Error(await responseError(res));
  16529. document.getElementById('update-install-button').disabled = true;
  16530. document.getElementById('update-available').textContent = '—';
  16531. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16532. await loadUpdateStatus(false);
  16533. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16534. }
  16535. async function checkUpdate() {
  16536. try {
  16537. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16538. if (!res.ok) throw new Error(await responseError(res));
  16539. const data = await res.json();
  16540. document.getElementById('update-available').textContent = data.available_version;
  16541. document.getElementById('update-install-button').disabled = !data.update_available;
  16542. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16543. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16544. }
  16545. async function startUpdate(action) {
  16546. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16547. try {
  16548. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16549. if (!res.ok) throw new Error(await responseError(res));
  16550. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16551. await loadUpdateStatus(false);
  16552. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16553. }
  16554. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16555. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16556. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16557. function safeFirewallRow(row) {
  16558. const result = {...row};
  16559. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16560. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16561. return result;
  16562. }
  16563. function setFirewallDays(prefix, days) {
  16564. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16565. 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); }
  16566. }
  16567. function getFirewallDays(prefix) {
  16568. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16569. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16570. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16571. return selected.join(',');
  16572. }
  16573. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16574. const id = document.getElementById(kind+'-modal-id')?.value;
  16575. if (!id) { resetDisplay(); return; }
  16576. try {
  16577. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16578. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16579. resetDisplay(); await loadFirewall(false);
  16580. } catch(error) { showToast('Error', error.message, 'error'); }
  16581. }
  16582. function reviewLegacyFirewallSettings(kind, id) {
  16583. if (!id) return true;
  16584. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16585. const rule = (rows || []).find(r => r.id === id);
  16586. if (!rule) return true;
  16587. 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'];
  16588. const present = unsupported.filter(key => rule[key]);
  16589. if (!present.length) return true;
  16590. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16591. }
  16592. function refreshFirewallRejectTypes() {
  16593. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16594. const old=select.value;
  16595. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16596. 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'];
  16597. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16598. if(types.includes(old))select.value=old;
  16599. }
  16600. function setFirewallActionSelection(kind, value) {
  16601. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16602. if(!Array.from(select.options).some(option=>option.value===value)) {
  16603. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16604. }
  16605. select.value=value;
  16606. }
  16607. // ==========================================
  16608. // REVERSE PROXY & APPLICATION GATEWAY
  16609. // ==========================================
  16610. state.proxyRules = [];
  16611. state.proxyConfig = null;
  16612. async function loadReverseProxy(manual = false) {
  16613. try {
  16614. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16615. fetch(`${API_BASE}/proxy/config`),
  16616. fetch(`${API_BASE}/proxy/rules`),
  16617. fetch(`${API_BASE}/certificates`).catch(() => null)
  16618. ]);
  16619. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16620. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16621. state.proxyConfig = await cfgRes.json();
  16622. state.proxyRules = await rulesRes.json() || [];
  16623. if (certsRes && certsRes.ok) {
  16624. state.certificates = await certsRes.json() || [];
  16625. }
  16626. renderProxyRules(state.proxyRules);
  16627. updateProxyMetrics();
  16628. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16629. } catch (err) {
  16630. console.error('loadReverseProxy error:', err);
  16631. if (manual) showToast('Error', err.message, 'error');
  16632. }
  16633. }
  16634. function updateProxyMetrics() {
  16635. const badge = document.getElementById('badge-proxy-count');
  16636. if (badge) badge.textContent = (state.proxyRules || []).length;
  16637. const metricRules = document.getElementById('proxy-metric-rules');
  16638. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16639. const cfg = state.proxyConfig;
  16640. const statusEl = document.getElementById('proxy-metric-status');
  16641. const portsEl = document.getElementById('proxy-metric-ports');
  16642. if (cfg) {
  16643. if (statusEl) {
  16644. if (cfg.enabled) {
  16645. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16646. } else {
  16647. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16648. }
  16649. }
  16650. if (portsEl) {
  16651. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16652. }
  16653. }
  16654. let totalRequests = 0;
  16655. const certSet = new Set();
  16656. (state.proxyRules || []).forEach(r => {
  16657. totalRequests += (r.stats && r.stats.requests) || 0;
  16658. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16659. });
  16660. const metricRequests = document.getElementById('proxy-metric-requests');
  16661. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16662. const metricCerts = document.getElementById('proxy-metric-certs');
  16663. if (metricCerts) metricCerts.textContent = certSet.size;
  16664. }
  16665. function renderProxyRules(rules) {
  16666. const tbody = document.getElementById('proxy-rules-table-body');
  16667. if (!tbody) return;
  16668. if (!rules || rules.length === 0) {
  16669. 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>';
  16670. return;
  16671. }
  16672. tbody.innerHTML = rules.map(r => {
  16673. const isEnabled = r.enabled !== false;
  16674. 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>';
  16675. 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>`;
  16676. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16677. 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>';
  16678. 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>';
  16679. 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>` : '';
  16680. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16681. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16682. return `
  16683. <tr class="hover:bg-slate-800/40 transition">
  16684. <td class="py-3 px-4">
  16685. <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'}">
  16686. <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>
  16687. </button>
  16688. </td>
  16689. <td class="py-3 px-4">
  16690. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16691. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16692. </td>
  16693. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16694. ${domainsStr}
  16695. </td>
  16696. <td class="py-3 px-4">
  16697. ${pathBadge}
  16698. </td>
  16699. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16700. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16701. </td>
  16702. <td class="py-3 px-4 whitespace-nowrap">
  16703. ${protoBadge}${certBadge}
  16704. </td>
  16705. <td class="py-3 px-4 font-mono">
  16706. ${stripBadge}
  16707. </td>
  16708. <td class="py-3 px-4 font-mono text-slate-300">
  16709. ${requests}
  16710. </td>
  16711. <td class="py-3 px-4 text-right whitespace-nowrap">
  16712. <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>
  16713. <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>
  16714. </td>
  16715. </tr>
  16716. `;
  16717. }).join('');
  16718. }
  16719. function populateProxyCertDropdown(selectedVal = '') {
  16720. const select = document.getElementById('proxy-rule-cert');
  16721. if (!select) return;
  16722. const certs = state.certificates || [];
  16723. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16724. certs.filter(c => !c.is_ca).forEach(c => {
  16725. const opt = document.createElement('option');
  16726. opt.value = c.name;
  16727. const cn = c.common_name ? ` (${c.common_name})` : '';
  16728. opt.textContent = `${c.name}${cn}`;
  16729. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16730. opt.selected = true;
  16731. }
  16732. select.appendChild(opt);
  16733. });
  16734. }
  16735. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16736. const select = document.getElementById('proxy-cfg-default-cert');
  16737. if (!select) return;
  16738. const certs = state.certificates || [];
  16739. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16740. certs.filter(c => !c.is_ca).forEach(c => {
  16741. const opt = document.createElement('option');
  16742. opt.value = c.name;
  16743. const cn = c.common_name ? ` (${c.common_name})` : '';
  16744. opt.textContent = `${c.name}${cn}`;
  16745. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16746. opt.selected = true;
  16747. }
  16748. select.appendChild(opt);
  16749. });
  16750. }
  16751. function onProxyProtoChange() {
  16752. const proto = document.getElementById('proxy-rule-proto')?.value;
  16753. const certSelect = document.getElementById('proxy-rule-cert');
  16754. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16755. if (proto === 'http') {
  16756. if (certSelect) certSelect.disabled = true;
  16757. if (redirectCheck) redirectCheck.disabled = true;
  16758. } else {
  16759. if (certSelect) certSelect.disabled = false;
  16760. if (redirectCheck) redirectCheck.disabled = false;
  16761. }
  16762. }
  16763. function openAddProxyRuleModal() {
  16764. const modal = document.getElementById('modal-proxy-rule');
  16765. if (!modal) return;
  16766. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16767. <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>
  16768. <span>Add Reverse Proxy Rule</span>
  16769. `;
  16770. document.getElementById('proxy-rule-id').value = '';
  16771. document.getElementById('proxy-rule-name').value = '';
  16772. document.getElementById('proxy-rule-domains').value = '';
  16773. document.getElementById('proxy-rule-path').value = '/';
  16774. document.getElementById('proxy-rule-target').value = '';
  16775. document.getElementById('proxy-rule-proto').value = 'both';
  16776. document.getElementById('proxy-rule-strip-path').checked = false;
  16777. document.getElementById('proxy-rule-http-to-https').checked = false;
  16778. document.getElementById('proxy-rule-preserve-host').checked = false;
  16779. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16780. document.getElementById('proxy-rule-enabled').checked = true;
  16781. document.getElementById('proxy-rule-comment').value = '';
  16782. populateProxyCertDropdown('');
  16783. onProxyProtoChange();
  16784. modal.classList.remove('hidden');
  16785. }
  16786. function openEditProxyRuleModal(id) {
  16787. const modal = document.getElementById('modal-proxy-rule');
  16788. if (!modal) return;
  16789. const rule = (state.proxyRules || []).find(r => r.id === id);
  16790. if (!rule) {
  16791. showToast('Error', 'Rule not found', 'error');
  16792. return;
  16793. }
  16794. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16795. <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>
  16796. <span>Edit Reverse Proxy Rule</span>
  16797. `;
  16798. document.getElementById('proxy-rule-id').value = rule.id || '';
  16799. document.getElementById('proxy-rule-name').value = rule.name || '';
  16800. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16801. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16802. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16803. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16804. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16805. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16806. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16807. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16808. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16809. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16810. populateProxyCertDropdown(rule.certificate || '');
  16811. onProxyProtoChange();
  16812. modal.classList.remove('hidden');
  16813. }
  16814. function closeProxyRuleModal() {
  16815. const modal = document.getElementById('modal-proxy-rule');
  16816. if (modal) modal.classList.add('hidden');
  16817. }
  16818. async function saveProxyRule(event) {
  16819. event.preventDefault();
  16820. const id = document.getElementById('proxy-rule-id').value;
  16821. const name = document.getElementById('proxy-rule-name').value.trim();
  16822. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16823. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16824. const target = document.getElementById('proxy-rule-target').value.trim();
  16825. const proto = document.getElementById('proxy-rule-proto').value;
  16826. const cert = document.getElementById('proxy-rule-cert').value;
  16827. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16828. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16829. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16830. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16831. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16832. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16833. let domains = [];
  16834. if (rawDomains && rawDomains !== '*') {
  16835. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16836. }
  16837. const payload = {
  16838. id: id || undefined,
  16839. name,
  16840. domains,
  16841. path: pathVal,
  16842. target_url: target,
  16843. protocol: proto,
  16844. certificate: cert,
  16845. strip_path: stripPath,
  16846. http_to_https: httpToHttps,
  16847. preserve_host: preserveHost,
  16848. insecure_tls: insecureTLS,
  16849. enabled,
  16850. comment
  16851. };
  16852. try {
  16853. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16854. const method = id ? 'PUT' : 'POST';
  16855. const res = await fetch(url, {
  16856. method,
  16857. headers: { 'Content-Type': 'application/json' },
  16858. body: JSON.stringify(payload)
  16859. });
  16860. if (!res.ok) {
  16861. const errData = await res.json().catch(() => ({}));
  16862. throw new Error(errData.message || 'Failed to save proxy rule');
  16863. }
  16864. closeProxyRuleModal();
  16865. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16866. await loadReverseProxy(false);
  16867. } catch (err) {
  16868. showToast('Error', err.message, 'error');
  16869. }
  16870. }
  16871. async function deleteProxyRule(id) {
  16872. const rule = (state.proxyRules || []).find(r => r.id === id);
  16873. const name = rule ? rule.name : id;
  16874. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  16875. return;
  16876. }
  16877. try {
  16878. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  16879. method: 'DELETE'
  16880. });
  16881. if (!res.ok) {
  16882. const errData = await res.json().catch(() => ({}));
  16883. throw new Error(errData.message || 'Failed to delete rule');
  16884. }
  16885. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  16886. await loadReverseProxy(false);
  16887. } catch (err) {
  16888. showToast('Error', err.message, 'error');
  16889. }
  16890. }
  16891. async function toggleProxyRuleState(id, currentState) {
  16892. try {
  16893. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  16894. method: 'POST',
  16895. headers: { 'Content-Type': 'application/json' },
  16896. body: JSON.stringify({ enabled: !currentState })
  16897. });
  16898. if (!res.ok) {
  16899. const errData = await res.json().catch(() => ({}));
  16900. throw new Error(errData.message || 'Failed to toggle rule state');
  16901. }
  16902. await loadReverseProxy(false);
  16903. } catch (err) {
  16904. showToast('Error', err.message, 'error');
  16905. }
  16906. }
  16907. function openProxyConfigModal() {
  16908. const modal = document.getElementById('modal-proxy-config');
  16909. if (!modal) return;
  16910. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  16911. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  16912. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  16913. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  16914. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  16915. modal.classList.remove('hidden');
  16916. }
  16917. function closeProxyConfigModal() {
  16918. const modal = document.getElementById('modal-proxy-config');
  16919. if (modal) modal.classList.add('hidden');
  16920. }
  16921. async function saveProxyConfig(event) {
  16922. event.preventDefault();
  16923. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  16924. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  16925. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  16926. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  16927. const payload = {
  16928. enabled,
  16929. http_port: httpPort,
  16930. https_port: httpsPort,
  16931. default_cert: defaultCert
  16932. };
  16933. try {
  16934. const res = await fetch(`${API_BASE}/proxy/config`, {
  16935. method: 'POST',
  16936. headers: { 'Content-Type': 'application/json' },
  16937. body: JSON.stringify(payload)
  16938. });
  16939. if (!res.ok) {
  16940. const errData = await res.json().catch(() => ({}));
  16941. throw new Error(errData.message || 'Failed to update proxy settings');
  16942. }
  16943. closeProxyConfigModal();
  16944. showToast('Success', 'Reverse proxy settings updated', 'success');
  16945. await loadReverseProxy(false);
  16946. } catch (err) {
  16947. showToast('Error', err.message, 'error');
  16948. }
  16949. }
  16950. // ==================== SD-WAN Controller ====================
  16951. async function loadSDWAN(manual = false) {
  16952. try {
  16953. const [groupsRes, telemetryRes] = await Promise.all([
  16954. fetch(`${API_BASE}/sdwan/groups`),
  16955. fetch(`${API_BASE}/sdwan/telemetry`)
  16956. ]);
  16957. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  16958. state.sdwanGroups = await groupsRes.json() || [];
  16959. if (telemetryRes.ok) {
  16960. state.sdwanTelemetry = await telemetryRes.json() || {};
  16961. }
  16962. renderSDWANGroups(state.sdwanGroups);
  16963. renderSDWANMembers(state.sdwanGroups);
  16964. updateSDWANMetrics(state.sdwanTelemetry);
  16965. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  16966. } catch (err) {
  16967. console.error('loadSDWAN error:', err);
  16968. if (manual) showToast('Error', err.message, 'error');
  16969. }
  16970. }
  16971. function updateSDWANMetrics(telemetry) {
  16972. const groups = state.sdwanGroups || [];
  16973. const t = telemetry || {};
  16974. const badge = document.getElementById('badge-sdwan-count');
  16975. if (badge) badge.textContent = groups.length;
  16976. const metricGroups = document.getElementById('sdwan-metric-groups');
  16977. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  16978. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  16979. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  16980. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  16981. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  16982. const metricDown = document.getElementById('sdwan-metric-down');
  16983. if (metricDown) metricDown.textContent = t.down_members || 0;
  16984. }
  16985. function renderSDWANGroups(groups) {
  16986. const tbody = document.getElementById('sdwan-groups-table-body');
  16987. if (!tbody) return;
  16988. if (!groups || groups.length === 0) {
  16989. 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>';
  16990. return;
  16991. }
  16992. tbody.innerHTML = groups.map(g => {
  16993. const isEnabled = g.disabled !== true;
  16994. const members = g.members || [];
  16995. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  16996. // Build distribution progress bar
  16997. let distHtml = '';
  16998. if (members.length === 0) {
  16999. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17000. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17001. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17002. const segments = members.map((m, idx) => {
  17003. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17004. const col = colors[idx % colors.length];
  17005. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17006. }).join('');
  17007. const labels = members.map((m, idx) => {
  17008. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17009. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17010. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17011. }).join('');
  17012. distHtml = `
  17013. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17014. <div class="flex flex-wrap">${labels}</div>
  17015. `;
  17016. } else if (g.mode === 'lowest-latency') {
  17017. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17018. } else if (g.mode === 'lowest-loss') {
  17019. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17020. } else if (g.mode === 'failover') {
  17021. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17022. }
  17023. let modeBadge = '';
  17024. switch (g.mode) {
  17025. case 'weighted':
  17026. 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>';
  17027. break;
  17028. case 'pcc':
  17029. 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>';
  17030. break;
  17031. case 'lowest-latency':
  17032. 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>';
  17033. break;
  17034. case 'lowest-loss':
  17035. 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>';
  17036. break;
  17037. case 'failover':
  17038. 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>';
  17039. break;
  17040. default:
  17041. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17042. }
  17043. const autoNatBadge = g.auto_nat
  17044. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17045. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17046. return `
  17047. <tr class="hover:bg-slate-800/40 transition">
  17048. <td class="py-3 px-4">
  17049. <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'}">
  17050. <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>
  17051. </button>
  17052. </td>
  17053. <td class="py-3 px-4">
  17054. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17055. <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>
  17056. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17057. </div>
  17058. </td>
  17059. <td class="py-3 px-4">${modeBadge}</td>
  17060. <td class="py-3 px-4">${distHtml}</td>
  17061. <td class="py-3 px-4">
  17062. <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>
  17063. </td>
  17064. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17065. <td class="py-3 px-4">${autoNatBadge}</td>
  17066. <td class="py-3 px-4 text-right">
  17067. <div class="flex items-center justify-end gap-1.5">
  17068. <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">
  17069. <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>
  17070. </button>
  17071. <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">
  17072. <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>
  17073. </button>
  17074. <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">
  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="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>
  17076. </button>
  17077. </div>
  17078. </td>
  17079. </tr>
  17080. `;
  17081. }).join('');
  17082. }
  17083. function renderSDWANMembers(groups) {
  17084. const tbody = document.getElementById('sdwan-members-table-body');
  17085. if (!tbody) return;
  17086. const allMembers = [];
  17087. (groups || []).forEach(g => {
  17088. (g.members || []).forEach(m => {
  17089. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17090. });
  17091. });
  17092. if (allMembers.length === 0) {
  17093. 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>';
  17094. return;
  17095. }
  17096. tbody.innerHTML = allMembers.map(m => {
  17097. const isEnabled = m.disabled !== true;
  17098. 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>';
  17099. if (!isEnabled) {
  17100. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17101. } else if (m.status === 'DEGRADED') {
  17102. 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>';
  17103. } else if (m.status === 'DOWN') {
  17104. 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>';
  17105. }
  17106. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17107. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17108. return `
  17109. <tr class="hover:bg-slate-800/40 transition">
  17110. <td class="py-3 px-4">
  17111. <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'}">
  17112. <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>
  17113. </button>
  17114. </td>
  17115. <td class="py-3 px-4">
  17116. <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>
  17117. </td>
  17118. <td class="py-3 px-4">
  17119. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17120. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17121. </td>
  17122. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17123. <td class="py-3 px-4">
  17124. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17125. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17126. </td>
  17127. <td class="py-3 px-4">${statusBadge}</td>
  17128. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17129. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17130. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17131. </td>
  17132. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17133. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17134. </td>
  17135. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17136. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17137. </td>
  17138. <td class="py-3 px-4 text-right">
  17139. <div class="flex items-center justify-end gap-1.5">
  17140. <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">
  17141. <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>
  17142. </button>
  17143. <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">
  17144. <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>
  17145. </button>
  17146. </div>
  17147. </td>
  17148. </tr>
  17149. `;
  17150. }).join('');
  17151. }
  17152. // Modal handling for SD-WAN Groups
  17153. function openAddSDWANGroupModal() {
  17154. const modal = document.getElementById('modal-sdwan-group');
  17155. if (!modal) return;
  17156. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17157. document.getElementById('sdwan-group-id').value = '';
  17158. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17159. document.getElementById('sdwan-group-name').disabled = false;
  17160. document.getElementById('sdwan-group-mode').value = 'weighted';
  17161. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17162. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17163. document.getElementById('sdwan-group-probe-interval').value = 3;
  17164. document.getElementById('sdwan-group-auto-nat').checked = true;
  17165. document.getElementById('sdwan-group-comment').value = '';
  17166. modal.classList.remove('hidden');
  17167. }
  17168. function openEditSDWANGroupModal(id) {
  17169. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17170. if (!group) return;
  17171. const modal = document.getElementById('modal-sdwan-group');
  17172. if (!modal) return;
  17173. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17174. document.getElementById('sdwan-group-id').value = group.id;
  17175. document.getElementById('sdwan-group-name').value = group.name;
  17176. document.getElementById('sdwan-group-name').disabled = true;
  17177. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17178. if (group.mode === 'pcc') {
  17179. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17180. } else {
  17181. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17182. }
  17183. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17184. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17185. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17186. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17187. modal.classList.remove('hidden');
  17188. }
  17189. function closeSDWANGroupModal() {
  17190. const modal = document.getElementById('modal-sdwan-group');
  17191. if (modal) modal.classList.add('hidden');
  17192. }
  17193. function onSDWANModeChange() {
  17194. const mode = document.getElementById('sdwan-group-mode').value;
  17195. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17196. if (pccContainer) {
  17197. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17198. else pccContainer.classList.add('hidden');
  17199. }
  17200. }
  17201. async function saveSDWANGroup(event) {
  17202. event.preventDefault();
  17203. const id = document.getElementById('sdwan-group-id').value;
  17204. const name = document.getElementById('sdwan-group-name').value.trim();
  17205. const mode = document.getElementById('sdwan-group-mode').value;
  17206. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17207. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17208. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17209. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17210. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17211. const payload = {
  17212. id: id || undefined,
  17213. name,
  17214. mode,
  17215. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17216. probe_interval: probeInterval,
  17217. auto_nat: autoNAT,
  17218. comment,
  17219. members: existing ? existing.members : undefined
  17220. };
  17221. try {
  17222. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17223. method: 'POST',
  17224. headers: { 'Content-Type': 'application/json' },
  17225. body: JSON.stringify(payload)
  17226. });
  17227. if (!res.ok) {
  17228. const err = await res.json().catch(() => ({}));
  17229. throw new Error(err.message || 'Failed to save SD-WAN group');
  17230. }
  17231. closeSDWANGroupModal();
  17232. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17233. await loadSDWAN(false);
  17234. } catch (err) {
  17235. showToast('Error', err.message, 'error');
  17236. }
  17237. }
  17238. async function toggleSDWANGroupState(id, currentState) {
  17239. try {
  17240. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17241. method: 'POST',
  17242. headers: { 'Content-Type': 'application/json' },
  17243. body: JSON.stringify({ disabled: currentState })
  17244. });
  17245. if (!res.ok) throw new Error('Failed to update group state');
  17246. await loadSDWAN(false);
  17247. } catch (err) {
  17248. showToast('Error', err.message, 'error');
  17249. }
  17250. }
  17251. async function deleteSDWANGroup(id) {
  17252. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17253. const name = group ? group.name : id;
  17254. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17255. try {
  17256. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17257. method: 'DELETE'
  17258. });
  17259. if (!res.ok) {
  17260. const err = await res.json().catch(() => ({}));
  17261. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17262. }
  17263. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17264. await loadSDWAN(false);
  17265. } catch (err) {
  17266. showToast('Error', err.message, 'error');
  17267. }
  17268. }
  17269. // Modal handling for SD-WAN Members
  17270. function populateSDWANGroupsSelect(selectedId = '') {
  17271. const sel = document.getElementById('sdwan-member-group-id');
  17272. if (!sel) return;
  17273. sel.innerHTML = '';
  17274. (state.sdwanGroups || []).forEach(g => {
  17275. const opt = document.createElement('option');
  17276. opt.value = g.id;
  17277. opt.textContent = `${g.name} (${g.mode})`;
  17278. if (g.id === selectedId) opt.selected = true;
  17279. sel.appendChild(opt);
  17280. });
  17281. }
  17282. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17283. const sel = document.getElementById('sdwan-member-interface');
  17284. if (!sel) return;
  17285. sel.innerHTML = '';
  17286. (state.interfaces || []).forEach(i => {
  17287. const opt = document.createElement('option');
  17288. opt.value = i.name;
  17289. opt.textContent = `${i.name} (${i.role || i.type})`;
  17290. if (i.name === selectedVal) opt.selected = true;
  17291. sel.appendChild(opt);
  17292. });
  17293. }
  17294. function openAddSDWANMemberModal(defaultGroupId = null) {
  17295. const modal = document.getElementById('modal-sdwan-member');
  17296. if (!modal) return;
  17297. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17298. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17299. return;
  17300. }
  17301. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17302. document.getElementById('sdwan-member-id').value = '';
  17303. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17304. populateSDWANMemberInterfaceSelect();
  17305. document.getElementById('sdwan-member-gateway').value = '';
  17306. document.getElementById('sdwan-member-weight').value = 50;
  17307. document.getElementById('sdwan-member-priority').value = 1;
  17308. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17309. document.getElementById('sdwan-member-max-lat').value = 250;
  17310. document.getElementById('sdwan-member-max-loss').value = 20;
  17311. document.getElementById('sdwan-member-comment').value = '';
  17312. modal.classList.remove('hidden');
  17313. }
  17314. function openEditSDWANMemberModal(groupId, memberId) {
  17315. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17316. if (!group) return;
  17317. const member = (group.members || []).find(m => m.id === memberId);
  17318. if (!member) return;
  17319. const modal = document.getElementById('modal-sdwan-member');
  17320. if (!modal) return;
  17321. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17322. document.getElementById('sdwan-member-id').value = member.id;
  17323. populateSDWANGroupsSelect(group.id);
  17324. document.getElementById('sdwan-member-group-id').disabled = true;
  17325. populateSDWANMemberInterfaceSelect(member.interface);
  17326. document.getElementById('sdwan-member-interface').disabled = true;
  17327. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17328. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17329. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17330. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17331. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17332. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17333. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17334. modal.classList.remove('hidden');
  17335. }
  17336. function closeSDWANMemberModal() {
  17337. const modal = document.getElementById('modal-sdwan-member');
  17338. if (modal) {
  17339. document.getElementById('sdwan-member-group-id').disabled = false;
  17340. document.getElementById('sdwan-member-interface').disabled = false;
  17341. modal.classList.add('hidden');
  17342. }
  17343. }
  17344. async function saveSDWANMember(event) {
  17345. event.preventDefault();
  17346. const id = document.getElementById('sdwan-member-id').value;
  17347. const groupId = document.getElementById('sdwan-member-group-id').value;
  17348. const iface = document.getElementById('sdwan-member-interface').value;
  17349. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17350. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17351. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17352. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17353. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17354. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17355. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17356. const payload = {
  17357. id: id || undefined,
  17358. interface: iface,
  17359. gateway,
  17360. weight,
  17361. priority,
  17362. target_probe: targetProbe,
  17363. max_latency: maxLatency,
  17364. max_loss: maxLoss,
  17365. comment
  17366. };
  17367. try {
  17368. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17369. method: 'POST',
  17370. headers: { 'Content-Type': 'application/json' },
  17371. body: JSON.stringify(payload)
  17372. });
  17373. if (!res.ok) {
  17374. const err = await res.json().catch(() => ({}));
  17375. throw new Error(err.message || 'Failed to save member link');
  17376. }
  17377. closeSDWANMemberModal();
  17378. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17379. await loadSDWAN(false);
  17380. } catch (err) {
  17381. showToast('Error', err.message, 'error');
  17382. }
  17383. }
  17384. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17385. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17386. if (!group) return;
  17387. const member = (group.members || []).find(m => m.id === memberId);
  17388. if (!member) return;
  17389. const payload = {
  17390. ...member,
  17391. disabled: currentState
  17392. };
  17393. try {
  17394. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17395. method: 'POST',
  17396. headers: { 'Content-Type': 'application/json' },
  17397. body: JSON.stringify(payload)
  17398. });
  17399. if (!res.ok) throw new Error('Failed to update member state');
  17400. await loadSDWAN(false);
  17401. } catch (err) {
  17402. showToast('Error', err.message, 'error');
  17403. }
  17404. }
  17405. async function deleteSDWANMember(groupId, iface) {
  17406. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17407. try {
  17408. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17409. method: 'DELETE'
  17410. });
  17411. if (!res.ok) {
  17412. const err = await res.json().catch(() => ({}));
  17413. throw new Error(err.message || 'Failed to remove member link');
  17414. }
  17415. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17416. await loadSDWAN(false);
  17417. } catch (err) {
  17418. showToast('Error', err.message, 'error');
  17419. }
  17420. }