app.js 826 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495
  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. const redist = [];
  9213. if (inst.redistribute_connected) redist.push('conn');
  9214. if (inst.redistribute_static) redist.push('static');
  9215. if (inst.redistribute_bgp) redist.push('bgp');
  9216. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9217. redist.push('default');
  9218. }
  9219. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9220. const origBadge = origDef === 'always'
  9221. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 font-bold border border-amber-500/30">always</span>'
  9222. : (origDef === 'if-installed'
  9223. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 font-bold border border-sky-500/30">if-installed</span>'
  9224. : '<span class="text-slate-500 text-[10px]">never</span>');
  9225. return `
  9226. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9227. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9228. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9229. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9230. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9231. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9232. </td>
  9233. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9234. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9235. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9236. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9237. <td class="py-1.5 px-3">${origBadge}</td>
  9238. </tr>
  9239. `;
  9240. }).join('');
  9241. }
  9242. // TAB 2: AREAS
  9243. function renderOspfAreas() {
  9244. const tbody = document.getElementById('ospf-areas-table-body');
  9245. if (!tbody) return;
  9246. const countEl = document.getElementById('ospf-areas-footer-count');
  9247. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9248. let list = state.ospfAreas || [];
  9249. if (filter) {
  9250. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9251. }
  9252. if (countEl) countEl.innerText = list.length;
  9253. const selId = state.selectedOspfRow?.areas;
  9254. tbody.innerHTML = list.map((a, idx) => {
  9255. const isSel = a.id === selId;
  9256. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9257. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9258. return `
  9259. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9260. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9261. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9262. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9263. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9264. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9265. </td>
  9266. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9267. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9268. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9269. </tr>
  9270. `;
  9271. }).join('');
  9272. }
  9273. // TAB 3: AREA RANGES
  9274. function renderOspfAreaRanges() {
  9275. const tbody = document.getElementById('ospf-ranges-table-body');
  9276. if (!tbody) return;
  9277. const countEl = document.getElementById('ospf-ranges-footer-count');
  9278. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9279. let list = state.ospfAreaRanges || [];
  9280. if (filter) {
  9281. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9282. }
  9283. if (countEl) countEl.innerText = list.length;
  9284. const selId = state.selectedOspfRow?.['area-ranges'];
  9285. tbody.innerHTML = list.map((r, idx) => {
  9286. const isSel = r.id === selId;
  9287. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9288. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9289. return `
  9290. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9291. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9292. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9293. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9294. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9295. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9296. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9297. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9298. </tr>
  9299. `;
  9300. }).join('');
  9301. }
  9302. // TAB 4: INTERFACE TEMPLATES
  9303. function renderOspfTemplates() {
  9304. const tbody = document.getElementById('ospf-templates-table-body');
  9305. if (!tbody) return;
  9306. const countEl = document.getElementById('ospf-templates-footer-count');
  9307. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9308. let list = state.ospfTemplates || [];
  9309. if (filter) {
  9310. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9311. }
  9312. if (countEl) countEl.innerText = list.length;
  9313. const selId = state.selectedOspfRow?.templates;
  9314. tbody.innerHTML = list.map((t, idx) => {
  9315. const isSel = t.id === selId;
  9316. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9317. const ifaces = t.interfaces || t.interface || 'all';
  9318. const nets = t.networks || t.network || '';
  9319. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9320. return `
  9321. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9322. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9323. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9324. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9325. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9326. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9327. </td>
  9328. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9329. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9330. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9331. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9332. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9333. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9334. </tr>
  9335. `;
  9336. }).join('');
  9337. }
  9338. // TAB 5: LIVE INTERFACES
  9339. function renderOspfLiveInterfaces() {
  9340. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9341. if (!tbody) return;
  9342. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9343. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9344. let list = state.ospfLiveInterfaces || [];
  9345. if (filter) {
  9346. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9347. }
  9348. if (countEl) countEl.innerText = list.length;
  9349. tbody.innerHTML = list.map(i => `
  9350. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9351. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9352. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9353. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9354. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9355. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9356. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9357. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9358. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9359. </tr>
  9360. `).join('');
  9361. }
  9362. // TAB 6: STATIC NEIGHBORS
  9363. function renderOspfStaticNbrs() {
  9364. const tbody = document.getElementById('ospf-snbrs-table-body');
  9365. if (!tbody) return;
  9366. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9367. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9368. let list = state.ospfStaticNbrs || [];
  9369. if (filter) {
  9370. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9371. }
  9372. if (countEl) countEl.innerText = list.length;
  9373. const selId = state.selectedOspfRow?.['static-nbrs'];
  9374. tbody.innerHTML = list.map((n, idx) => {
  9375. const isSel = n.id === selId;
  9376. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9377. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9378. return `
  9379. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9380. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9381. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9382. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9383. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9384. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9385. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9386. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9387. </tr>
  9388. `;
  9389. }).join('');
  9390. }
  9391. // TAB 7: LIVE NEIGHBORS
  9392. function renderOspfNeighbors() {
  9393. const tbody = document.getElementById('ospf-neighbors-table-body');
  9394. if (!tbody) return;
  9395. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9396. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9397. let list = state.ospfNeighbors || [];
  9398. if (filter) {
  9399. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9400. }
  9401. if (countEl) countEl.innerText = list.length;
  9402. tbody.innerHTML = list.map(n => `
  9403. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9404. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9405. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9406. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9407. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9408. </td>
  9409. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9410. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9411. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9412. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9413. </tr>
  9414. `).join('');
  9415. }
  9416. // TAB 8: LINK-STATE DATABASE (LSA)
  9417. function renderOspfLSA() {
  9418. const tbody = document.getElementById('ospf-lsa-table-body');
  9419. if (!tbody) return;
  9420. const countEl = document.getElementById('ospf-lsa-footer-count');
  9421. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9422. let list = state.ospfLSA || [];
  9423. if (filter) {
  9424. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9425. }
  9426. if (countEl) countEl.innerText = list.length;
  9427. tbody.innerHTML = list.map(l => `
  9428. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9429. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9430. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9431. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9432. </td>
  9433. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9434. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9435. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9436. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9437. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9438. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9439. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9440. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9441. </tr>
  9442. `).join('');
  9443. }
  9444. function renderOspfStatusPill() {
  9445. // Maintained for backward compatibility
  9446. const pill = document.getElementById('ospf-live-status-pill');
  9447. if (!pill) return;
  9448. 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';
  9449. pill.innerText = 'OSPF ACTIVE';
  9450. }
  9451. function renderOspfInterfaces() {
  9452. renderOspfTemplates();
  9453. }
  9454. function renderOspfRoutes() {
  9455. // Routes retained in background
  9456. }
  9457. // BGP Modals & Actions
  9458. function openBgpInstanceModal() {
  9459. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9460. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9461. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9462. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9463. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9464. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9465. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9466. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9467. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9468. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9469. }
  9470. function closeBgpInstanceModal() {
  9471. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9472. }
  9473. async function submitBgpInstance(e) {
  9474. e.preventDefault();
  9475. const payload = {
  9476. enabled: document.getElementById('modal-bgp-enabled').checked,
  9477. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9478. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9479. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9480. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9481. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9482. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9483. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9484. };
  9485. try {
  9486. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9487. method: 'POST',
  9488. headers: { 'Content-Type': 'application/json' },
  9489. body: JSON.stringify(payload)
  9490. });
  9491. if (res.ok) {
  9492. closeBgpInstanceModal();
  9493. showToast('Success', 'BGP instance configuration updated', 'success');
  9494. loadDynamicRouting();
  9495. } else {
  9496. const err = await res.json();
  9497. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9498. }
  9499. } catch (err) {
  9500. showToast('Error', err.message, 'error');
  9501. }
  9502. }
  9503. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9504. function switchBgpPeerModalTab(tab) {
  9505. // Normalize legacy tab names
  9506. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9507. if (tab === 'attributes') tab = 'networks';
  9508. const tabs = ['general', 'filters', 'networks'];
  9509. tabs.forEach(t => {
  9510. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9511. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9512. if (t === tab) {
  9513. if (pane) pane.classList.remove('hidden');
  9514. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9515. } else {
  9516. if (pane) pane.classList.add('hidden');
  9517. 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';
  9518. }
  9519. });
  9520. }
  9521. function addOutputNetworkRow(val = '') {
  9522. const container = document.getElementById('modal-bgp-output-networks-container');
  9523. if (!container) return;
  9524. const row = document.createElement('div');
  9525. row.className = 'flex items-center gap-2 output-net-row';
  9526. row.innerHTML = `
  9527. <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">
  9528. <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>
  9529. `;
  9530. container.appendChild(row);
  9531. }
  9532. function parseBgpTime(val) {
  9533. if (!val) return 0;
  9534. val = String(val).trim();
  9535. if (val.includes(':')) {
  9536. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9537. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9538. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9539. }
  9540. return parseInt(val, 10) || 0;
  9541. }
  9542. function formatBgpTime(secs) {
  9543. if (!secs || secs <= 0) return '30';
  9544. return String(secs);
  9545. }
  9546. function populateBgpRoutingTables() {
  9547. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9548. if (!sel) return;
  9549. const cur = sel.value || 'main';
  9550. sel.innerHTML = '<option value="main">main</option>';
  9551. (state.routingTables || []).forEach(t => {
  9552. if (t.name !== 'main') {
  9553. const opt = document.createElement('option');
  9554. opt.value = t.name;
  9555. opt.innerText = t.name;
  9556. sel.appendChild(opt);
  9557. }
  9558. });
  9559. sel.value = cur;
  9560. }
  9561. function openAddBgpPeerModal() {
  9562. document.getElementById('bgp-peer-form').reset();
  9563. document.getElementById('modal-bgp-peer-id').value = '';
  9564. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9565. // General Tab
  9566. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9567. document.getElementById('modal-bgp-peer-name').value = '';
  9568. document.getElementById('modal-bgp-peer-comment').value = '';
  9569. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9570. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9571. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9572. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9573. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9574. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9575. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9576. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9577. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9578. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9579. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9580. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9581. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9582. // Filters Tab
  9583. populateFilterChainsDatalist();
  9584. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9585. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9586. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9587. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9588. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9589. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9590. // Advertised Networks Tab
  9591. const container = document.getElementById('modal-bgp-output-networks-container');
  9592. if (container) {
  9593. container.innerHTML = '';
  9594. addOutputNetworkRow('');
  9595. }
  9596. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9597. if (removeBtn) removeBtn.classList.add('hidden');
  9598. switchBgpPeerModalTab('general');
  9599. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9600. }
  9601. function populateFilterChainsDatalist() {
  9602. const dl = document.getElementById('filter-chains-list');
  9603. if (!dl) return;
  9604. const chains = new Set();
  9605. (state.routingFilters || []).forEach(f => {
  9606. if (f.chain) chains.add(f.chain);
  9607. });
  9608. if (chains.size === 0) {
  9609. chains.add('awmn');
  9610. chains.add('Internal');
  9611. chains.add('bgp-in');
  9612. chains.add('bgp-out');
  9613. }
  9614. dl.innerHTML = '';
  9615. chains.forEach(c => {
  9616. const opt = document.createElement('option');
  9617. opt.value = c;
  9618. dl.appendChild(opt);
  9619. });
  9620. }
  9621. function openEditBgpPeerModal(id) {
  9622. const p = (state.bgpPeers || []).find(item => item.id === id);
  9623. if (!p) return;
  9624. populateFilterChainsDatalist();
  9625. document.getElementById('modal-bgp-peer-id').value = p.id;
  9626. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9627. // General Tab
  9628. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9629. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9630. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9631. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9632. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9633. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9634. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9635. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9636. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9637. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9638. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9639. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9640. // Passive mode
  9641. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9642. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9643. // Next-hop self
  9644. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9645. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9646. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9647. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9648. // Filters Tab
  9649. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9650. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9651. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9652. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9653. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9654. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9655. // Advertised Networks Tab
  9656. const container = document.getElementById('modal-bgp-output-networks-container');
  9657. if (container) {
  9658. container.innerHTML = '';
  9659. if (p.output_networks && p.output_networks.length > 0) {
  9660. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9661. } else {
  9662. addOutputNetworkRow('');
  9663. }
  9664. }
  9665. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9666. if (removeBtn) removeBtn.classList.remove('hidden');
  9667. switchBgpPeerModalTab('general');
  9668. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9669. }
  9670. function copyCurrentBgpPeer() {
  9671. document.getElementById('modal-bgp-peer-id').value = '';
  9672. const nameEl = document.getElementById('modal-bgp-peer-name');
  9673. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9674. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9675. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9676. if (removeBtn) removeBtn.classList.add('hidden');
  9677. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9678. }
  9679. function removeCurrentBgpPeer() {
  9680. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9681. if (!id) return;
  9682. deleteBgpPeer(id);
  9683. closeBgpPeerModal();
  9684. }
  9685. function closeBgpPeerModal() {
  9686. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9687. }
  9688. function getBgpPeerFormData() {
  9689. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9690. const outputNetworks = [];
  9691. netInputs.forEach(inp => {
  9692. const v = inp.value.trim();
  9693. if (v) outputNetworks.push(v);
  9694. });
  9695. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9696. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9697. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9698. return {
  9699. id: document.getElementById('modal-bgp-peer-id').value,
  9700. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9701. enabled: enabled,
  9702. disabled: !enabled,
  9703. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9704. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9705. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9706. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9707. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9708. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9709. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9710. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9711. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9712. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9713. passive: isPassive,
  9714. connect: !isPassive,
  9715. listen: true,
  9716. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9717. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9718. nexthop_self: isNexthopSelf,
  9719. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9720. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9721. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9722. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9723. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9724. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9725. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9726. output_networks: outputNetworks
  9727. };
  9728. }
  9729. async function submitBgpPeer(e) {
  9730. if (e) e.preventDefault();
  9731. const payload = getBgpPeerFormData();
  9732. try {
  9733. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9734. method: 'POST',
  9735. headers: { 'Content-Type': 'application/json' },
  9736. body: JSON.stringify(payload)
  9737. });
  9738. if (res.ok) {
  9739. closeBgpPeerModal();
  9740. showToast('Success', 'BGP Connection saved', 'success');
  9741. loadDynamicRouting();
  9742. } else {
  9743. const err = await res.json();
  9744. showToast('Error', err.error || 'Failed to save peer', 'error');
  9745. }
  9746. } catch (err) {
  9747. showToast('Error', err.message, 'error');
  9748. }
  9749. }
  9750. async function applyBgpPeerModal(e) {
  9751. if (e) e.preventDefault();
  9752. const payload = getBgpPeerFormData();
  9753. try {
  9754. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9755. method: 'POST',
  9756. headers: { 'Content-Type': 'application/json' },
  9757. body: JSON.stringify(payload)
  9758. });
  9759. if (res.ok) {
  9760. const data = await res.json();
  9761. if (data.peer && data.peer.id) {
  9762. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9763. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9764. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9765. }
  9766. showToast('Applied', 'BGP Connection applied', 'success');
  9767. loadDynamicRouting();
  9768. } else {
  9769. const err = await res.json();
  9770. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9771. }
  9772. } catch (err) {
  9773. showToast('Error', err.message, 'error');
  9774. }
  9775. }
  9776. async function deleteBgpPeer(id) {
  9777. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9778. try {
  9779. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9780. if (res.ok) {
  9781. showToast('Deleted', 'BGP peer removed', 'success');
  9782. loadDynamicRouting();
  9783. }
  9784. } catch (err) {
  9785. showToast('Error', err.message, 'error');
  9786. }
  9787. }
  9788. async function toggleBgpPeerState(id, disabled) {
  9789. try {
  9790. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9791. method: 'POST',
  9792. headers: { 'Content-Type': 'application/json' },
  9793. body: JSON.stringify({ disabled })
  9794. });
  9795. if (res.ok) {
  9796. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9797. loadDynamicRouting();
  9798. }
  9799. } catch (err) {
  9800. showToast('Error', err.message, 'error');
  9801. }
  9802. }
  9803. function openAddBgpNetworkModal() {
  9804. document.getElementById('bgp-network-form').reset();
  9805. document.getElementById('modal-bgp-net-id').value = '';
  9806. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9807. }
  9808. function closeBgpNetworkModal() {
  9809. document.getElementById('bgp-network-modal').classList.add('hidden');
  9810. }
  9811. async function submitBgpNetwork(e) {
  9812. e.preventDefault();
  9813. const payload = {
  9814. id: document.getElementById('modal-bgp-net-id').value,
  9815. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9816. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9817. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9818. };
  9819. try {
  9820. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9821. method: 'POST',
  9822. headers: { 'Content-Type': 'application/json' },
  9823. body: JSON.stringify(payload)
  9824. });
  9825. if (res.ok) {
  9826. closeBgpNetworkModal();
  9827. showToast('Success', 'BGP network advertisement saved', 'success');
  9828. loadDynamicRouting();
  9829. } else {
  9830. const err = await res.json();
  9831. showToast('Error', err.error || 'Failed to save network', 'error');
  9832. }
  9833. } catch (err) {
  9834. showToast('Error', err.message, 'error');
  9835. }
  9836. }
  9837. async function deleteBgpNetwork(id) {
  9838. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9839. try {
  9840. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9841. if (res.ok) {
  9842. showToast('Deleted', 'Network advertisement removed', 'success');
  9843. loadDynamicRouting();
  9844. }
  9845. } catch (err) {
  9846. showToast('Error', err.message, 'error');
  9847. }
  9848. }
  9849. // =========================================================================
  9850. // DEBTIK v7 OSPF MODALS & ACTIONS
  9851. // =========================================================================
  9852. // --- 1. OSPF INSTANCE ---
  9853. function openOspfInstanceModal(id = null) {
  9854. const isEdit = !!id;
  9855. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9856. id: '',
  9857. name: 'Default',
  9858. version: 2,
  9859. vrf: 'main',
  9860. router_id: '192.168.131.56',
  9861. routing_table: 'main',
  9862. enabled: true,
  9863. redistribute_connected: false,
  9864. redistribute_static: true,
  9865. redistribute_bgp: false,
  9866. comment: ''
  9867. };
  9868. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9869. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9870. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9871. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9872. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9873. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9874. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9875. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9876. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9877. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9878. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9879. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9880. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  9881. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9882. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  9883. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  9884. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  9885. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9886. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9887. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9888. }
  9889. function toggleOspfDefaultModeUI() {
  9890. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  9891. const select = document.getElementById('modal-ospf-inst-originate-default');
  9892. if (!select) return;
  9893. if (isChecked) {
  9894. if (select.value === 'never') select.value = 'if-installed';
  9895. } else {
  9896. select.value = 'never';
  9897. }
  9898. }
  9899. function onOspfOriginateDefaultChange() {
  9900. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  9901. const chk = document.getElementById('modal-ospf-inst-redist-default');
  9902. if (chk) chk.checked = val !== 'never';
  9903. }
  9904. function openEditOspfInstanceModal(id) {
  9905. openOspfInstanceModal(id);
  9906. }
  9907. function closeOspfInstanceModal() {
  9908. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9909. }
  9910. async function submitOspfInstance(e) {
  9911. if (e) e.preventDefault();
  9912. const payload = {
  9913. id: document.getElementById('modal-ospf-inst-id').value,
  9914. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9915. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9916. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9917. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9918. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9919. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9920. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9921. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9922. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9923. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9924. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  9925. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  9926. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  9927. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  9928. };
  9929. try {
  9930. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9931. method: 'POST',
  9932. headers: { 'Content-Type': 'application/json' },
  9933. body: JSON.stringify(payload)
  9934. });
  9935. if (res.ok) {
  9936. closeOspfInstanceModal();
  9937. showToast('Saved', 'OSPF instance updated', 'success');
  9938. loadDynamicRouting();
  9939. } else {
  9940. const err = await res.json();
  9941. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9942. }
  9943. } catch (err) {
  9944. showToast('Error', err.message, 'error');
  9945. }
  9946. }
  9947. function applyOspfInstanceForm() {
  9948. submitOspfInstance(null);
  9949. }
  9950. function copyOspfInstance() {
  9951. document.getElementById('modal-ospf-inst-id').value = '';
  9952. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9953. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9954. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9955. }
  9956. async function deleteCurrentOspfInstance() {
  9957. const id = document.getElementById('modal-ospf-inst-id').value;
  9958. if (!id) return;
  9959. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9960. try {
  9961. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9962. if (res.ok) {
  9963. closeOspfInstanceModal();
  9964. showToast('Removed', 'OSPF instance deleted', 'success');
  9965. loadDynamicRouting();
  9966. }
  9967. } catch (err) {
  9968. showToast('Error', err.message, 'error');
  9969. }
  9970. }
  9971. async function enableSelectedOspfInstance() {
  9972. const id = state.selectedOspfRow?.instances;
  9973. if (!id) return;
  9974. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9975. method: 'POST',
  9976. headers: { 'Content-Type': 'application/json' },
  9977. body: JSON.stringify({ disabled: false })
  9978. });
  9979. loadDynamicRouting();
  9980. }
  9981. async function disableSelectedOspfInstance() {
  9982. const id = state.selectedOspfRow?.instances;
  9983. if (!id) return;
  9984. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9985. method: 'POST',
  9986. headers: { 'Content-Type': 'application/json' },
  9987. body: JSON.stringify({ disabled: true })
  9988. });
  9989. loadDynamicRouting();
  9990. }
  9991. async function removeSelectedOspfInstance() {
  9992. const id = state.selectedOspfRow?.instances;
  9993. if (!id) return;
  9994. if (!confirm('Delete selected OSPF instance?')) return;
  9995. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9996. loadDynamicRouting();
  9997. }
  9998. async function promptCommentOspfInstance() {
  9999. const id = state.selectedOspfRow?.instances;
  10000. if (!id) return;
  10001. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10002. if (!inst) return;
  10003. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10004. if (comment === null) return;
  10005. inst.comment = comment;
  10006. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10007. method: 'POST',
  10008. headers: { 'Content-Type': 'application/json' },
  10009. body: JSON.stringify(inst)
  10010. });
  10011. loadDynamicRouting();
  10012. }
  10013. // --- 2. OSPF AREA ---
  10014. function populateOspfAreaDropdowns() {
  10015. const instSelect = document.getElementById('modal-ospf-area-instance');
  10016. if (instSelect) {
  10017. const cur = instSelect.value;
  10018. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10019. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10020. if (cur) instSelect.value = cur;
  10021. }
  10022. }
  10023. function openOspfAreaModal(id = null) {
  10024. const isEdit = !!id;
  10025. populateOspfAreaDropdowns();
  10026. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10027. id: '',
  10028. name: 'Default',
  10029. instance: 'Default',
  10030. area_id: '0.0.0.0',
  10031. area_type: 'default',
  10032. default_cost: 1,
  10033. no_summaries: false,
  10034. disabled: false,
  10035. comment: ''
  10036. };
  10037. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10038. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10039. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10040. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10041. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10042. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10043. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10044. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10045. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10046. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10047. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10048. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10049. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10050. }
  10051. function openEditOspfAreaModal(id) {
  10052. openOspfAreaModal(id);
  10053. }
  10054. function closeOspfAreaModal() {
  10055. document.getElementById('ospf-area-modal').classList.add('hidden');
  10056. }
  10057. async function submitOspfArea(e) {
  10058. if (e) e.preventDefault();
  10059. const payload = {
  10060. id: document.getElementById('modal-ospf-area-id').value,
  10061. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10062. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10063. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10064. area_type: document.getElementById('modal-ospf-area-type').value,
  10065. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10066. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10067. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10068. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10069. };
  10070. try {
  10071. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10072. method: 'POST',
  10073. headers: { 'Content-Type': 'application/json' },
  10074. body: JSON.stringify(payload)
  10075. });
  10076. if (res.ok) {
  10077. closeOspfAreaModal();
  10078. showToast('Saved', 'OSPF area saved', 'success');
  10079. loadDynamicRouting();
  10080. } else {
  10081. const err = await res.json();
  10082. showToast('Error', err.error || 'Failed to save area', 'error');
  10083. }
  10084. } catch (err) {
  10085. showToast('Error', err.message, 'error');
  10086. }
  10087. }
  10088. function applyOspfAreaForm() {
  10089. submitOspfArea(null);
  10090. }
  10091. function copyOspfArea() {
  10092. document.getElementById('modal-ospf-area-id').value = '';
  10093. document.getElementById('modal-ospf-area-name').value += '-copy';
  10094. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10095. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10096. }
  10097. async function deleteCurrentOspfArea() {
  10098. const id = document.getElementById('modal-ospf-area-id').value;
  10099. if (!id) return;
  10100. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10101. try {
  10102. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10103. if (res.ok) {
  10104. closeOspfAreaModal();
  10105. showToast('Removed', 'OSPF area deleted', 'success');
  10106. loadDynamicRouting();
  10107. }
  10108. } catch (err) {
  10109. showToast('Error', err.message, 'error');
  10110. }
  10111. }
  10112. async function enableSelectedOspfArea() {
  10113. const id = state.selectedOspfRow?.areas;
  10114. if (!id) return;
  10115. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10116. method: 'POST',
  10117. headers: { 'Content-Type': 'application/json' },
  10118. body: JSON.stringify({ disabled: false })
  10119. });
  10120. loadDynamicRouting();
  10121. }
  10122. async function disableSelectedOspfArea() {
  10123. const id = state.selectedOspfRow?.areas;
  10124. if (!id) return;
  10125. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10126. method: 'POST',
  10127. headers: { 'Content-Type': 'application/json' },
  10128. body: JSON.stringify({ disabled: true })
  10129. });
  10130. loadDynamicRouting();
  10131. }
  10132. async function removeSelectedOspfArea() {
  10133. const id = state.selectedOspfRow?.areas;
  10134. if (!id) return;
  10135. if (!confirm('Delete selected OSPF area?')) return;
  10136. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10137. loadDynamicRouting();
  10138. }
  10139. async function promptCommentOspfArea() {
  10140. const id = state.selectedOspfRow?.areas;
  10141. if (!id) return;
  10142. const area = (state.ospfAreas || []).find(a => a.id === id);
  10143. if (!area) return;
  10144. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10145. if (comment === null) return;
  10146. area.comment = comment;
  10147. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10148. method: 'POST',
  10149. headers: { 'Content-Type': 'application/json' },
  10150. body: JSON.stringify(area)
  10151. });
  10152. loadDynamicRouting();
  10153. }
  10154. // --- 3. OSPF AREA RANGE ---
  10155. function populateAreaRangeDropdowns() {
  10156. const select = document.getElementById('modal-ospf-range-area');
  10157. if (select) {
  10158. const cur = select.value;
  10159. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10160. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10161. if (cur) select.value = cur;
  10162. }
  10163. }
  10164. function openOspfAreaRangeModal(id = null) {
  10165. const isEdit = !!id;
  10166. populateAreaRangeDropdowns();
  10167. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10168. id: '',
  10169. area: 'Default',
  10170. prefix: '',
  10171. cost: 1,
  10172. advertise: true,
  10173. disabled: false,
  10174. comment: ''
  10175. };
  10176. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10177. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10178. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10179. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10180. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10181. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10182. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10183. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10184. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10185. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10186. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10187. }
  10188. function openEditOspfAreaRangeModal(id) {
  10189. openOspfAreaRangeModal(id);
  10190. }
  10191. function closeOspfAreaRangeModal() {
  10192. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10193. }
  10194. async function submitOspfAreaRange(e) {
  10195. if (e) e.preventDefault();
  10196. const payload = {
  10197. id: document.getElementById('modal-ospf-range-id').value,
  10198. area: document.getElementById('modal-ospf-range-area').value,
  10199. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10200. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10201. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10202. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10203. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10204. };
  10205. try {
  10206. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10207. method: 'POST',
  10208. headers: { 'Content-Type': 'application/json' },
  10209. body: JSON.stringify(payload)
  10210. });
  10211. if (res.ok) {
  10212. closeOspfAreaRangeModal();
  10213. showToast('Saved', 'Area range saved', 'success');
  10214. loadDynamicRouting();
  10215. } else {
  10216. const err = await res.json();
  10217. showToast('Error', err.error || 'Failed to save area range', 'error');
  10218. }
  10219. } catch (err) {
  10220. showToast('Error', err.message, 'error');
  10221. }
  10222. }
  10223. function applyOspfAreaRangeForm() {
  10224. submitOspfAreaRange(null);
  10225. }
  10226. async function deleteCurrentOspfAreaRange() {
  10227. const id = document.getElementById('modal-ospf-range-id').value;
  10228. if (!id) return;
  10229. if (!confirm('Delete this area range?')) return;
  10230. try {
  10231. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10232. closeOspfAreaRangeModal();
  10233. showToast('Removed', 'Area range removed', 'success');
  10234. loadDynamicRouting();
  10235. } catch (err) {
  10236. showToast('Error', err.message, 'error');
  10237. }
  10238. }
  10239. async function enableSelectedOspfAreaRange() {
  10240. const id = state.selectedOspfRow?.['area-ranges'];
  10241. if (!id) return;
  10242. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10243. if (!r) return;
  10244. r.disabled = false;
  10245. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10246. loadDynamicRouting();
  10247. }
  10248. async function disableSelectedOspfAreaRange() {
  10249. const id = state.selectedOspfRow?.['area-ranges'];
  10250. if (!id) return;
  10251. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10252. if (!r) return;
  10253. r.disabled = true;
  10254. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10255. loadDynamicRouting();
  10256. }
  10257. async function removeSelectedOspfAreaRange() {
  10258. const id = state.selectedOspfRow?.['area-ranges'];
  10259. if (!id) return;
  10260. if (!confirm('Delete selected area range?')) return;
  10261. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10262. loadDynamicRouting();
  10263. }
  10264. async function promptCommentOspfAreaRange() {
  10265. const id = state.selectedOspfRow?.['area-ranges'];
  10266. if (!id) return;
  10267. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10268. if (!r) return;
  10269. const comment = prompt('Enter comment for area range:', r.comment || '');
  10270. if (comment === null) return;
  10271. r.comment = comment;
  10272. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10273. loadDynamicRouting();
  10274. }
  10275. // --- 4. OSPF INTERFACE TEMPLATE ---
  10276. function switchOspfTemplateTab(tab) {
  10277. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10278. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10279. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10280. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10281. if (tab === 'general') {
  10282. if (tabGen) tabGen.classList.remove('hidden');
  10283. if (tabAuth) tabAuth.classList.add('hidden');
  10284. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10285. 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';
  10286. } else {
  10287. if (tabGen) tabGen.classList.add('hidden');
  10288. if (tabAuth) tabAuth.classList.remove('hidden');
  10289. 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';
  10290. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10291. }
  10292. }
  10293. function populateTemplateAreaDropdowns() {
  10294. const select = document.getElementById('modal-ospf-tmpl-area');
  10295. if (select) {
  10296. const cur = select.value;
  10297. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10298. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10299. if (cur) select.value = cur;
  10300. }
  10301. }
  10302. function openOspfTemplateModal(id = null) {
  10303. const isEdit = !!id;
  10304. populateTemplateAreaDropdowns();
  10305. switchOspfTemplateTab('general');
  10306. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10307. id: '',
  10308. interfaces: '',
  10309. area: 'Default',
  10310. networks: '',
  10311. network_type: 'broadcast',
  10312. cost: 1,
  10313. priority: 128,
  10314. passive: false,
  10315. hello_interval: 10,
  10316. dead_interval: 40,
  10317. auth: 'none',
  10318. auth_key: '',
  10319. disabled: false,
  10320. comment: ''
  10321. };
  10322. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10323. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10324. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10325. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10326. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10327. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10328. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10329. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10330. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10331. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10332. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10333. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10334. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10335. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10336. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10337. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10338. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10339. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10340. }
  10341. function openEditOspfTemplateModal(id) {
  10342. openOspfTemplateModal(id);
  10343. }
  10344. function closeOspfTemplateModal() {
  10345. document.getElementById('ospf-template-modal').classList.add('hidden');
  10346. }
  10347. async function submitOspfTemplate(e) {
  10348. if (e) e.preventDefault();
  10349. const payload = {
  10350. id: document.getElementById('modal-ospf-tmpl-id').value,
  10351. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10352. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10353. area: document.getElementById('modal-ospf-tmpl-area').value,
  10354. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10355. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10356. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10357. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10358. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10359. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10360. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10361. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10362. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10363. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10364. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10365. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10366. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10367. };
  10368. try {
  10369. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10370. method: 'POST',
  10371. headers: { 'Content-Type': 'application/json' },
  10372. body: JSON.stringify(payload)
  10373. });
  10374. if (res.ok) {
  10375. closeOspfTemplateModal();
  10376. showToast('Saved', 'Interface template saved', 'success');
  10377. loadDynamicRouting();
  10378. } else {
  10379. const err = await res.json();
  10380. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10381. }
  10382. } catch (err) {
  10383. showToast('Error', err.message, 'error');
  10384. }
  10385. }
  10386. function applyOspfTemplateForm() {
  10387. submitOspfTemplate(null);
  10388. }
  10389. function copyOspfTemplate() {
  10390. document.getElementById('modal-ospf-tmpl-id').value = '';
  10391. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10392. showToast('Copied', 'Duplicated as new template', 'info');
  10393. }
  10394. async function deleteCurrentOspfTemplate() {
  10395. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10396. if (!id) return;
  10397. if (!confirm('Delete this interface template?')) return;
  10398. try {
  10399. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10400. closeOspfTemplateModal();
  10401. showToast('Removed', 'Interface template deleted', 'success');
  10402. loadDynamicRouting();
  10403. } catch (err) {
  10404. showToast('Error', err.message, 'error');
  10405. }
  10406. }
  10407. async function enableSelectedOspfTemplate() {
  10408. const id = state.selectedOspfRow?.templates;
  10409. if (!id) return;
  10410. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10411. method: 'POST',
  10412. headers: { 'Content-Type': 'application/json' },
  10413. body: JSON.stringify({ disabled: false })
  10414. });
  10415. loadDynamicRouting();
  10416. }
  10417. async function disableSelectedOspfTemplate() {
  10418. const id = state.selectedOspfRow?.templates;
  10419. if (!id) return;
  10420. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10421. method: 'POST',
  10422. headers: { 'Content-Type': 'application/json' },
  10423. body: JSON.stringify({ disabled: true })
  10424. });
  10425. loadDynamicRouting();
  10426. }
  10427. async function removeSelectedOspfTemplate() {
  10428. const id = state.selectedOspfRow?.templates;
  10429. if (!id) return;
  10430. if (!confirm('Delete selected interface template?')) return;
  10431. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10432. loadDynamicRouting();
  10433. }
  10434. async function promptCommentOspfTemplate() {
  10435. const id = state.selectedOspfRow?.templates;
  10436. if (!id) return;
  10437. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10438. if (!tmpl) return;
  10439. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10440. if (comment === null) return;
  10441. tmpl.comment = comment;
  10442. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10443. method: 'POST',
  10444. headers: { 'Content-Type': 'application/json' },
  10445. body: JSON.stringify(tmpl)
  10446. });
  10447. loadDynamicRouting();
  10448. }
  10449. // --- 5. OSPF STATIC NEIGHBOR ---
  10450. function populateStaticNbrAreaDropdowns() {
  10451. const select = document.getElementById('modal-ospf-snbr-area');
  10452. if (select) {
  10453. const cur = select.value;
  10454. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10455. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10456. if (cur) select.value = cur;
  10457. }
  10458. }
  10459. function openOspfStaticNbrModal(id = null) {
  10460. const isEdit = !!id;
  10461. populateStaticNbrAreaDropdowns();
  10462. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10463. id: '',
  10464. address: '',
  10465. area: 'Default',
  10466. poll_interval: 120,
  10467. cost: 1,
  10468. disabled: false,
  10469. comment: ''
  10470. };
  10471. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10472. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10473. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10474. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10475. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10476. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10477. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10478. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10479. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10480. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10481. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10482. }
  10483. function openEditOspfStaticNbrModal(id) {
  10484. openOspfStaticNbrModal(id);
  10485. }
  10486. function closeOspfStaticNbrModal() {
  10487. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10488. }
  10489. async function submitOspfStaticNbr(e) {
  10490. if (e) e.preventDefault();
  10491. const payload = {
  10492. id: document.getElementById('modal-ospf-snbr-id').value,
  10493. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10494. area: document.getElementById('modal-ospf-snbr-area').value,
  10495. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10496. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10497. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10498. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10499. };
  10500. try {
  10501. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10502. method: 'POST',
  10503. headers: { 'Content-Type': 'application/json' },
  10504. body: JSON.stringify(payload)
  10505. });
  10506. if (res.ok) {
  10507. closeOspfStaticNbrModal();
  10508. showToast('Saved', 'Static neighbor saved', 'success');
  10509. loadDynamicRouting();
  10510. } else {
  10511. const err = await res.json();
  10512. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10513. }
  10514. } catch (err) {
  10515. showToast('Error', err.message, 'error');
  10516. }
  10517. }
  10518. function applyOspfStaticNbrForm() {
  10519. submitOspfStaticNbr(null);
  10520. }
  10521. async function deleteCurrentOspfStaticNbr() {
  10522. const id = document.getElementById('modal-ospf-snbr-id').value;
  10523. if (!id) return;
  10524. if (!confirm('Delete this static neighbor?')) return;
  10525. try {
  10526. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10527. closeOspfStaticNbrModal();
  10528. showToast('Removed', 'Static neighbor removed', 'success');
  10529. loadDynamicRouting();
  10530. } catch (err) {
  10531. showToast('Error', err.message, 'error');
  10532. }
  10533. }
  10534. async function enableSelectedOspfStaticNbr() {
  10535. const id = state.selectedOspfRow?.['static-nbrs'];
  10536. if (!id) return;
  10537. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10538. loadDynamicRouting();
  10539. }
  10540. async function disableSelectedOspfStaticNbr() {
  10541. const id = state.selectedOspfRow?.['static-nbrs'];
  10542. if (!id) return;
  10543. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10544. loadDynamicRouting();
  10545. }
  10546. async function removeSelectedOspfStaticNbr() {
  10547. const id = state.selectedOspfRow?.['static-nbrs'];
  10548. if (!id) return;
  10549. if (!confirm('Delete selected static neighbor?')) return;
  10550. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10551. loadDynamicRouting();
  10552. }
  10553. async function promptCommentOspfStaticNbr() {
  10554. const id = state.selectedOspfRow?.['static-nbrs'];
  10555. if (!id) return;
  10556. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10557. if (!n) return;
  10558. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10559. if (comment === null) return;
  10560. n.comment = comment;
  10561. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10562. loadDynamicRouting();
  10563. }
  10564. // Backward-compat aliases
  10565. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10566. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10567. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10568. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10569. function deleteOspfInterface(id) {
  10570. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10571. }
  10572. function toggleOspfInterfaceState(id, disabled) {
  10573. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10574. method: 'POST',
  10575. headers: { 'Content-Type': 'application/json' },
  10576. body: JSON.stringify({ disabled })
  10577. }).then(() => loadDynamicRouting());
  10578. }
  10579. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10580. function deleteOspfArea(id) {
  10581. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10582. }
  10583. // ============================================================================
  10584. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10585. // ============================================================================
  10586. function switchBridgeSubTab(tab) {
  10587. state.bridgeSubTab = tab;
  10588. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10589. tabs.forEach(t => {
  10590. const panel = document.getElementById(`bridge-subtab-${t}`);
  10591. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10592. if (panel) {
  10593. if (t === tab) panel.classList.remove('hidden');
  10594. else panel.classList.add('hidden');
  10595. }
  10596. if (btn) {
  10597. if (t === tab) {
  10598. 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';
  10599. } else {
  10600. 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';
  10601. }
  10602. }
  10603. });
  10604. const addBtn = document.getElementById('bridge-top-action-btn');
  10605. if (addBtn) {
  10606. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10607. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10608. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10609. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10610. }
  10611. if (tab === 'hosts') loadBridgeHosts();
  10612. setTimeout(initTableSorting, 50);
  10613. }
  10614. function openCurrentBridgeModal() {
  10615. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10616. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10617. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10618. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10619. }
  10620. async function loadBridge() {
  10621. try {
  10622. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10623. fetch(`${API_BASE}/bridge/bridges`),
  10624. fetch(`${API_BASE}/bridge/ports`),
  10625. fetch(`${API_BASE}/bridge/vlans`),
  10626. fetch(`${API_BASE}/bridge/summary`),
  10627. fetch(`${API_BASE}/vpn/eoip`),
  10628. fetch(`${API_BASE}/vpn/vxlan`),
  10629. fetch(`${API_BASE}/vlans`)
  10630. ]);
  10631. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10632. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10633. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10634. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10635. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10636. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10637. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10638. // Badges & Stats
  10639. const bBridges = document.getElementById('bridge-badge-bridges');
  10640. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10641. const bPorts = document.getElementById('bridge-badge-ports');
  10642. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10643. const bVlans = document.getElementById('bridge-badge-vlans');
  10644. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10645. const bHosts = document.getElementById('bridge-badge-hosts');
  10646. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10647. const sBr = document.getElementById('bridge-stat-bridges');
  10648. if (sBr) sBr.innerText = (state.bridges || []).length;
  10649. const sPorts = document.getElementById('bridge-stat-ports');
  10650. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10651. const sHosts = document.getElementById('bridge-stat-hosts');
  10652. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10653. renderBridges();
  10654. renderBridgePorts();
  10655. renderBridgeVLANs();
  10656. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10657. } catch (err) {
  10658. console.error('Failed to load bridge subsystem:', err);
  10659. }
  10660. }
  10661. // ----------------- Bridges -----------------
  10662. function renderBridges() {
  10663. const tbody = document.getElementById('bridge-table-body');
  10664. const empty = document.getElementById('bridge-empty-bridges');
  10665. const countBadge = document.getElementById('bridge-count-badge');
  10666. if (!tbody) return;
  10667. tbody.innerHTML = '';
  10668. const bridges = state.bridges || [];
  10669. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10670. if (bridges.length === 0) {
  10671. empty?.classList.remove('hidden');
  10672. return;
  10673. }
  10674. empty?.classList.add('hidden');
  10675. bridges.forEach((b, idx) => {
  10676. const tr = document.createElement('tr');
  10677. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10678. // Format IP addresses pill list
  10679. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10680. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10681. ipsHtml = b.ip_addresses.map(ip => `
  10682. <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">
  10683. <span>${ip}</span>
  10684. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10685. </span>
  10686. `).join(' ');
  10687. }
  10688. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10689. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10690. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10691. tr.innerHTML = `
  10692. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10693. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10694. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10695. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10696. </td>
  10697. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10698. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10699. <td class="py-2.5 px-3">
  10700. <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>
  10701. </td>
  10702. <td class="py-2.5 px-3 text-center">
  10703. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10704. </td>
  10705. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10706. <td class="py-2.5 px-3">
  10707. <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>
  10708. </td>
  10709. <td class="py-2.5 px-3">
  10710. <div class="flex items-center gap-1.5 flex-wrap">
  10711. ${ipsHtml}
  10712. <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>
  10713. </div>
  10714. </td>
  10715. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10716. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10717. </td>
  10718. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10719. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10720. <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>
  10721. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10722. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10723. </td>
  10724. `;
  10725. tbody.appendChild(tr);
  10726. });
  10727. }
  10728. function openAddBridgeModal() {
  10729. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10730. document.getElementById('bridge-modal-id').value = '';
  10731. document.getElementById('bridge-modal-name').value = 'bridge1';
  10732. document.getElementById('bridge-modal-name').disabled = false;
  10733. document.getElementById('bridge-modal-mtu').value = '1500';
  10734. document.getElementById('bridge-modal-mac').value = '';
  10735. document.getElementById('bridge-modal-stp').value = 'stp';
  10736. document.getElementById('bridge-modal-priority').value = '32768';
  10737. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10738. document.getElementById('bridge-modal-pvid').value = '1';
  10739. document.getElementById('bridge-modal-fastforward').checked = true;
  10740. document.getElementById('bridge-modal-comment').value = '';
  10741. document.getElementById('bridge-modal-disabled').checked = false;
  10742. toggleBridgeModalVlanFiltering();
  10743. document.getElementById('bridge-modal').classList.remove('hidden');
  10744. }
  10745. function openEditBridgeModal(id) {
  10746. const b = (state.bridges || []).find(x => x.id === id);
  10747. if (!b) return;
  10748. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10749. document.getElementById('bridge-modal-id').value = b.id;
  10750. document.getElementById('bridge-modal-name').value = b.name;
  10751. document.getElementById('bridge-modal-name').disabled = true;
  10752. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10753. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10754. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10755. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10756. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10757. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10758. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10759. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10760. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10761. toggleBridgeModalVlanFiltering();
  10762. document.getElementById('bridge-modal').classList.remove('hidden');
  10763. }
  10764. function closeBridgeModal() {
  10765. document.getElementById('bridge-modal').classList.add('hidden');
  10766. }
  10767. function toggleBridgeModalVlanFiltering() {
  10768. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10769. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10770. if (pvidBox) {
  10771. if (chk) pvidBox.classList.remove('opacity-40');
  10772. else pvidBox.classList.add('opacity-40');
  10773. }
  10774. }
  10775. async function submitSaveBridge(e) {
  10776. e.preventDefault();
  10777. const id = document.getElementById('bridge-modal-id').value;
  10778. const name = document.getElementById('bridge-modal-name').value.trim();
  10779. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10780. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10781. const stp = document.getElementById('bridge-modal-stp').value;
  10782. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10783. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10784. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10785. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10786. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10787. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10788. try {
  10789. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10790. method: 'POST',
  10791. headers: { 'Content-Type': 'application/json' },
  10792. body: JSON.stringify({
  10793. id,
  10794. name,
  10795. mtu,
  10796. mac_address: mac,
  10797. stp,
  10798. priority,
  10799. vlan_filtering: vlanFiltering,
  10800. pvid,
  10801. fast_forward: fastForward,
  10802. comment,
  10803. disabled
  10804. })
  10805. });
  10806. if (res.ok) {
  10807. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10808. closeBridgeModal();
  10809. loadBridge();
  10810. fetchData(false);
  10811. } else {
  10812. const err = await res.json();
  10813. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10814. }
  10815. } catch (err) {
  10816. showToast('Error', err.message, 'error');
  10817. }
  10818. }
  10819. async function toggleBridgeState(id, disabled) {
  10820. try {
  10821. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10822. method: 'POST',
  10823. headers: { 'Content-Type': 'application/json' },
  10824. body: JSON.stringify({ disabled })
  10825. });
  10826. if (res.ok) {
  10827. loadBridge();
  10828. fetchData(false);
  10829. }
  10830. } catch (err) {
  10831. showToast('Error', err.message, 'error');
  10832. }
  10833. }
  10834. async function deleteBridge(id) {
  10835. const b = (state.bridges || []).find(x => x.id === id);
  10836. const name = b ? b.name : id;
  10837. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10838. try {
  10839. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10840. if (res.ok) {
  10841. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10842. loadBridge();
  10843. fetchData(false);
  10844. } else {
  10845. const err = await res.json();
  10846. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10847. }
  10848. } catch (err) {
  10849. showToast('Error', err.message, 'error');
  10850. }
  10851. }
  10852. // ----------------- Bridge IP Assignments -----------------
  10853. function openAddBridgeIPModal(id, name) {
  10854. document.getElementById('bridge-ip-modal-id').value = id;
  10855. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10856. document.getElementById('bridge-ip-modal-cidr').value = '';
  10857. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10858. }
  10859. function closeBridgeIPModal() {
  10860. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10861. }
  10862. async function submitAddBridgeIP(e) {
  10863. e.preventDefault();
  10864. const id = document.getElementById('bridge-ip-modal-id').value;
  10865. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10866. try {
  10867. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10868. method: 'POST',
  10869. headers: { 'Content-Type': 'application/json' },
  10870. body: JSON.stringify({ ip })
  10871. });
  10872. if (res.ok) {
  10873. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10874. closeBridgeIPModal();
  10875. loadBridge();
  10876. fetchData(false);
  10877. } else {
  10878. const err = await res.json();
  10879. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10880. }
  10881. } catch (err) {
  10882. showToast('Error', err.message, 'error');
  10883. }
  10884. }
  10885. async function deleteBridgeIP(id, ip) {
  10886. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10887. try {
  10888. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10889. method: 'DELETE',
  10890. headers: { 'Content-Type': 'application/json' },
  10891. body: JSON.stringify({ ip })
  10892. });
  10893. if (res.ok) {
  10894. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10895. loadBridge();
  10896. fetchData(false);
  10897. }
  10898. } catch (err) {
  10899. showToast('Error', err.message, 'error');
  10900. }
  10901. }
  10902. // ----------------- Bridge Ports -----------------
  10903. function renderBridgePorts() {
  10904. const tbody = document.getElementById('bridge-ports-table-body');
  10905. const empty = document.getElementById('bridge-empty-ports');
  10906. const countBadge = document.getElementById('bridge-ports-count-badge');
  10907. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10908. if (!tbody) return;
  10909. tbody.innerHTML = '';
  10910. // Update filter select
  10911. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10912. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10913. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10914. if (ports.length === 0) {
  10915. empty?.classList.remove('hidden');
  10916. return;
  10917. }
  10918. empty?.classList.add('hidden');
  10919. ports.forEach((p, idx) => {
  10920. const tr = document.createElement('tr');
  10921. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10922. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10923. tr.innerHTML = `
  10924. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10925. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10926. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10927. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10928. </td>
  10929. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10930. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10931. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10932. <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>
  10933. <td class="py-2.5 px-3">
  10934. ${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>'}
  10935. </td>
  10936. <td class="py-2.5 px-3">
  10937. <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>
  10938. </td>
  10939. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10940. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10941. <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>
  10942. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10943. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10944. </td>
  10945. `;
  10946. tbody.appendChild(tr);
  10947. });
  10948. }
  10949. function openAddBridgePortModal() {
  10950. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10951. document.getElementById('bridge-port-modal-id').value = '';
  10952. populateBridgeSelect('bridge-port-modal-bridge');
  10953. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10954. document.getElementById('bridge-port-modal-pvid').value = '1';
  10955. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10956. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10957. document.getElementById('bridge-port-modal-horizon').value = '0';
  10958. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10959. document.getElementById('bridge-port-modal-priority').value = '128';
  10960. document.getElementById('bridge-port-modal-learn').checked = true;
  10961. document.getElementById('bridge-port-modal-comment').value = '';
  10962. document.getElementById('bridge-port-modal-disabled').checked = false;
  10963. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10964. }
  10965. function openEditBridgePortModal(id) {
  10966. const p = (state.bridgePorts || []).find(x => x.id === id);
  10967. if (!p) return;
  10968. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10969. document.getElementById('bridge-port-modal-id').value = p.id;
  10970. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10971. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10972. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10973. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10974. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10975. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10976. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10977. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10978. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10979. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10980. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10981. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10982. }
  10983. function closeBridgePortModal() {
  10984. document.getElementById('bridge-port-modal').classList.add('hidden');
  10985. }
  10986. async function submitSaveBridgePort(e) {
  10987. e.preventDefault();
  10988. const id = document.getElementById('bridge-port-modal-id').value;
  10989. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10990. const iface = document.getElementById('bridge-port-modal-interface').value;
  10991. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10992. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10993. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10994. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10995. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10996. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10997. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10998. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10999. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11000. try {
  11001. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11002. method: 'POST',
  11003. headers: { 'Content-Type': 'application/json' },
  11004. body: JSON.stringify({
  11005. id,
  11006. bridge,
  11007. interface: iface,
  11008. pvid,
  11009. frame_types: frameTypes,
  11010. ingress_filtering: ingressFiltering,
  11011. horizon,
  11012. path_cost: pathCost,
  11013. priority,
  11014. learn,
  11015. comment,
  11016. disabled
  11017. })
  11018. });
  11019. if (res.ok) {
  11020. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11021. closeBridgePortModal();
  11022. loadBridge();
  11023. fetchData(false);
  11024. } else {
  11025. const err = await res.json();
  11026. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11027. }
  11028. } catch (err) {
  11029. showToast('Error', err.message, 'error');
  11030. }
  11031. }
  11032. async function toggleBridgePortState(id, disabled) {
  11033. try {
  11034. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11035. method: 'POST',
  11036. headers: { 'Content-Type': 'application/json' },
  11037. body: JSON.stringify({ disabled })
  11038. });
  11039. if (res.ok) {
  11040. loadBridge();
  11041. fetchData(false);
  11042. }
  11043. } catch (err) {
  11044. showToast('Error', err.message, 'error');
  11045. }
  11046. }
  11047. async function deleteBridgePort(id) {
  11048. const p = (state.bridgePorts || []).find(x => x.id === id);
  11049. const iface = p ? p.interface : id;
  11050. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11051. try {
  11052. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11053. if (res.ok) {
  11054. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11055. loadBridge();
  11056. fetchData(false);
  11057. }
  11058. } catch (err) {
  11059. showToast('Error', err.message, 'error');
  11060. }
  11061. }
  11062. // ----------------- Bridge VLANs -----------------
  11063. function renderBridgeVLANs() {
  11064. const tbody = document.getElementById('bridge-vlans-table-body');
  11065. const empty = document.getElementById('bridge-empty-vlans');
  11066. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11067. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11068. if (!tbody) return;
  11069. tbody.innerHTML = '';
  11070. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11071. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11072. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11073. if (vlans.length === 0) {
  11074. empty?.classList.remove('hidden');
  11075. return;
  11076. }
  11077. empty?.classList.add('hidden');
  11078. vlans.forEach((v, idx) => {
  11079. const tr = document.createElement('tr');
  11080. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11081. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11082. ? 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(' ')
  11083. : '<span class="text-slate-600">none</span>';
  11084. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11085. ? 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(' ')
  11086. : '<span class="text-slate-600">none</span>';
  11087. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11088. tr.innerHTML = `
  11089. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11090. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11091. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11092. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11093. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11094. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11095. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11096. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11097. <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>
  11098. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11099. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11100. </td>
  11101. `;
  11102. tbody.appendChild(tr);
  11103. });
  11104. }
  11105. function openAddBridgeVLANModal() {
  11106. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11107. document.getElementById('bridge-vlan-modal-id').value = '';
  11108. populateBridgeSelect('bridge-vlan-modal-bridge');
  11109. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11110. document.getElementById('bridge-vlan-modal-comment').value = '';
  11111. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11112. updateBridgeVlanPortCheckboxes();
  11113. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11114. }
  11115. function openEditBridgeVLANModal(id) {
  11116. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11117. if (!v) return;
  11118. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11119. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11120. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11121. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11122. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11123. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11124. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11125. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11126. }
  11127. function closeBridgeVlanModal() {
  11128. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11129. }
  11130. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11131. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11132. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11133. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11134. if (!taggedBox || !untaggedBox) return;
  11135. // Ports belonging to the selected bridge
  11136. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11137. if (memberPorts.length === 0) {
  11138. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11139. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11140. return;
  11141. }
  11142. taggedBox.innerHTML = memberPorts.map(p => `
  11143. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11144. <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">
  11145. <span>${p.interface}</span>
  11146. </label>
  11147. `).join('');
  11148. untaggedBox.innerHTML = memberPorts.map(p => `
  11149. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11150. <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">
  11151. <span>${p.interface}</span>
  11152. </label>
  11153. `).join('');
  11154. }
  11155. async function submitSaveBridgeVLAN(e) {
  11156. e.preventDefault();
  11157. const id = document.getElementById('bridge-vlan-modal-id').value;
  11158. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11159. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11160. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11161. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11162. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11163. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11164. try {
  11165. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11166. method: 'POST',
  11167. headers: { 'Content-Type': 'application/json' },
  11168. body: JSON.stringify({
  11169. id,
  11170. bridge,
  11171. vlan_ids: vlanIDs,
  11172. tagged,
  11173. untagged,
  11174. comment,
  11175. disabled
  11176. })
  11177. });
  11178. if (res.ok) {
  11179. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11180. closeBridgeVlanModal();
  11181. loadBridge();
  11182. } else {
  11183. const err = await res.json();
  11184. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11185. }
  11186. } catch (err) {
  11187. showToast('Error', err.message, 'error');
  11188. }
  11189. }
  11190. async function toggleBridgeVLANState(id, disabled) {
  11191. try {
  11192. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11193. method: 'POST',
  11194. headers: { 'Content-Type': 'application/json' },
  11195. body: JSON.stringify({ disabled })
  11196. });
  11197. if (res.ok) loadBridge();
  11198. } catch (err) {
  11199. showToast('Error', err.message, 'error');
  11200. }
  11201. }
  11202. async function deleteBridgeVLAN(id) {
  11203. if (!confirm('Delete this bridge VLAN entry?')) return;
  11204. try {
  11205. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11206. if (res.ok) {
  11207. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11208. loadBridge();
  11209. }
  11210. } catch (err) {
  11211. showToast('Error', err.message, 'error');
  11212. }
  11213. }
  11214. // ----------------- Hosts / MAC Table -----------------
  11215. async function loadBridgeHosts() {
  11216. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11217. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11218. try {
  11219. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11220. const res = await fetch(url);
  11221. if (res.ok) {
  11222. state.bridgeHosts = await res.json();
  11223. renderBridgeHosts();
  11224. }
  11225. } catch (err) {
  11226. console.error('Failed to load bridge hosts:', err);
  11227. }
  11228. }
  11229. function renderBridgeHosts() {
  11230. const tbody = document.getElementById('bridge-hosts-table-body');
  11231. const empty = document.getElementById('bridge-empty-hosts');
  11232. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11233. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11234. if (!tbody) return;
  11235. tbody.innerHTML = '';
  11236. const hosts = (state.bridgeHosts || []).filter(h => {
  11237. if (!search) return true;
  11238. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11239. });
  11240. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11241. if (hosts.length === 0) {
  11242. empty?.classList.remove('hidden');
  11243. return;
  11244. }
  11245. empty?.classList.add('hidden');
  11246. hosts.forEach(h => {
  11247. const tr = document.createElement('tr');
  11248. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11249. let flagBadges = '';
  11250. 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>';
  11251. 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>';
  11252. 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>';
  11253. tr.innerHTML = `
  11254. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11255. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11256. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11257. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11258. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11259. <td class="py-2.5 px-3">${flagBadges}</td>
  11260. `;
  11261. tbody.appendChild(tr);
  11262. });
  11263. }
  11264. async function flushBridgeHosts() {
  11265. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11266. if (!selBridge) {
  11267. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11268. return;
  11269. }
  11270. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11271. try {
  11272. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11273. method: 'POST',
  11274. headers: { 'Content-Type': 'application/json' },
  11275. body: JSON.stringify({ bridge: selBridge })
  11276. });
  11277. if (res.ok) {
  11278. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11279. loadBridgeHosts();
  11280. }
  11281. } catch (err) {
  11282. showToast('Error', err.message, 'error');
  11283. }
  11284. }
  11285. // ----------------- Helpers -----------------
  11286. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11287. const sel = document.getElementById(selectId);
  11288. if (!sel) return;
  11289. const prevVal = currentVal || sel.value;
  11290. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11291. (state.bridges || []).forEach(b => {
  11292. const opt = document.createElement('option');
  11293. opt.value = b.name;
  11294. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11295. if (b.name === prevVal) opt.selected = true;
  11296. sel.appendChild(opt);
  11297. });
  11298. }
  11299. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11300. const sel = document.getElementById(selectId);
  11301. if (!sel) return;
  11302. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11303. // 1. Physical Interfaces
  11304. const grpPhys = document.createElement('optgroup');
  11305. grpPhys.label = 'Physical Interfaces';
  11306. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11307. const opt = document.createElement('option');
  11308. opt.value = i.name;
  11309. opt.innerText = `${i.name} (${i.role || i.type})`;
  11310. if (i.name === currentVal) opt.selected = true;
  11311. grpPhys.appendChild(opt);
  11312. });
  11313. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11314. // 2. VLAN Sub-interfaces
  11315. const grpVlans = document.createElement('optgroup');
  11316. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11317. (state.vlans || []).forEach(v => {
  11318. const opt = document.createElement('option');
  11319. opt.value = v.name;
  11320. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11321. if (v.name === currentVal) opt.selected = true;
  11322. grpVlans.appendChild(opt);
  11323. });
  11324. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11325. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11326. const grpEoip = document.createElement('optgroup');
  11327. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11328. (state.eoipTunnels || []).forEach(t => {
  11329. const opt = document.createElement('option');
  11330. opt.value = t.name;
  11331. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11332. if (t.name === currentVal) opt.selected = true;
  11333. grpEoip.appendChild(opt);
  11334. });
  11335. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11336. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11337. const grpVxlan = document.createElement('optgroup');
  11338. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11339. (state.vxlanTunnels || []).forEach(t => {
  11340. const opt = document.createElement('option');
  11341. opt.value = t.name;
  11342. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11343. if (t.name === currentVal) opt.selected = true;
  11344. grpVxlan.appendChild(opt);
  11345. });
  11346. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11347. }
  11348. // -------------------------------------------------------------
  11349. // DebTik Routing Filters Management (/routing filter)
  11350. // -------------------------------------------------------------
  11351. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11352. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11353. if (!state.rfSort) state.rfSort = {};
  11354. function switchRoutingFilterTab(tab) {
  11355. state.activeRoutingFilterTab = tab;
  11356. const tabs = ['rules', 'community-lists', 'as-lists'];
  11357. tabs.forEach(t => {
  11358. const btn = document.getElementById(`tab-rf-${t}`);
  11359. const content = document.getElementById(`tab-content-rf-${t}`);
  11360. if (btn) {
  11361. if (t === tab) {
  11362. 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';
  11363. } else {
  11364. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11365. }
  11366. }
  11367. if (content) {
  11368. if (t === tab) content.classList.remove('hidden');
  11369. else content.classList.add('hidden');
  11370. }
  11371. });
  11372. const chainContainer = document.getElementById('rf-chain-filter-container');
  11373. if (chainContainer) {
  11374. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11375. else chainContainer.classList.add('hidden');
  11376. }
  11377. renderRoutingFilters();
  11378. }
  11379. function selectFilterRow(tab, id) {
  11380. if (state.selectedFilterRow[tab] === id) {
  11381. delete state.selectedFilterRow[tab];
  11382. } else {
  11383. state.selectedFilterRow[tab] = id;
  11384. }
  11385. if (tab === 'rules') renderRoutingFilterRules();
  11386. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11387. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11388. }
  11389. function openRoutingFilterNewModal() {
  11390. const tab = state.activeRoutingFilterTab || 'rules';
  11391. if (tab === 'rules') openAddRoutingFilterModal();
  11392. else if (tab === 'community-lists') openAddCommunityListModal();
  11393. else if (tab === 'as-lists') openAddASListModal();
  11394. }
  11395. function toggleSelectedRoutingFilter(disabled) {
  11396. const tab = state.activeRoutingFilterTab || 'rules';
  11397. const id = state.selectedFilterRow[tab];
  11398. if (!id) {
  11399. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11400. return;
  11401. }
  11402. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11403. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11404. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11405. }
  11406. function removeSelectedRoutingFilter() {
  11407. const tab = state.activeRoutingFilterTab || 'rules';
  11408. const id = state.selectedFilterRow[tab];
  11409. if (!id) {
  11410. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11411. return;
  11412. }
  11413. if (tab === 'rules') deleteRoutingFilter(id);
  11414. else if (tab === 'community-lists') deleteCommunityList(id);
  11415. else if (tab === 'as-lists') deleteASList(id);
  11416. }
  11417. function searchRoutingFilters(q) {
  11418. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11419. renderRoutingFilters();
  11420. }
  11421. function sortFilterTable(tab, col) {
  11422. if (!state.rfSort) state.rfSort = {};
  11423. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11424. if (state.rfSort[tab].col === col) {
  11425. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11426. } else {
  11427. state.rfSort[tab].col = col;
  11428. state.rfSort[tab].asc = true;
  11429. }
  11430. const asc = state.rfSort[tab].asc;
  11431. let list = [];
  11432. if (tab === 'rules') list = state.routingFilters || [];
  11433. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11434. else if (tab === 'as-lists') list = state.routingASLists || [];
  11435. list.sort((a, b) => {
  11436. let valA = a[col] ?? '';
  11437. let valB = b[col] ?? '';
  11438. if (col === 'flags') {
  11439. valA = a.disabled ? 'X' : 'A';
  11440. valB = b.disabled ? 'X' : 'A';
  11441. }
  11442. if (typeof valA === 'number' && typeof valB === 'number') {
  11443. return asc ? valA - valB : valB - valA;
  11444. }
  11445. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11446. });
  11447. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11448. allCols.forEach(c => {
  11449. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11450. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11451. });
  11452. if (tab === 'rules') renderRoutingFilterRules();
  11453. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11454. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11455. }
  11456. function renderRoutingFilters() {
  11457. const navBadge = document.getElementById('badge-filters-count');
  11458. const allRules = state.routingFilters || [];
  11459. if (navBadge) navBadge.innerText = allRules.length;
  11460. // Populate chain filter select options and datalist
  11461. const chainSelect = document.getElementById('routing-filter-chain-select');
  11462. const chainDatalist = document.getElementById('dl-routing-chains');
  11463. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11464. if (chainSelect) {
  11465. const currentVal = state.filterChainSelected || 'all';
  11466. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11467. uniqueChains.map(ch => {
  11468. const count = allRules.filter(r => r.chain === ch).length;
  11469. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11470. }).join('');
  11471. chainSelect.value = currentVal;
  11472. }
  11473. if (chainDatalist) {
  11474. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11475. }
  11476. renderRoutingFilterRules();
  11477. renderRoutingFilterCommunityLists();
  11478. renderRoutingFilterASLists();
  11479. }
  11480. function filterRoutingFiltersByChain(chain) {
  11481. state.filterChainSelected = chain;
  11482. renderRoutingFilters();
  11483. }
  11484. // -------------------------------------------------------------
  11485. // TAB 1: RULES (/routing filter rule)
  11486. // -------------------------------------------------------------
  11487. function renderRoutingFilterRules() {
  11488. const tbody = document.getElementById('routing-filter-rules-tbody');
  11489. if (!tbody) return;
  11490. const empty = document.getElementById('rf-rules-empty');
  11491. const statusCount = document.getElementById('rf-status-count');
  11492. let list = (state.routingFilters || []).slice();
  11493. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11494. list = list.filter(r => r.chain === state.filterChainSelected);
  11495. }
  11496. const q = state.rfSearchQuery;
  11497. if (q) {
  11498. list = list.filter(r =>
  11499. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11500. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11501. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11502. (r.comment && r.comment.toLowerCase().includes(q))
  11503. );
  11504. }
  11505. if (!state.rfSort?.['rules']) {
  11506. list.sort((a, b) => {
  11507. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11508. return (a.rule_order || 0) - (b.rule_order || 0);
  11509. });
  11510. }
  11511. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11512. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11513. }
  11514. if (list.length === 0) {
  11515. tbody.innerHTML = '';
  11516. if (empty) empty.classList.remove('hidden');
  11517. return;
  11518. }
  11519. if (empty) empty.classList.add('hidden');
  11520. tbody.innerHTML = list.map(r => {
  11521. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11522. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11523. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11524. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11525. let ruleDisplay = '';
  11526. if (r.rule && r.rule.trim() !== '') {
  11527. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11528. } else {
  11529. let conds = [];
  11530. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11531. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11532. let act = r.action || 'accept';
  11533. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11534. }
  11535. return `
  11536. <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'}">
  11537. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11538. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11539. <td class="py-2 px-3">
  11540. <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>
  11541. </td>
  11542. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11543. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11544. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11545. <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>
  11546. <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>
  11547. <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'}">
  11548. ${r.disabled ? 'Enable' : 'Disable'}
  11549. </button>
  11550. <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">
  11551. Edit
  11552. </button>
  11553. <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">
  11554. ✕
  11555. </button>
  11556. </td>
  11557. </tr>
  11558. `;
  11559. }).join('');
  11560. }
  11561. // -------------------------------------------------------------
  11562. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11563. // -------------------------------------------------------------
  11564. function renderRoutingFilterCommunityLists() {
  11565. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11566. if (!tbody) return;
  11567. const empty = document.getElementById('rf-comm-lists-empty');
  11568. const statusCount = document.getElementById('rf-status-count');
  11569. let list = (state.routingCommunityLists || []).slice();
  11570. const q = state.rfSearchQuery;
  11571. if (q) {
  11572. list = list.filter(cl =>
  11573. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11574. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11575. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11576. );
  11577. }
  11578. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11579. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11580. }
  11581. if (list.length === 0) {
  11582. tbody.innerHTML = '';
  11583. if (empty) empty.classList.remove('hidden');
  11584. return;
  11585. }
  11586. if (empty) empty.classList.add('hidden');
  11587. tbody.innerHTML = list.map(cl => {
  11588. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11589. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11590. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11591. const commBadges = (cl.communities || []).map(c =>
  11592. `<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>`
  11593. ).join(' ');
  11594. return `
  11595. <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'}">
  11596. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11597. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11598. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11599. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11600. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11601. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11602. <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'}">
  11603. ${cl.disabled ? 'Enable' : 'Disable'}
  11604. </button>
  11605. <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">
  11606. Edit
  11607. </button>
  11608. <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">
  11609. ✕
  11610. </button>
  11611. </td>
  11612. </tr>
  11613. `;
  11614. }).join('');
  11615. }
  11616. // -------------------------------------------------------------
  11617. // TAB 4: AS LISTS (/routing filter num-list)
  11618. // -------------------------------------------------------------
  11619. function renderRoutingFilterASLists() {
  11620. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11621. if (!tbody) return;
  11622. const empty = document.getElementById('rf-as-lists-empty');
  11623. const statusCount = document.getElementById('rf-status-count');
  11624. let list = (state.routingASLists || []).slice();
  11625. const q = state.rfSearchQuery;
  11626. if (q) {
  11627. list = list.filter(al =>
  11628. (al.name && al.name.toLowerCase().includes(q)) ||
  11629. (al.range && al.range.toLowerCase().includes(q)) ||
  11630. (al.comment && al.comment.toLowerCase().includes(q))
  11631. );
  11632. }
  11633. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11634. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11635. }
  11636. if (list.length === 0) {
  11637. tbody.innerHTML = '';
  11638. if (empty) empty.classList.remove('hidden');
  11639. return;
  11640. }
  11641. if (empty) empty.classList.add('hidden');
  11642. tbody.innerHTML = list.map(al => {
  11643. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11644. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11645. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11646. return `
  11647. <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'}">
  11648. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11649. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11650. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11651. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11652. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11653. <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'}">
  11654. ${al.disabled ? 'Enable' : 'Disable'}
  11655. </button>
  11656. <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">
  11657. Edit
  11658. </button>
  11659. <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">
  11660. ✕
  11661. </button>
  11662. </td>
  11663. </tr>
  11664. `;
  11665. }).join('');
  11666. }
  11667. // -------------------------------------------------------------
  11668. // SNIPPETS & WIZARD HELPERS
  11669. // -------------------------------------------------------------
  11670. function insertRuleSnippet(type) {
  11671. const textarea = document.getElementById('modal-rf-rule');
  11672. if (!textarea) return;
  11673. let snippet = '';
  11674. switch (type) {
  11675. case 'accept-default':
  11676. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11677. break;
  11678. case 'drop-rfc1918':
  11679. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11680. break;
  11681. case 'len-24':
  11682. snippet = 'if (dst-len > 24) { reject; }';
  11683. break;
  11684. case 'local-pref-150':
  11685. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11686. break;
  11687. case 'as-prepend-2':
  11688. snippet = 'set bgp-path-prepend 2; accept;';
  11689. break;
  11690. case 'set-comm':
  11691. snippet = 'set bgp-communities.add 65000:100; accept;';
  11692. break;
  11693. case 'match-comm':
  11694. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11695. break;
  11696. case 'reject-all':
  11697. snippet = 'reject;';
  11698. break;
  11699. }
  11700. if (!snippet) return;
  11701. if (!textarea.value.trim()) {
  11702. textarea.value = snippet;
  11703. } else {
  11704. textarea.value = textarea.value.trim() + '\n' + snippet;
  11705. }
  11706. }
  11707. function generateScriptFromWizard() {
  11708. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11709. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11710. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11711. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11712. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11713. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11714. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11715. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11716. const conds = [];
  11717. if (pfx) {
  11718. if (pfxLen) {
  11719. if (pfxLen.includes('-')) {
  11720. const parts = pfxLen.split('-');
  11721. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11722. } else {
  11723. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11724. }
  11725. } else {
  11726. conds.push(`dst in ${pfx}`);
  11727. }
  11728. }
  11729. if (proto && proto !== 'any') {
  11730. conds.push(`protocol ${proto}`);
  11731. }
  11732. if (asp) {
  11733. conds.push(`bgp-as-path "${asp}"`);
  11734. }
  11735. if (comm) {
  11736. conds.push(`bgp-communities includes ${comm}`);
  11737. }
  11738. const actions = [];
  11739. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11740. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11741. if (act && act !== 'passthrough') {
  11742. actions.push(`${act};`);
  11743. }
  11744. let code = '';
  11745. if (conds.length > 0) {
  11746. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11747. } else {
  11748. code = actions.join(' ');
  11749. }
  11750. const textarea = document.getElementById('modal-rf-rule');
  11751. if (textarea) textarea.value = code;
  11752. }
  11753. // -------------------------------------------------------------
  11754. // MODAL CRUD: RULES (/routing filter rule)
  11755. // -------------------------------------------------------------
  11756. function openAddRoutingFilterModal(defaultChain = '') {
  11757. const form = document.getElementById('routing-filter-form');
  11758. if (form) form.reset();
  11759. const idEl = document.getElementById('modal-rf-id');
  11760. if (idEl) idEl.value = '';
  11761. const titleEl = document.getElementById('modal-rf-title');
  11762. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11763. const chainEl = document.getElementById('modal-rf-chain');
  11764. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11765. const orderEl = document.getElementById('modal-rf-order');
  11766. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11767. const ruleEl = document.getElementById('modal-rf-rule');
  11768. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11769. const disEl = document.getElementById('modal-rf-disabled');
  11770. if (disEl) disEl.checked = false;
  11771. const modal = document.getElementById('modal-routing-filter');
  11772. if (modal) modal.classList.remove('hidden');
  11773. }
  11774. function openEditRoutingFilterModal(id) {
  11775. const r = (state.routingFilters || []).find(item => item.id === id);
  11776. if (!r) return;
  11777. const idEl = document.getElementById('modal-rf-id');
  11778. if (idEl) idEl.value = r.id;
  11779. const titleEl = document.getElementById('modal-rf-title');
  11780. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11781. const chainEl = document.getElementById('modal-rf-chain');
  11782. if (chainEl) chainEl.value = r.chain || '';
  11783. const orderEl = document.getElementById('modal-rf-order');
  11784. if (orderEl) orderEl.value = r.rule_order || 10;
  11785. const ruleEl = document.getElementById('modal-rf-rule');
  11786. if (ruleEl) {
  11787. if (r.rule) {
  11788. ruleEl.value = r.rule;
  11789. } else {
  11790. let conds = [];
  11791. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11792. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11793. let act = r.action || 'accept';
  11794. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11795. }
  11796. }
  11797. const comEl = document.getElementById('modal-rf-comment');
  11798. if (comEl) comEl.value = r.comment || '';
  11799. const disEl = document.getElementById('modal-rf-disabled');
  11800. if (disEl) disEl.checked = !!r.disabled;
  11801. const modal = document.getElementById('modal-routing-filter');
  11802. if (modal) modal.classList.remove('hidden');
  11803. }
  11804. function closeRoutingFilterModal() {
  11805. const modal = document.getElementById('modal-routing-filter');
  11806. if (modal) modal.classList.add('hidden');
  11807. }
  11808. async function submitRoutingFilter(e) {
  11809. if (e) e.preventDefault();
  11810. const payload = {
  11811. id: document.getElementById('modal-rf-id').value,
  11812. chain: document.getElementById('modal-rf-chain').value.trim(),
  11813. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11814. rule: document.getElementById('modal-rf-rule').value.trim(),
  11815. comment: document.getElementById('modal-rf-comment').value.trim(),
  11816. disabled: document.getElementById('modal-rf-disabled').checked
  11817. };
  11818. try {
  11819. const res = await fetch(`${API_BASE}/routing/filters`, {
  11820. method: 'POST',
  11821. headers: { 'Content-Type': 'application/json' },
  11822. body: JSON.stringify(payload)
  11823. });
  11824. if (res.ok) {
  11825. closeRoutingFilterModal();
  11826. showToast('Success', 'Routing filter rule saved', 'success');
  11827. loadDynamicRouting();
  11828. } else {
  11829. const err = await res.json();
  11830. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11831. }
  11832. } catch (err) {
  11833. showToast('Error', err.message, 'error');
  11834. }
  11835. }
  11836. async function applyRoutingFilterForm() {
  11837. const payload = {
  11838. id: document.getElementById('modal-rf-id').value,
  11839. chain: document.getElementById('modal-rf-chain').value.trim(),
  11840. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11841. rule: document.getElementById('modal-rf-rule').value.trim(),
  11842. comment: document.getElementById('modal-rf-comment').value.trim(),
  11843. disabled: document.getElementById('modal-rf-disabled').checked
  11844. };
  11845. try {
  11846. const res = await fetch(`${API_BASE}/routing/filters`, {
  11847. method: 'POST',
  11848. headers: { 'Content-Type': 'application/json' },
  11849. body: JSON.stringify(payload)
  11850. });
  11851. if (res.ok) {
  11852. const data = await res.json();
  11853. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11854. showToast('Applied', 'Routing filter configuration applied', 'success');
  11855. loadDynamicRouting();
  11856. } else {
  11857. const err = await res.json();
  11858. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11859. }
  11860. } catch (err) {
  11861. showToast('Error', err.message, 'error');
  11862. }
  11863. }
  11864. async function moveRoutingFilterOrder(id, delta) {
  11865. const list = state.routingFilters || [];
  11866. const idx = list.findIndex(r => r.id === id);
  11867. if (idx < 0) return;
  11868. const targetIdx = idx + delta;
  11869. if (targetIdx < 0 || targetIdx >= list.length) return;
  11870. const currentOrder = list[idx].rule_order || 10;
  11871. const targetOrder = list[targetIdx].rule_order || 20;
  11872. list[idx].rule_order = targetOrder;
  11873. list[targetIdx].rule_order = currentOrder;
  11874. try {
  11875. await fetch(`${API_BASE}/routing/filters`, {
  11876. method: 'POST',
  11877. headers: { 'Content-Type': 'application/json' },
  11878. body: JSON.stringify(list[idx])
  11879. });
  11880. await fetch(`${API_BASE}/routing/filters`, {
  11881. method: 'POST',
  11882. headers: { 'Content-Type': 'application/json' },
  11883. body: JSON.stringify(list[targetIdx])
  11884. });
  11885. loadDynamicRouting();
  11886. } catch (e) {
  11887. console.error('Reorder error:', e);
  11888. }
  11889. }
  11890. async function deleteRoutingFilter(id) {
  11891. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11892. try {
  11893. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11894. if (res.ok) {
  11895. showToast('Deleted', 'Routing filter rule removed', 'info');
  11896. loadDynamicRouting();
  11897. } else {
  11898. const err = await res.json();
  11899. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11900. }
  11901. } catch (err) {
  11902. showToast('Error', err.message, 'error');
  11903. }
  11904. }
  11905. async function toggleRoutingFilterState(id, disabled) {
  11906. try {
  11907. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11908. method: 'POST',
  11909. headers: { 'Content-Type': 'application/json' },
  11910. body: JSON.stringify({ disabled })
  11911. });
  11912. if (res.ok) {
  11913. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11914. loadDynamicRouting();
  11915. } else {
  11916. const err = await res.json();
  11917. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11918. }
  11919. } catch (err) {
  11920. showToast('Error', err.message, 'error');
  11921. }
  11922. }
  11923. // -------------------------------------------------------------
  11924. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11925. // -------------------------------------------------------------
  11926. function openAddCommunityListModal() {
  11927. document.getElementById('modal-rf-cl-id').value = '';
  11928. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11929. document.getElementById('modal-rf-cl-name').value = '';
  11930. document.getElementById('modal-rf-cl-communities').value = '';
  11931. document.getElementById('modal-rf-cl-regexp').value = '';
  11932. document.getElementById('modal-rf-cl-comment').value = '';
  11933. document.getElementById('modal-rf-cl-disabled').checked = false;
  11934. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11935. }
  11936. function openEditCommunityListModal(id) {
  11937. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11938. if (!cl) return;
  11939. document.getElementById('modal-rf-cl-id').value = cl.id;
  11940. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11941. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11942. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11943. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11944. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11945. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11946. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11947. }
  11948. function closeCommunityListModal() {
  11949. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11950. }
  11951. async function submitCommunityList(e) {
  11952. e.preventDefault();
  11953. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11954. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11955. const payload = {
  11956. id: document.getElementById('modal-rf-cl-id').value,
  11957. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11958. communities: comms,
  11959. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11960. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11961. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11962. };
  11963. try {
  11964. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11965. method: 'POST',
  11966. headers: { 'Content-Type': 'application/json' },
  11967. body: JSON.stringify(payload)
  11968. });
  11969. if (res.ok) {
  11970. closeCommunityListModal();
  11971. showToast('Success', 'Community list saved', 'success');
  11972. loadDynamicRouting();
  11973. } else {
  11974. const err = await res.json();
  11975. showToast('Error', err.error || 'Failed to save community list', 'error');
  11976. }
  11977. } catch (err) {
  11978. showToast('Error', err.message, 'error');
  11979. }
  11980. }
  11981. async function deleteCommunityList(id) {
  11982. if (!confirm('Are you sure you want to delete this community list?')) return;
  11983. try {
  11984. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11985. if (res.ok) {
  11986. showToast('Deleted', 'Community list removed', 'info');
  11987. loadDynamicRouting();
  11988. } else {
  11989. const err = await res.json();
  11990. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11991. }
  11992. } catch (err) {
  11993. showToast('Error', err.message, 'error');
  11994. }
  11995. }
  11996. async function toggleCommunityListState(id, disabled) {
  11997. try {
  11998. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11999. method: 'POST',
  12000. headers: { 'Content-Type': 'application/json' },
  12001. body: JSON.stringify({ disabled })
  12002. });
  12003. if (res.ok) {
  12004. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12005. loadDynamicRouting();
  12006. } else {
  12007. const err = await res.json();
  12008. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12009. }
  12010. } catch (err) {
  12011. showToast('Error', err.message, 'error');
  12012. }
  12013. }
  12014. // -------------------------------------------------------------
  12015. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12016. // -------------------------------------------------------------
  12017. function openAddASListModal() {
  12018. document.getElementById('modal-rf-al-id').value = '';
  12019. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12020. document.getElementById('modal-rf-al-name').value = '';
  12021. document.getElementById('modal-rf-al-range').value = '';
  12022. document.getElementById('modal-rf-al-comment').value = '';
  12023. document.getElementById('modal-rf-al-disabled').checked = false;
  12024. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12025. }
  12026. function openEditASListModal(id) {
  12027. const al = (state.routingASLists || []).find(item => item.id === id);
  12028. if (!al) return;
  12029. document.getElementById('modal-rf-al-id').value = al.id;
  12030. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12031. document.getElementById('modal-rf-al-name').value = al.name || '';
  12032. document.getElementById('modal-rf-al-range').value = al.range || '';
  12033. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12034. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12035. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12036. }
  12037. function closeASListModal() {
  12038. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12039. }
  12040. async function submitASList(e) {
  12041. e.preventDefault();
  12042. const payload = {
  12043. id: document.getElementById('modal-rf-al-id').value,
  12044. name: document.getElementById('modal-rf-al-name').value.trim(),
  12045. range: document.getElementById('modal-rf-al-range').value.trim(),
  12046. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12047. disabled: document.getElementById('modal-rf-al-disabled').checked
  12048. };
  12049. try {
  12050. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12051. method: 'POST',
  12052. headers: { 'Content-Type': 'application/json' },
  12053. body: JSON.stringify(payload)
  12054. });
  12055. if (res.ok) {
  12056. closeASListModal();
  12057. showToast('Success', 'AS number list saved', 'success');
  12058. loadDynamicRouting();
  12059. } else {
  12060. const err = await res.json();
  12061. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12062. }
  12063. } catch (err) {
  12064. showToast('Error', err.message, 'error');
  12065. }
  12066. }
  12067. async function deleteASList(id) {
  12068. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12069. try {
  12070. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12071. if (res.ok) {
  12072. showToast('Deleted', 'AS list removed', 'info');
  12073. loadDynamicRouting();
  12074. } else {
  12075. const err = await res.json();
  12076. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12077. }
  12078. } catch (err) {
  12079. showToast('Error', err.message, 'error');
  12080. }
  12081. }
  12082. async function toggleASListState(id, disabled) {
  12083. try {
  12084. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12085. method: 'POST',
  12086. headers: { 'Content-Type': 'application/json' },
  12087. body: JSON.stringify({ disabled })
  12088. });
  12089. if (res.ok) {
  12090. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12091. loadDynamicRouting();
  12092. } else {
  12093. const err = await res.json();
  12094. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12095. }
  12096. } catch (err) {
  12097. showToast('Error', err.message, 'error');
  12098. }
  12099. }
  12100. // ==========================================
  12101. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12102. // ==========================================
  12103. function loadToolsView() {
  12104. populateToolsInterfaces();
  12105. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12106. }
  12107. function populateToolsInterfaces() {
  12108. const pingSel = document.getElementById('tools-ping-iface');
  12109. const traceSel = document.getElementById('tools-tr-iface');
  12110. let opts = '<option value="">Auto (Default Route)</option>';
  12111. if (Array.isArray(state.interfaces)) {
  12112. state.interfaces.forEach(iface => {
  12113. if (iface.name) {
  12114. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12115. }
  12116. });
  12117. }
  12118. if (pingSel) {
  12119. const cur = pingSel.value;
  12120. pingSel.innerHTML = opts;
  12121. if (cur) pingSel.value = cur;
  12122. }
  12123. if (traceSel) {
  12124. const cur = traceSel.value;
  12125. traceSel.innerHTML = opts;
  12126. if (cur) traceSel.value = cur;
  12127. }
  12128. }
  12129. function switchToolsSubTab(subTab) {
  12130. state.activeToolsSubTab = subTab;
  12131. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12132. tabs.forEach(t => {
  12133. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12134. const view = document.getElementById(`tools-view-${t}`);
  12135. if (btn) {
  12136. if (t === subTab) {
  12137. 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';
  12138. } else {
  12139. 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';
  12140. }
  12141. }
  12142. if (view) {
  12143. if (t === subTab) {
  12144. view.classList.remove('hidden');
  12145. } else {
  12146. view.classList.add('hidden');
  12147. }
  12148. }
  12149. });
  12150. }
  12151. function setPortPreset(port) {
  12152. const input = document.getElementById('tools-port-num');
  12153. if (input) input.value = port;
  12154. }
  12155. let pingAbortController = null;
  12156. let tracerouteAbortController = null;
  12157. function clearPingTable() {
  12158. const tbody = document.getElementById('tools-ping-tbody');
  12159. if (tbody) tbody.innerHTML = '';
  12160. const rawEl = document.getElementById('tools-ping-raw');
  12161. if (rawEl) rawEl.innerText = '';
  12162. const sentEl = document.getElementById('tools-ping-stat-sent');
  12163. if (sentEl) sentEl.innerText = '0';
  12164. const recvEl = document.getElementById('tools-ping-stat-recv');
  12165. if (recvEl) recvEl.innerText = '0';
  12166. const lossEl = document.getElementById('tools-ping-stat-loss');
  12167. if (lossEl) lossEl.innerText = '0%';
  12168. const avgEl = document.getElementById('tools-ping-stat-avg');
  12169. if (avgEl) avgEl.innerText = '0 ms';
  12170. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12171. if (minMaxEl) minMaxEl.innerText = '-';
  12172. const badge = document.getElementById('tools-ping-status-badge');
  12173. if (badge) {
  12174. badge.className = '';
  12175. badge.innerText = '';
  12176. }
  12177. }
  12178. function clearTracerouteTable() {
  12179. const tbody = document.getElementById('tools-tr-tbody');
  12180. if (tbody) tbody.innerHTML = '';
  12181. const rawEl = document.getElementById('tools-tr-raw');
  12182. if (rawEl) rawEl.innerText = '';
  12183. const statHops = document.getElementById('tools-tr-hops-count');
  12184. if (statHops) statHops.innerText = '0 Hops';
  12185. }
  12186. function resetPingButton() {
  12187. const btn = document.getElementById('tools-ping-btn');
  12188. const btnText = document.getElementById('tools-ping-btn-text');
  12189. const spinner = document.getElementById('tools-ping-spinner');
  12190. if (btn) {
  12191. btn.disabled = false;
  12192. 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';
  12193. }
  12194. if (btnText) btnText.innerText = 'Start Ping';
  12195. if (spinner) spinner.classList.add('hidden');
  12196. }
  12197. function setPingRunningButton() {
  12198. const btn = document.getElementById('tools-ping-btn');
  12199. const btnText = document.getElementById('tools-ping-btn-text');
  12200. const spinner = document.getElementById('tools-ping-spinner');
  12201. if (btn) {
  12202. btn.disabled = false;
  12203. 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';
  12204. }
  12205. if (btnText) btnText.innerText = 'Stop Ping';
  12206. if (spinner) spinner.classList.remove('hidden');
  12207. }
  12208. function resetTracerouteButton() {
  12209. const btn = document.getElementById('tools-tr-btn');
  12210. const btnText = document.getElementById('tools-tr-btn-text');
  12211. const spinner = document.getElementById('tools-tr-spinner');
  12212. if (btn) {
  12213. btn.disabled = false;
  12214. 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';
  12215. }
  12216. if (btnText) btnText.innerText = 'Start Traceroute';
  12217. if (spinner) spinner.classList.add('hidden');
  12218. }
  12219. function setTracerouteRunningButton() {
  12220. const btn = document.getElementById('tools-tr-btn');
  12221. const btnText = document.getElementById('tools-tr-btn-text');
  12222. const spinner = document.getElementById('tools-tr-spinner');
  12223. if (btn) {
  12224. btn.disabled = false;
  12225. 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';
  12226. }
  12227. if (btnText) btnText.innerText = 'Stop Traceroute';
  12228. if (spinner) spinner.classList.remove('hidden');
  12229. }
  12230. async function executePing(e) {
  12231. if (e) e.preventDefault();
  12232. // If already running, clicking the button stops the stream!
  12233. if (pingAbortController) {
  12234. pingAbortController.abort();
  12235. pingAbortController = null;
  12236. resetPingButton();
  12237. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12238. return;
  12239. }
  12240. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12241. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12242. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12243. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12244. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12245. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12246. if (!target) {
  12247. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12248. return;
  12249. }
  12250. clearPingTable();
  12251. const resCard = document.getElementById('tools-ping-results');
  12252. if (resCard) resCard.classList.remove('hidden');
  12253. pingAbortController = new AbortController();
  12254. setPingRunningButton();
  12255. try {
  12256. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12257. method: 'POST',
  12258. headers: { 'Content-Type': 'application/json' },
  12259. body: JSON.stringify({
  12260. target,
  12261. count,
  12262. size,
  12263. timeout,
  12264. interface: iface,
  12265. dont_frag: dontFrag
  12266. }),
  12267. signal: pingAbortController.signal
  12268. });
  12269. if (!res.ok) {
  12270. const errText = await res.text();
  12271. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12272. resetPingButton();
  12273. pingAbortController = null;
  12274. return;
  12275. }
  12276. const reader = res.body.getReader();
  12277. const decoder = new TextDecoder('utf-8');
  12278. let buffer = '';
  12279. while (true) {
  12280. const { done, value } = await reader.read();
  12281. if (done) break;
  12282. buffer += decoder.decode(value, { stream: true });
  12283. const blocks = buffer.split('\n\n');
  12284. buffer = blocks.pop() || '';
  12285. for (const block of blocks) {
  12286. const trimmed = block.trim();
  12287. if (!trimmed) continue;
  12288. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12289. try {
  12290. const evt = JSON.parse(line);
  12291. handleLivePingEvent(evt);
  12292. } catch (parseErr) {
  12293. console.warn('Ping SSE parse error:', parseErr, line);
  12294. }
  12295. }
  12296. }
  12297. } catch (err) {
  12298. if (err.name === 'AbortError') {
  12299. // User aborted normally
  12300. } else {
  12301. showToast('Ping Error', err.message, 'error');
  12302. }
  12303. } finally {
  12304. pingAbortController = null;
  12305. resetPingButton();
  12306. }
  12307. }
  12308. function handleLivePingEvent(evt) {
  12309. const sentEl = document.getElementById('tools-ping-stat-sent');
  12310. const recvEl = document.getElementById('tools-ping-stat-recv');
  12311. const lossEl = document.getElementById('tools-ping-stat-loss');
  12312. const avgEl = document.getElementById('tools-ping-stat-avg');
  12313. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12314. const badge = document.getElementById('tools-ping-status-badge');
  12315. const tbody = document.getElementById('tools-ping-tbody');
  12316. const rawEl = document.getElementById('tools-ping-raw');
  12317. if (evt.raw && rawEl) {
  12318. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12319. rawEl.scrollTop = rawEl.scrollHeight;
  12320. }
  12321. if (evt.type === 'reply') {
  12322. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12323. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12324. if (lossEl && evt.packet_loss_pct !== undefined) {
  12325. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12326. lossEl.className = evt.packet_loss_pct === 0
  12327. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12328. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  12329. }
  12330. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12331. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12332. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12333. }
  12334. if (badge) {
  12335. if (evt.packet_loss_pct === 0) {
  12336. 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';
  12337. badge.innerText = '100% OK';
  12338. } else {
  12339. 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';
  12340. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12341. }
  12342. }
  12343. if (tbody) {
  12344. const tr = document.createElement('tr');
  12345. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12346. tr.innerHTML = `
  12347. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12348. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12349. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12350. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12351. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12352. <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>
  12353. `;
  12354. tbody.appendChild(tr);
  12355. }
  12356. } else if (evt.type === 'timeout') {
  12357. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12358. if (lossEl && evt.packet_loss_pct !== undefined) {
  12359. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12360. 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';
  12361. }
  12362. if (badge) {
  12363. 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';
  12364. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12365. }
  12366. if (tbody) {
  12367. const tr = document.createElement('tr');
  12368. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12369. tr.innerHTML = `
  12370. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12371. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12372. <td class="py-2 px-3 text-slate-600">--</td>
  12373. <td class="py-2 px-3 text-slate-600">--</td>
  12374. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12375. <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>
  12376. `;
  12377. tbody.appendChild(tr);
  12378. }
  12379. } else if (evt.type === 'unreach') {
  12380. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12381. if (lossEl && evt.packet_loss_pct !== undefined) {
  12382. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12383. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12384. }
  12385. if (badge) {
  12386. 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';
  12387. badge.innerText = 'UNREACHABLE';
  12388. }
  12389. if (tbody) {
  12390. const tr = document.createElement('tr');
  12391. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12392. tr.innerHTML = `
  12393. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12394. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12395. <td class="py-2 px-3 text-slate-600">--</td>
  12396. <td class="py-2 px-3 text-slate-600">--</td>
  12397. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12398. <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>
  12399. `;
  12400. tbody.appendChild(tr);
  12401. }
  12402. } else if (evt.type === 'stats') {
  12403. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12404. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12405. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12406. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12407. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12408. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12409. }
  12410. } else if (evt.type === 'done') {
  12411. 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');
  12412. }
  12413. }
  12414. async function executeTraceroute(e) {
  12415. if (e) e.preventDefault();
  12416. if (tracerouteAbortController) {
  12417. tracerouteAbortController.abort();
  12418. tracerouteAbortController = null;
  12419. resetTracerouteButton();
  12420. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12421. return;
  12422. }
  12423. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12424. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12425. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12426. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12427. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12428. if (!target) {
  12429. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12430. return;
  12431. }
  12432. clearTracerouteTable();
  12433. const resCard = document.getElementById('tools-tr-results');
  12434. if (resCard) resCard.classList.remove('hidden');
  12435. tracerouteAbortController = new AbortController();
  12436. setTracerouteRunningButton();
  12437. try {
  12438. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12439. method: 'POST',
  12440. headers: { 'Content-Type': 'application/json' },
  12441. body: JSON.stringify({
  12442. target,
  12443. max_hops: maxHops,
  12444. protocol,
  12445. interface: iface,
  12446. resolve
  12447. }),
  12448. signal: tracerouteAbortController.signal
  12449. });
  12450. if (!res.ok) {
  12451. const errText = await res.text();
  12452. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12453. resetTracerouteButton();
  12454. tracerouteAbortController = null;
  12455. return;
  12456. }
  12457. const reader = res.body.getReader();
  12458. const decoder = new TextDecoder('utf-8');
  12459. let buffer = '';
  12460. while (true) {
  12461. const { done, value } = await reader.read();
  12462. if (done) break;
  12463. buffer += decoder.decode(value, { stream: true });
  12464. const blocks = buffer.split('\n\n');
  12465. buffer = blocks.pop() || '';
  12466. for (const block of blocks) {
  12467. const trimmed = block.trim();
  12468. if (!trimmed) continue;
  12469. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12470. try {
  12471. const evt = JSON.parse(line);
  12472. handleLiveTracerouteEvent(evt);
  12473. } catch (parseErr) {
  12474. console.warn('Traceroute SSE parse error:', parseErr, line);
  12475. }
  12476. }
  12477. }
  12478. } catch (err) {
  12479. if (err.name === 'AbortError') {
  12480. // User aborted normally
  12481. } else {
  12482. showToast('Traceroute Error', err.message, 'error');
  12483. }
  12484. } finally {
  12485. tracerouteAbortController = null;
  12486. resetTracerouteButton();
  12487. }
  12488. }
  12489. function handleLiveTracerouteEvent(evt) {
  12490. const statHops = document.getElementById('tools-tr-hops-count');
  12491. const tbody = document.getElementById('tools-tr-tbody');
  12492. const rawEl = document.getElementById('tools-tr-raw');
  12493. if (evt.raw && rawEl) {
  12494. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12495. rawEl.scrollTop = rawEl.scrollHeight;
  12496. }
  12497. if (evt.hops_count !== undefined && statHops) {
  12498. statHops.innerText = `${evt.hops_count} Hops`;
  12499. }
  12500. if (evt.type === 'hop' && evt.hop && tbody) {
  12501. const h = evt.hop;
  12502. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12503. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12504. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12505. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12506. const tr = document.createElement('tr');
  12507. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12508. tr.innerHTML = `
  12509. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12510. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12511. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12512. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12513. <td class="py-2.5 px-3 text-right">
  12514. ${isTimeout
  12515. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12516. : '<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>'}
  12517. </td>
  12518. `;
  12519. tbody.appendChild(tr);
  12520. } else if (evt.type === 'done') {
  12521. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12522. }
  12523. }
  12524. async function executeMTR(e) {
  12525. if (e) e.preventDefault();
  12526. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12527. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12528. if (!target) {
  12529. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12530. return;
  12531. }
  12532. const btn = document.getElementById('tools-mtr-btn');
  12533. const spinner = document.getElementById('tools-mtr-spinner');
  12534. if (btn) btn.disabled = true;
  12535. if (spinner) spinner.classList.remove('hidden');
  12536. try {
  12537. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12538. method: 'POST',
  12539. headers: { 'Content-Type': 'application/json' },
  12540. body: JSON.stringify({ target, count: cycles })
  12541. });
  12542. const data = await res.json();
  12543. if (!res.ok) {
  12544. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12545. return;
  12546. }
  12547. const resCard = document.getElementById('tools-mtr-results');
  12548. if (resCard) resCard.classList.remove('hidden');
  12549. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12550. const statHops = document.getElementById('tools-mtr-hops-count');
  12551. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12552. const tbody = document.getElementById('tools-mtr-tbody');
  12553. if (tbody) {
  12554. if (hopsCount > 0) {
  12555. tbody.innerHTML = data.hops.map(h => {
  12556. 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');
  12557. return `
  12558. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12559. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12560. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12561. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12562. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12563. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12564. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12565. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12566. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12567. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12568. </tr>
  12569. `;
  12570. }).join('');
  12571. } else {
  12572. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12573. }
  12574. }
  12575. const rawEl = document.getElementById('tools-mtr-raw');
  12576. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12577. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12578. } catch (err) {
  12579. showToast('MTR Error', err.message, 'error');
  12580. } finally {
  12581. if (btn) btn.disabled = false;
  12582. if (spinner) spinner.classList.add('hidden');
  12583. }
  12584. }
  12585. async function executeDNS(e) {
  12586. if (e) e.preventDefault();
  12587. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12588. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12589. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12590. if (!domain) {
  12591. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12592. return;
  12593. }
  12594. const btn = document.getElementById('tools-dns-btn');
  12595. const spinner = document.getElementById('tools-dns-spinner');
  12596. if (btn) btn.disabled = true;
  12597. if (spinner) spinner.classList.remove('hidden');
  12598. try {
  12599. const res = await fetch(`${API_BASE}/tools/dns`, {
  12600. method: 'POST',
  12601. headers: { 'Content-Type': 'application/json' },
  12602. body: JSON.stringify({ domain, type, server })
  12603. });
  12604. const data = await res.json();
  12605. if (!res.ok) {
  12606. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12607. return;
  12608. }
  12609. const resCard = document.getElementById('tools-dns-results');
  12610. if (resCard) resCard.classList.remove('hidden');
  12611. const metaEl = document.getElementById('tools-dns-meta');
  12612. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12613. const tbody = document.getElementById('tools-dns-tbody');
  12614. if (tbody) {
  12615. if (Array.isArray(data.records) && data.records.length > 0) {
  12616. tbody.innerHTML = data.records.map(r => `
  12617. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12618. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12619. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12620. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12621. <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>
  12622. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12623. </tr>
  12624. `).join('');
  12625. } else {
  12626. 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>`;
  12627. }
  12628. }
  12629. const rawEl = document.getElementById('tools-dns-raw');
  12630. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12631. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12632. } catch (err) {
  12633. showToast('DNS Error', err.message, 'error');
  12634. } finally {
  12635. if (btn) btn.disabled = false;
  12636. if (spinner) spinner.classList.add('hidden');
  12637. }
  12638. }
  12639. async function executePortProbe(e) {
  12640. if (e) e.preventDefault();
  12641. const target = document.getElementById('tools-port-target')?.value?.trim();
  12642. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12643. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12644. if (!target || !port) {
  12645. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12646. return;
  12647. }
  12648. const btn = document.getElementById('tools-port-btn');
  12649. const spinner = document.getElementById('tools-port-spinner');
  12650. if (btn) btn.disabled = true;
  12651. if (spinner) spinner.classList.remove('hidden');
  12652. try {
  12653. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12654. method: 'POST',
  12655. headers: { 'Content-Type': 'application/json' },
  12656. body: JSON.stringify({ target, port, timeout })
  12657. });
  12658. const data = await res.json();
  12659. if (!res.ok) {
  12660. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12661. return;
  12662. }
  12663. const resCard = document.getElementById('tools-port-results');
  12664. if (resCard) resCard.classList.remove('hidden');
  12665. const banner = document.getElementById('tools-port-banner');
  12666. const icon = document.getElementById('tools-port-icon');
  12667. const title = document.getElementById('tools-port-title');
  12668. const sub = document.getElementById('tools-port-sub');
  12669. const latency = document.getElementById('tools-port-latency');
  12670. if (data.open) {
  12671. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12672. if (icon) {
  12673. 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';
  12674. icon.innerText = '✓';
  12675. }
  12676. if (title) {
  12677. title.className = 'text-sm font-bold text-emerald-300';
  12678. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12679. }
  12680. if (sub) {
  12681. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12682. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12683. }
  12684. if (latency) {
  12685. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12686. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12687. }
  12688. } else {
  12689. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12690. if (icon) {
  12691. 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';
  12692. icon.innerText = '✕';
  12693. }
  12694. if (title) {
  12695. title.className = 'text-sm font-bold text-rose-300';
  12696. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12697. }
  12698. if (sub) {
  12699. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12700. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12701. }
  12702. if (latency) {
  12703. latency.className = 'text-base font-bold font-mono text-slate-500';
  12704. latency.innerText = '--';
  12705. }
  12706. }
  12707. const rawEl = document.getElementById('tools-port-raw');
  12708. 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'}`);
  12709. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12710. } catch (err) {
  12711. showToast('Probe Error', err.message, 'error');
  12712. } finally {
  12713. if (btn) btn.disabled = false;
  12714. if (spinner) spinner.classList.add('hidden');
  12715. }
  12716. }
  12717. // ==========================================
  12718. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12719. // ==========================================
  12720. async function loadDHCPClients(showToastMsg = false) {
  12721. try {
  12722. const [clientsRes, sumRes] = await Promise.all([
  12723. fetch(`${API_BASE}/dhcp/clients`),
  12724. fetch(`${API_BASE}/dhcp/clients/summary`)
  12725. ]);
  12726. if (clientsRes.ok) {
  12727. state.dhcpClients = await clientsRes.json();
  12728. }
  12729. if (sumRes.ok) {
  12730. state.dhcpSummary = await sumRes.json();
  12731. }
  12732. renderDHCPClients();
  12733. updateDHCPSummaryCards();
  12734. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12735. if (bDhcp && state.dhcpSummary) {
  12736. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12737. }
  12738. if (showToastMsg) {
  12739. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12740. }
  12741. } catch (err) {
  12742. console.error('Failed to load DHCP clients:', err);
  12743. if (showToastMsg) {
  12744. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12745. }
  12746. }
  12747. }
  12748. function updateDHCPSummaryCards() {
  12749. const sum = state.dhcpSummary || {
  12750. total_clients: (state.dhcpClients || []).length,
  12751. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12752. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12753. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12754. };
  12755. const totalEl = document.getElementById('dhcp-stat-total');
  12756. const boundEl = document.getElementById('dhcp-stat-bound');
  12757. const searchEl = document.getElementById('dhcp-stat-searching');
  12758. const disEl = document.getElementById('dhcp-stat-disabled');
  12759. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12760. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12761. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12762. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12763. }
  12764. function renderDHCPClients() {
  12765. const tbody = document.getElementById('dhcp-clients-tbody');
  12766. const emptyState = document.getElementById('dhcp-clients-empty');
  12767. if (!tbody) return;
  12768. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12769. if (clients.length === 0) {
  12770. tbody.innerHTML = '';
  12771. if (emptyState) emptyState.classList.remove('hidden');
  12772. return;
  12773. }
  12774. if (emptyState) emptyState.classList.add('hidden');
  12775. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12776. if (tbody.dataset.sig === sig) return;
  12777. tbody.dataset.sig = sig;
  12778. tbody.innerHTML = clients.map(c => {
  12779. let statusBadge = '';
  12780. if (!c.enabled) {
  12781. 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>';
  12782. } else if (c.status === 'bound') {
  12783. 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>';
  12784. } else if (c.status === 'searching') {
  12785. 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>';
  12786. } else if (c.status === 'stopped') {
  12787. 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>';
  12788. } else {
  12789. 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>`;
  12790. }
  12791. 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>';
  12792. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12793. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12794. 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>';
  12795. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12796. // Option flags
  12797. const flags = [];
  12798. 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>');
  12799. 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>');
  12800. 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>');
  12801. 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>`);
  12802. return `
  12803. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12804. <td class="py-3 px-4">
  12805. <div class="flex items-center gap-2">
  12806. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12807. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12808. </div>
  12809. </td>
  12810. <td class="py-3 px-4">${statusBadge}</td>
  12811. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12812. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12813. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12814. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12815. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12816. <td class="py-3 px-4">
  12817. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12818. </td>
  12819. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12820. ${c.enabled ? `
  12821. <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>
  12822. <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>
  12823. <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>
  12824. ` : `
  12825. <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>
  12826. `}
  12827. <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>
  12828. <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>
  12829. </td>
  12830. </tr>
  12831. `;
  12832. }).join('');
  12833. }
  12834. function openDHCPClientModal(clientId = null) {
  12835. const modal = document.getElementById('modal-dhcp-client');
  12836. if (!modal) return;
  12837. const title = document.getElementById('modal-dhcp-title');
  12838. const idInput = document.getElementById('modal-dhcp-id');
  12839. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12840. const distInput = document.getElementById('modal-dhcp-distance');
  12841. const commentInput = document.getElementById('modal-dhcp-comment');
  12842. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12843. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12844. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12845. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12846. // Populate interfaces
  12847. if (ifaceSelect) {
  12848. let opts = '<option value="">Select interface...</option>';
  12849. const allIfaces = state.interfaces || [];
  12850. const allVlans = state.vlans || [];
  12851. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12852. // Group 1: Physical & Bridge Interfaces
  12853. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12854. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12855. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12856. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12857. });
  12858. opts += '</optgroup>';
  12859. // Group 2: VLAN Interfaces
  12860. if (allVlans.length > 0) {
  12861. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12862. allVlans.forEach(v => {
  12863. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12864. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12865. });
  12866. opts += '</optgroup>';
  12867. }
  12868. ifaceSelect.innerHTML = opts;
  12869. }
  12870. if (clientId) {
  12871. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12872. if (client) {
  12873. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12874. if (idInput) idInput.value = client.id;
  12875. if (ifaceSelect) {
  12876. ifaceSelect.value = client.interface;
  12877. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12878. }
  12879. if (distInput) distInput.value = client.default_route_distance || 1;
  12880. if (commentInput) commentInput.value = client.comment || '';
  12881. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12882. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12883. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12884. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12885. }
  12886. } else {
  12887. if (title) title.innerText = 'Add DHCP Client';
  12888. if (idInput) idInput.value = '';
  12889. if (ifaceSelect) {
  12890. ifaceSelect.value = '';
  12891. ifaceSelect.disabled = false;
  12892. }
  12893. if (distInput) distInput.value = 1;
  12894. if (commentInput) commentInput.value = '';
  12895. if (defRouteCheck) defRouteCheck.checked = true;
  12896. if (peerDnsCheck) peerDnsCheck.checked = true;
  12897. if (peerNtpCheck) peerNtpCheck.checked = true;
  12898. if (enabledCheck) enabledCheck.checked = true;
  12899. }
  12900. modal.classList.remove('hidden');
  12901. }
  12902. function openDHCPClientModalForIface(ifaceName) {
  12903. openDHCPClientModal();
  12904. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12905. if (ifaceSelect && ifaceName) {
  12906. ifaceSelect.value = ifaceName;
  12907. }
  12908. }
  12909. function closeDHCPClientModal() {
  12910. const modal = document.getElementById('modal-dhcp-client');
  12911. if (modal) modal.classList.add('hidden');
  12912. }
  12913. async function submitSaveDHCPClient(e) {
  12914. if (e) e.preventDefault();
  12915. const id = document.getElementById('modal-dhcp-id')?.value;
  12916. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12917. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12918. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12919. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12920. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12921. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12922. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12923. if (!id && !iface) {
  12924. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12925. return;
  12926. }
  12927. try {
  12928. let res;
  12929. if (id) {
  12930. // PUT update
  12931. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12932. method: 'PUT',
  12933. headers: { 'Content-Type': 'application/json' },
  12934. body: JSON.stringify({
  12935. enabled,
  12936. add_default_route: defRoute,
  12937. default_route_distance: distance,
  12938. use_peer_dns: peerDns,
  12939. use_peer_ntp: peerNtp,
  12940. comment
  12941. })
  12942. });
  12943. } else {
  12944. // POST create
  12945. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12946. method: 'POST',
  12947. headers: { 'Content-Type': 'application/json' },
  12948. body: JSON.stringify({
  12949. interface: iface,
  12950. enabled,
  12951. add_default_route: defRoute,
  12952. default_route_distance: distance,
  12953. use_peer_dns: peerDns,
  12954. use_peer_ntp: peerNtp,
  12955. comment
  12956. })
  12957. });
  12958. }
  12959. const data = await res.json();
  12960. if (!res.ok) {
  12961. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12962. return;
  12963. }
  12964. closeDHCPClientModal();
  12965. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12966. await loadDHCPClients();
  12967. fetchData(); // refresh interfaces list with new lease/status
  12968. } catch (err) {
  12969. showToast('Error', err.message, 'error');
  12970. }
  12971. }
  12972. async function toggleDHCPClientState(id, enabled) {
  12973. try {
  12974. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12975. method: 'POST',
  12976. headers: { 'Content-Type': 'application/json' },
  12977. body: JSON.stringify({ enabled })
  12978. });
  12979. const data = await res.json();
  12980. if (!res.ok) {
  12981. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12982. return;
  12983. }
  12984. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12985. await loadDHCPClients();
  12986. fetchData();
  12987. } catch (err) {
  12988. showToast('Error', err.message, 'error');
  12989. }
  12990. }
  12991. async function renewDHCPClient(id) {
  12992. try {
  12993. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12994. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12995. method: 'POST'
  12996. });
  12997. const data = await res.json();
  12998. if (!res.ok) {
  12999. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13000. return;
  13001. }
  13002. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13003. setTimeout(() => {
  13004. loadDHCPClients();
  13005. fetchData();
  13006. }, 1500);
  13007. } catch (err) {
  13008. showToast('Error', err.message, 'error');
  13009. }
  13010. }
  13011. async function releaseDHCPClient(id) {
  13012. try {
  13013. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13014. method: 'POST'
  13015. });
  13016. const data = await res.json();
  13017. if (!res.ok) {
  13018. showToast('Error', data.error || 'Failed to release lease', 'error');
  13019. return;
  13020. }
  13021. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13022. await loadDHCPClients();
  13023. fetchData();
  13024. } catch (err) {
  13025. showToast('Error', err.message, 'error');
  13026. }
  13027. }
  13028. async function deleteDHCPClient(id, ifaceName) {
  13029. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13030. return;
  13031. }
  13032. try {
  13033. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13034. method: 'DELETE'
  13035. });
  13036. const data = await res.json();
  13037. if (!res.ok) {
  13038. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13039. return;
  13040. }
  13041. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13042. await loadDHCPClients();
  13043. fetchData();
  13044. } catch (err) {
  13045. showToast('Error', err.message, 'error');
  13046. }
  13047. }
  13048. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13049. async function loadDHCPServer(populate = true) {
  13050. try {
  13051. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13052. fetch(`${API_BASE}/dhcp-server/summary`),
  13053. fetch(`${API_BASE}/dhcp-server/servers`),
  13054. fetch(`${API_BASE}/dhcp-server/networks`),
  13055. fetch(`${API_BASE}/dhcp-server/leases`),
  13056. fetch(`${API_BASE}/dhcp-server/options`)
  13057. ]);
  13058. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13059. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13060. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13061. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13062. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13063. const sum = state.dhcpServerSummary || {};
  13064. const srvs = state.dhcpServers || [];
  13065. const nets = state.dhcpNetworks || [];
  13066. const leases = state.dhcpLeases || [];
  13067. const opts = state.dhcpOptions || [];
  13068. // KPI Cards
  13069. const statActive = document.getElementById('dhcp-server-stat-active');
  13070. if (statActive) {
  13071. const activeCount = srvs.filter(s => s.running).length;
  13072. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13073. }
  13074. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13075. if (statLeases) {
  13076. statLeases.innerText = leases.length;
  13077. }
  13078. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13079. if (statLeasesSub) {
  13080. const dyn = leases.filter(l => l.dynamic).length;
  13081. const st = leases.filter(l => !l.dynamic).length;
  13082. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13083. }
  13084. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13085. if (statNetworks) {
  13086. statNetworks.innerText = nets.length;
  13087. }
  13088. // Subtab Badges
  13089. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13090. if (bSrv) bSrv.innerText = srvs.length;
  13091. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13092. if (bNet) bNet.innerText = nets.length;
  13093. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13094. if (bLease) bLease.innerText = leases.length;
  13095. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13096. if (bOpt) bOpt.innerText = opts.length;
  13097. // Sidebar Badge
  13098. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13099. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13100. renderCurrentDHCPServerTab();
  13101. } catch (err) {
  13102. console.error('Failed to load DHCP Server:', err);
  13103. }
  13104. }
  13105. function switchDHCPServerTab(tab) {
  13106. state.dhcpServerTab = tab;
  13107. const tabs = ['servers', 'networks', 'leases', 'options'];
  13108. tabs.forEach(t => {
  13109. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13110. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13111. if (panel) {
  13112. if (t === tab) panel.classList.remove('hidden');
  13113. else panel.classList.add('hidden');
  13114. }
  13115. if (btn) {
  13116. if (t === tab) {
  13117. 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';
  13118. } else {
  13119. 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';
  13120. }
  13121. }
  13122. });
  13123. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13124. if (addBtn) {
  13125. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13126. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13127. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13128. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13129. }
  13130. renderCurrentDHCPServerTab();
  13131. }
  13132. function handleDHCPServerPrimaryAdd() {
  13133. const tab = state.dhcpServerTab || 'servers';
  13134. if (tab === 'servers') openAddDHCPServerModal();
  13135. else if (tab === 'networks') openAddDHCPNetworkModal();
  13136. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13137. else if (tab === 'options') openAddDHCPOptionModal();
  13138. }
  13139. function renderCurrentDHCPServerTab() {
  13140. const tab = state.dhcpServerTab || 'servers';
  13141. if (tab === 'servers') renderDHCPServers();
  13142. else if (tab === 'networks') renderDHCPNetworks();
  13143. else if (tab === 'leases') renderDHCPLeases();
  13144. else if (tab === 'options') renderDHCPOptions();
  13145. }
  13146. function renderDHCPServers() {
  13147. const tbody = document.getElementById('dhcp-server-tbody');
  13148. const empty = document.getElementById('dhcp-server-empty');
  13149. if (!tbody) return;
  13150. const servers = state.dhcpServers || [];
  13151. if (servers.length === 0) {
  13152. tbody.innerHTML = '';
  13153. empty?.classList.remove('hidden');
  13154. return;
  13155. }
  13156. empty?.classList.add('hidden');
  13157. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13158. if (tbody.dataset.sig === sig) return;
  13159. tbody.dataset.sig = sig;
  13160. tbody.innerHTML = '';
  13161. servers.forEach(s => {
  13162. const tr = document.createElement('tr');
  13163. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13164. tr.innerHTML = `
  13165. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13166. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13167. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13168. <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>
  13169. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13170. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13171. <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>
  13172. <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>
  13173. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13174. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13175. <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>
  13176. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13177. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13178. </td>
  13179. `;
  13180. tbody.appendChild(tr);
  13181. });
  13182. }
  13183. function renderDHCPNetworks() {
  13184. const tbody = document.getElementById('dhcp-networks-tbody');
  13185. const empty = document.getElementById('dhcp-networks-empty');
  13186. if (!tbody) return;
  13187. tbody.innerHTML = '';
  13188. const networks = state.dhcpNetworks || [];
  13189. if (networks.length === 0) {
  13190. empty?.classList.remove('hidden');
  13191. return;
  13192. }
  13193. empty?.classList.add('hidden');
  13194. networks.forEach(n => {
  13195. const tr = document.createElement('tr');
  13196. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13197. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13198. const optionsChips = (n.dhcp_options || []).map(optId => {
  13199. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13200. if (!opt) return '';
  13201. 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>`;
  13202. }).filter(Boolean).join('');
  13203. tr.innerHTML = `
  13204. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13205. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13206. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13207. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13208. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13209. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13210. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13211. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13212. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13213. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13214. </td>
  13215. `;
  13216. tbody.appendChild(tr);
  13217. });
  13218. }
  13219. function renderDHCPLeases() {
  13220. const tbody = document.getElementById('dhcp-leases-tbody');
  13221. const empty = document.getElementById('dhcp-leases-empty');
  13222. if (!tbody) return;
  13223. tbody.innerHTML = '';
  13224. const leases = state.dhcpLeases || [];
  13225. if (leases.length === 0) {
  13226. empty?.classList.remove('hidden');
  13227. return;
  13228. }
  13229. empty?.classList.add('hidden');
  13230. leases.forEach(l => {
  13231. const tr = document.createElement('tr');
  13232. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13233. 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>';
  13234. const statusBadge = l.status === 'bound'
  13235. ? '<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>'
  13236. : l.status === 'static'
  13237. ? '<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>'
  13238. : '<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>';
  13239. const makeStaticBtn = l.dynamic
  13240. ? `<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>`
  13241. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13242. tr.innerHTML = `
  13243. <td class="py-2.5 px-3 text-center">${flag}</td>
  13244. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13245. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13246. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13247. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13248. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13249. <td class="py-2.5 px-3">${statusBadge}</td>
  13250. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13251. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13252. ${makeStaticBtn}
  13253. </td>
  13254. `;
  13255. tbody.appendChild(tr);
  13256. });
  13257. }
  13258. function renderDHCPOptions() {
  13259. const tbody = document.getElementById('dhcp-options-tbody');
  13260. const empty = document.getElementById('dhcp-options-empty');
  13261. if (!tbody) return;
  13262. tbody.innerHTML = '';
  13263. const options = state.dhcpOptions || [];
  13264. if (options.length === 0) {
  13265. empty?.classList.remove('hidden');
  13266. return;
  13267. }
  13268. empty?.classList.add('hidden');
  13269. options.forEach(o => {
  13270. const tr = document.createElement('tr');
  13271. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13272. tr.innerHTML = `
  13273. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13274. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13275. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13276. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13277. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13278. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13279. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13280. </td>
  13281. `;
  13282. tbody.appendChild(tr);
  13283. });
  13284. }
  13285. // ==================== MODALS & ACTIONS: SERVER ====================
  13286. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13287. const sel = document.getElementById(elemId);
  13288. if (!sel) return;
  13289. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13290. const networks = state.dhcpNetworks || [];
  13291. networks.forEach(n => {
  13292. const opt = document.createElement('option');
  13293. opt.value = n.address;
  13294. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13295. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13296. opt.selected = true;
  13297. }
  13298. sel.appendChild(opt);
  13299. });
  13300. }
  13301. function onDHCPServerNetworkChange() {
  13302. const netSel = document.getElementById('dhcp-server-modal-network');
  13303. if (!netSel) return;
  13304. const netVal = netSel.value;
  13305. if (!netVal) return;
  13306. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13307. if (!poolInput) return;
  13308. // Auto-calculate suggested address pool based on subnet CIDR
  13309. const parts = netVal.split('/');
  13310. const ip = parts[0];
  13311. const cidr = parseInt(parts[1] || '24', 10);
  13312. if (cidr === 24) {
  13313. const octets = ip.split('.');
  13314. if (octets.length === 4) {
  13315. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13316. poolInput.value = `${base}.10-${base}.254`;
  13317. }
  13318. }
  13319. }
  13320. function openAddDHCPServerModal() {
  13321. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13322. document.getElementById('dhcp-server-modal-id').value = '';
  13323. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13324. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13325. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13326. document.getElementById('dhcp-server-modal-comment').value = '';
  13327. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13328. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13329. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13330. const networks = state.dhcpNetworks || [];
  13331. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13332. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13333. if (defaultNet) {
  13334. onDHCPServerNetworkChange();
  13335. }
  13336. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13337. }
  13338. function openEditDHCPServerModal(id) {
  13339. const s = (state.dhcpServers || []).find(item => item.id === id);
  13340. if (!s) return;
  13341. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13342. document.getElementById('dhcp-server-modal-id').value = s.id;
  13343. document.getElementById('dhcp-server-modal-name').value = s.name;
  13344. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13345. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13346. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13347. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13348. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13349. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13350. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13351. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13352. }
  13353. function closeDHCPServerModal() {
  13354. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13355. }
  13356. async function submitSaveDHCPServer(e) {
  13357. e.preventDefault();
  13358. const id = document.getElementById('dhcp-server-modal-id').value;
  13359. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13360. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13361. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13362. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13363. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13364. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13365. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13366. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13367. try {
  13368. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13369. method: 'POST',
  13370. headers: { 'Content-Type': 'application/json' },
  13371. body: JSON.stringify({
  13372. id,
  13373. name,
  13374. interface: iface,
  13375. network,
  13376. address_pool: pool,
  13377. lease_time: leaseTime,
  13378. authoritative,
  13379. disabled,
  13380. comment
  13381. })
  13382. });
  13383. if (res.ok) {
  13384. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13385. closeDHCPServerModal();
  13386. loadDHCPServer(false);
  13387. fetchData(false);
  13388. } else {
  13389. const err = await res.text();
  13390. showToast('Error', err, 'error');
  13391. }
  13392. } catch (err) {
  13393. showToast('Error', err.message, 'error');
  13394. }
  13395. }
  13396. async function toggleDHCPServerState(id, disabled) {
  13397. try {
  13398. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13399. method: 'POST',
  13400. headers: { 'Content-Type': 'application/json' },
  13401. body: JSON.stringify({ disabled })
  13402. });
  13403. if (res.ok) {
  13404. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13405. loadDHCPServer(false);
  13406. fetchData(false);
  13407. }
  13408. } catch (err) {
  13409. showToast('Error', err.message, 'error');
  13410. }
  13411. }
  13412. async function deleteDHCPServer(id, name) {
  13413. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13414. try {
  13415. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13416. if (res.ok) {
  13417. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13418. loadDHCPServer(false);
  13419. fetchData(false);
  13420. }
  13421. } catch (err) {
  13422. showToast('Error', err.message, 'error');
  13423. }
  13424. }
  13425. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13426. function openAddDHCPNetworkModal() {
  13427. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13428. document.getElementById('dhcp-network-modal-id').value = '';
  13429. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13430. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13431. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13432. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13433. document.getElementById('dhcp-network-modal-netmask').value = '';
  13434. document.getElementById('dhcp-network-modal-comment').value = '';
  13435. renderDHCPNetworkOptionsCheckboxes([]);
  13436. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13437. }
  13438. function openEditDHCPNetworkModal(id) {
  13439. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13440. if (!n) return;
  13441. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13442. document.getElementById('dhcp-network-modal-id').value = n.id;
  13443. document.getElementById('dhcp-network-modal-address').value = n.address;
  13444. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13445. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13446. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13447. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13448. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13449. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13450. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13451. }
  13452. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13453. const container = document.getElementById('dhcp-network-modal-options-list');
  13454. if (!container) return;
  13455. container.innerHTML = '';
  13456. const opts = state.dhcpOptions || [];
  13457. if (opts.length === 0) {
  13458. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13459. return;
  13460. }
  13461. opts.forEach(o => {
  13462. const isChecked = selectedIds.includes(o.id);
  13463. const label = document.createElement('label');
  13464. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13465. label.innerHTML = `
  13466. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13467. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13468. `;
  13469. container.appendChild(label);
  13470. });
  13471. }
  13472. function closeDHCPNetworkModal() {
  13473. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13474. }
  13475. async function submitSaveDHCPNetwork(e) {
  13476. e.preventDefault();
  13477. const id = document.getElementById('dhcp-network-modal-id').value;
  13478. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13479. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13480. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13481. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13482. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13483. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13484. const selectedOpts = [];
  13485. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13486. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13487. try {
  13488. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13489. method: 'POST',
  13490. headers: { 'Content-Type': 'application/json' },
  13491. body: JSON.stringify({
  13492. id,
  13493. address,
  13494. gateway,
  13495. netmask,
  13496. dns_servers: dnsServers,
  13497. domain,
  13498. dhcp_options: selectedOpts,
  13499. comment
  13500. })
  13501. });
  13502. if (res.ok) {
  13503. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13504. closeDHCPNetworkModal();
  13505. loadDHCPServer(false);
  13506. fetchData(false);
  13507. } else {
  13508. const err = await res.text();
  13509. showToast('Error', err, 'error');
  13510. }
  13511. } catch (err) {
  13512. showToast('Error', err.message, 'error');
  13513. }
  13514. }
  13515. async function deleteDHCPNetwork(id, addr) {
  13516. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13517. try {
  13518. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13519. if (res.ok) {
  13520. showToast('Deleted', `Network ${addr} removed`, 'success');
  13521. loadDHCPServer(false);
  13522. fetchData(false);
  13523. }
  13524. } catch (err) {
  13525. showToast('Error', err.message, 'error');
  13526. }
  13527. }
  13528. // ==================== MODALS & ACTIONS: LEASES ====================
  13529. function openAddDHCPStaticLeaseModal() {
  13530. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13531. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13532. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13533. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13534. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13535. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13536. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13537. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13538. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13539. }
  13540. function closeDHCPStaticLeaseModal() {
  13541. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13542. }
  13543. async function submitSaveDHCPStaticLease(e) {
  13544. e.preventDefault();
  13545. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13546. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13547. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13548. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13549. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13550. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13551. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13552. try {
  13553. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13554. method: 'POST',
  13555. headers: { 'Content-Type': 'application/json' },
  13556. body: JSON.stringify({
  13557. id,
  13558. mac_address: mac,
  13559. address: ip,
  13560. hostname,
  13561. server,
  13562. comment,
  13563. disabled
  13564. })
  13565. });
  13566. if (res.ok) {
  13567. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13568. closeDHCPStaticLeaseModal();
  13569. loadDHCPServer(false);
  13570. fetchData(false);
  13571. } else {
  13572. const err = await res.text();
  13573. showToast('Error', err, 'error');
  13574. }
  13575. } catch (err) {
  13576. showToast('Error', err.message, 'error');
  13577. }
  13578. }
  13579. async function deleteDHCPStaticLease(id) {
  13580. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13581. try {
  13582. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13583. if (res.ok) {
  13584. showToast('Deleted', 'Static lease removed', 'success');
  13585. loadDHCPServer(false);
  13586. fetchData(false);
  13587. }
  13588. } catch (err) {
  13589. showToast('Error', err.message, 'error');
  13590. }
  13591. }
  13592. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13593. try {
  13594. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13595. method: 'POST',
  13596. headers: { 'Content-Type': 'application/json' },
  13597. body: JSON.stringify({
  13598. mac_address: mac,
  13599. address: ip,
  13600. hostname,
  13601. comment: comment || 'Converted to static'
  13602. })
  13603. });
  13604. if (res.ok) {
  13605. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13606. loadDHCPServer(false);
  13607. fetchData(false);
  13608. } else {
  13609. const err = await res.text();
  13610. showToast('Error', err, 'error');
  13611. }
  13612. } catch (err) {
  13613. showToast('Error', err.message, 'error');
  13614. }
  13615. }
  13616. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13617. function openAddDHCPOptionModal() {
  13618. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13619. document.getElementById('dhcp-option-modal-id').value = '';
  13620. document.getElementById('dhcp-option-modal-name').value = '';
  13621. document.getElementById('dhcp-option-modal-code').value = '';
  13622. document.getElementById('dhcp-option-modal-value').value = '';
  13623. document.getElementById('dhcp-option-modal-comment').value = '';
  13624. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13625. }
  13626. function openEditDHCPOptionModal(id) {
  13627. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13628. if (!o) return;
  13629. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13630. document.getElementById('dhcp-option-modal-id').value = o.id;
  13631. document.getElementById('dhcp-option-modal-name').value = o.name;
  13632. document.getElementById('dhcp-option-modal-code').value = o.code;
  13633. document.getElementById('dhcp-option-modal-value').value = o.value;
  13634. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13635. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13636. }
  13637. function closeDHCPOptionModal() {
  13638. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13639. }
  13640. async function submitSaveDHCPOption(e) {
  13641. e.preventDefault();
  13642. const id = document.getElementById('dhcp-option-modal-id').value;
  13643. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13644. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13645. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13646. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13647. try {
  13648. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13649. method: 'POST',
  13650. headers: { 'Content-Type': 'application/json' },
  13651. body: JSON.stringify({ id, name, code, value, comment })
  13652. });
  13653. if (res.ok) {
  13654. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13655. closeDHCPOptionModal();
  13656. loadDHCPServer(false);
  13657. fetchData(false);
  13658. } else {
  13659. const err = await res.text();
  13660. showToast('Error', err, 'error');
  13661. }
  13662. } catch (err) {
  13663. showToast('Error', err.message, 'error');
  13664. }
  13665. }
  13666. async function deleteDHCPOption(id, name) {
  13667. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13668. try {
  13669. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13670. if (res.ok) {
  13671. showToast('Deleted', `Option ${name} removed`, 'success');
  13672. loadDHCPServer(false);
  13673. fetchData(false);
  13674. }
  13675. } catch (err) {
  13676. showToast('Error', err.message, 'error');
  13677. }
  13678. }
  13679. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13680. function openDHCPServerSetupModal() {
  13681. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13682. onDHCPWizardIfaceChange();
  13683. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13684. }
  13685. function closeDHCPServerSetupModal() {
  13686. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13687. }
  13688. function onDHCPWizardIfaceChange() {
  13689. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13690. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13691. let ip = '192.168.88.1';
  13692. let prefix = '24';
  13693. if (iface && iface.ip_address) {
  13694. const parts = iface.ip_address.split('/');
  13695. ip = parts[0];
  13696. if (parts.length > 1) prefix = parts[1];
  13697. }
  13698. // Calculate subnet base (e.g. 192.168.88.0/24)
  13699. const ipParts = ip.split('.');
  13700. if (ipParts.length === 4) {
  13701. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13702. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13703. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13704. document.getElementById('dhcp-wizard-gateway').value = ip;
  13705. document.getElementById('dhcp-wizard-pool').value = pool;
  13706. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13707. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13708. }
  13709. }
  13710. async function submitDHCPServerSetupWizard(e) {
  13711. e.preventDefault();
  13712. const iface = document.getElementById('dhcp-wizard-iface').value;
  13713. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13714. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13715. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13716. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13717. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13718. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13719. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13720. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13721. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13722. try {
  13723. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13724. method: 'POST',
  13725. headers: { 'Content-Type': 'application/json' },
  13726. body: JSON.stringify({
  13727. interface: iface,
  13728. address_space: space,
  13729. gateway: gw,
  13730. address_pool: pool,
  13731. dns_servers: dnsServers,
  13732. lease_time: leaseTime,
  13733. ntp_servers: ntpServers,
  13734. next_server: tftp
  13735. })
  13736. });
  13737. if (res.ok) {
  13738. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13739. closeDHCPServerSetupModal();
  13740. loadDHCPServer(false);
  13741. fetchData(false);
  13742. } else {
  13743. const err = await res.text();
  13744. showToast('Error', err, 'error');
  13745. }
  13746. } catch (err) {
  13747. showToast('Error', err.message, 'error');
  13748. }
  13749. }
  13750. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13751. const sel = document.getElementById(elemId);
  13752. if (!sel) return;
  13753. sel.innerHTML = '<option value="">Select interface...</option>';
  13754. const ifaces = state.interfaces || [];
  13755. ifaces.forEach(i => {
  13756. if (i.name === 'lo') return;
  13757. const opt = document.createElement('option');
  13758. opt.value = i.name;
  13759. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13760. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13761. if (i.name === selectedVal) opt.selected = true;
  13762. sel.appendChild(opt);
  13763. });
  13764. }
  13765. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13766. function initTableSorting() {
  13767. document.querySelectorAll('table').forEach(setupSortableTable);
  13768. }
  13769. function setupSortableTable(table) {
  13770. const thead = table.querySelector('thead');
  13771. const tbody = table.querySelector('tbody');
  13772. if (!thead || !tbody) return;
  13773. const headerRows = thead.querySelectorAll('tr');
  13774. if (headerRows.length === 0) return;
  13775. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13776. ths.forEach((th, colIdx) => {
  13777. if (th._sortBound) return;
  13778. th._sortBound = true;
  13779. const rawText = th.innerText.trim().toLowerCase();
  13780. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13781. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13782. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13783. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13784. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13785. return;
  13786. }
  13787. th.classList.add('table-sortable', 'group');
  13788. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13789. let icon = th.querySelector('.table-sort-icon');
  13790. if (!icon) {
  13791. icon = document.createElement('span');
  13792. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13793. icon.innerHTML = '⇅';
  13794. th.appendChild(icon);
  13795. }
  13796. th.addEventListener('click', (e) => {
  13797. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13798. handleHeaderClick(table, th, colIdx);
  13799. });
  13800. });
  13801. if (!tbody._sortObserved) {
  13802. tbody._sortObserved = true;
  13803. let sortDebounceTimer = null;
  13804. const observer = new MutationObserver((mutations) => {
  13805. if (tbody._isSorting) return;
  13806. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13807. if (!hasChildChanges) return;
  13808. clearTimeout(sortDebounceTimer);
  13809. sortDebounceTimer = setTimeout(() => {
  13810. if (tbody._isSorting) return;
  13811. if (table._activeSort && table._activeSort.dir !== 'none') {
  13812. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13813. } else {
  13814. tagOriginalRowOrder(tbody);
  13815. }
  13816. }, 50);
  13817. });
  13818. tbody._sortObserver = observer;
  13819. observer.observe(tbody, { childList: true });
  13820. }
  13821. tagOriginalRowOrder(tbody);
  13822. }
  13823. function tagOriginalRowOrder(tbody) {
  13824. let idx = 0;
  13825. Array.from(tbody.children).forEach(tr => {
  13826. if (!tr.querySelector('td[colspan]')) {
  13827. if (!tr.hasAttribute('data-orig-idx')) {
  13828. tr.setAttribute('data-orig-idx', idx++);
  13829. }
  13830. }
  13831. });
  13832. }
  13833. function handleHeaderClick(table, th, colIdx) {
  13834. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13835. let newDir = 'asc';
  13836. if (currentSort.colIdx === colIdx) {
  13837. if (currentSort.dir === 'asc') newDir = 'desc';
  13838. else if (currentSort.dir === 'desc') newDir = 'none';
  13839. else newDir = 'asc';
  13840. } else {
  13841. newDir = 'asc';
  13842. }
  13843. table._activeSort = { colIdx, dir: newDir };
  13844. updateHeaderIcons(table, colIdx, newDir);
  13845. applyTableSort(table, colIdx, newDir, true);
  13846. }
  13847. function updateHeaderIcons(table, activeColIdx, dir) {
  13848. const thead = table.querySelector('thead');
  13849. if (!thead) return;
  13850. const ths = thead.querySelectorAll('th');
  13851. ths.forEach((th, idx) => {
  13852. const icon = th.querySelector('.table-sort-icon');
  13853. if (!icon) return;
  13854. if (idx === activeColIdx && dir !== 'none') {
  13855. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13856. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13857. th.classList.add('table-sorted-active');
  13858. } else {
  13859. icon.innerHTML = '⇅';
  13860. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13861. th.classList.remove('table-sorted-active');
  13862. }
  13863. });
  13864. }
  13865. function applyTableSort(table, colIdx, dir, userInitiated) {
  13866. const tbody = table.querySelector('tbody');
  13867. if (!tbody || tbody.children.length <= 1) return;
  13868. tbody._isSorting = true;
  13869. tagOriginalRowOrder(tbody);
  13870. // Group parent rows and any attached drawer/sub-rows
  13871. const groups = [];
  13872. let currentGroup = null;
  13873. Array.from(tbody.children).forEach(tr => {
  13874. if (tr.querySelector('td[colspan]')) {
  13875. if (currentGroup) {
  13876. currentGroup.subRows.push(tr);
  13877. } else {
  13878. groups.push({ mainRow: tr, subRows: [] });
  13879. }
  13880. } else {
  13881. currentGroup = { mainRow: tr, subRows: [] };
  13882. groups.push(currentGroup);
  13883. }
  13884. });
  13885. if (dir === 'none') {
  13886. groups.sort((a, b) => {
  13887. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13888. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13889. return idxA - idxB;
  13890. });
  13891. } else {
  13892. groups.sort((a, b) => {
  13893. const cellA = a.mainRow.children[colIdx];
  13894. const cellB = b.mainRow.children[colIdx];
  13895. const res = compareTableCells(cellA, cellB);
  13896. return dir === 'asc' ? res : -res;
  13897. });
  13898. }
  13899. // Check if rows are already in correct order to avoid modifying DOM
  13900. let alreadyOrdered = true;
  13901. let childIdx = 0;
  13902. for (const g of groups) {
  13903. if (tbody.children[childIdx] !== g.mainRow) {
  13904. alreadyOrdered = false;
  13905. break;
  13906. }
  13907. childIdx++;
  13908. for (const sub of g.subRows) {
  13909. if (tbody.children[childIdx] !== sub) {
  13910. alreadyOrdered = false;
  13911. break;
  13912. }
  13913. childIdx++;
  13914. }
  13915. }
  13916. if (alreadyOrdered) {
  13917. tbody._isSorting = false;
  13918. return;
  13919. }
  13920. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13921. if (tbody._sortObserver) {
  13922. tbody._sortObserver.disconnect();
  13923. }
  13924. // Re-append rows in sorted order
  13925. groups.forEach(g => {
  13926. tbody.appendChild(g.mainRow);
  13927. g.subRows.forEach(sub => tbody.appendChild(sub));
  13928. });
  13929. // Drain any queued mutations and re-connect observer
  13930. if (tbody._sortObserver) {
  13931. tbody._sortObserver.takeRecords();
  13932. tbody._sortObserver.observe(tbody, { childList: true });
  13933. }
  13934. tbody._isSorting = false;
  13935. }
  13936. function getCellRawText(cell) {
  13937. if (!cell) return '';
  13938. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13939. const input = cell.querySelector('input, select');
  13940. if (input) {
  13941. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13942. return input.value;
  13943. }
  13944. return cell.innerText.trim();
  13945. }
  13946. function parseTrafficToNumber(str) {
  13947. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13948. if (!m) return null;
  13949. const num = parseFloat(m[1].replace(/,/g, ''));
  13950. if (isNaN(num)) return null;
  13951. const unit = m[2].toUpperCase();
  13952. let mult = 1;
  13953. if (unit.startsWith('K')) mult = 1024;
  13954. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13955. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13956. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13957. return num * mult;
  13958. }
  13959. function parseIpToNumber(str) {
  13960. const clean = str.replace(/^[!~]/, '').trim();
  13961. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13962. if (!m) return null;
  13963. const o1 = parseInt(m[1], 10);
  13964. const o2 = parseInt(m[2], 10);
  13965. const o3 = parseInt(m[3], 10);
  13966. const o4 = parseInt(m[4], 10);
  13967. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13968. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13969. }
  13970. function parseCompoundPackets(str) {
  13971. const m = str.match(/^([\d,]+)p/);
  13972. if (!m) return null;
  13973. return parseInt(m[1].replace(/,/g, ''), 10);
  13974. }
  13975. function compareTableCells(cellA, cellB) {
  13976. const a = getCellRawText(cellA);
  13977. const b = getCellRawText(cellB);
  13978. if (a === '' && b !== '') return 1;
  13979. if (b === '' && a !== '') return -1;
  13980. if (a === b) return 0;
  13981. // 1. IP Addresses / CIDR
  13982. const ipA = parseIpToNumber(a);
  13983. const ipB = parseIpToNumber(b);
  13984. if (ipA !== null && ipB !== null) return ipA - ipB;
  13985. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13986. const pktA = parseCompoundPackets(a);
  13987. const pktB = parseCompoundPackets(b);
  13988. if (pktA !== null && pktB !== null) return pktA - pktB;
  13989. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13990. const trafA = parseTrafficToNumber(a);
  13991. const trafB = parseTrafficToNumber(b);
  13992. if (trafA !== null && trafB !== null) return trafA - trafB;
  13993. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13994. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13995. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13996. const numA = Number(cleanNumA);
  13997. const numB = Number(cleanNumB);
  13998. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13999. return numA - numB;
  14000. }
  14001. // 5. Natural case-insensitive string compare
  14002. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14003. }
  14004. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14005. async function loadVRRP(showToastNotification = false) {
  14006. try {
  14007. const [instRes, sumRes] = await Promise.all([
  14008. fetch(`${API_BASE}/vrrp/instances`),
  14009. fetch(`${API_BASE}/vrrp/summary`)
  14010. ]);
  14011. if (instRes.ok) {
  14012. state.vrrpInstances = await instRes.json();
  14013. renderVRRP();
  14014. }
  14015. if (sumRes.ok) {
  14016. state.vrrpSummary = await sumRes.json();
  14017. renderVRRPSummary();
  14018. }
  14019. if (showToastNotification) {
  14020. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14021. }
  14022. } catch (err) {
  14023. console.error('Failed to load VRRP:', err);
  14024. }
  14025. }
  14026. function renderVRRPSummary() {
  14027. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14028. const elTotal = document.getElementById('vrrp-stat-total');
  14029. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14030. const elMaster = document.getElementById('vrrp-stat-master');
  14031. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14032. const elBackup = document.getElementById('vrrp-stat-backup');
  14033. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14034. const bCount = document.getElementById('badge-vrrp-count');
  14035. if (bCount) bCount.innerText = s.total_instances || 0;
  14036. const dot = document.getElementById('badge-vrrp-dot');
  14037. if (dot) {
  14038. if (s.master_instances > 0) {
  14039. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14040. } else if (s.backup_instances > 0) {
  14041. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14042. } else {
  14043. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14044. }
  14045. }
  14046. }
  14047. function renderVRRP() {
  14048. const tbody = document.getElementById('vrrp-table-tbody');
  14049. const empty = document.getElementById('vrrp-table-empty');
  14050. if (!tbody) return;
  14051. tbody.innerHTML = '';
  14052. const instances = state.vrrpInstances || [];
  14053. if (instances.length === 0) {
  14054. empty?.classList.remove('hidden');
  14055. return;
  14056. }
  14057. empty?.classList.add('hidden');
  14058. instances.forEach(inst => {
  14059. const tr = document.createElement('tr');
  14060. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14061. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14062. 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>`;
  14063. if (inst.disabled) {
  14064. 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>`;
  14065. } else if (inst.state === 'MASTER') {
  14066. 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>`;
  14067. } else if (inst.state === 'BACKUP') {
  14068. 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>`;
  14069. } else if (inst.state === 'FAULT') {
  14070. 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>`;
  14071. }
  14072. // Render State Badge
  14073. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14074. if (!inst.disabled) {
  14075. if (inst.state === 'MASTER') {
  14076. 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>`;
  14077. } else if (inst.state === 'BACKUP') {
  14078. 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>`;
  14079. } else if (inst.state === 'FAULT') {
  14080. 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>`;
  14081. }
  14082. }
  14083. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14084. tr.innerHTML = `
  14085. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14086. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14087. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14088. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14089. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14090. <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>
  14091. <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>
  14092. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14093. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14094. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14095. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14096. <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>
  14097. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14098. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14099. </td>
  14100. `;
  14101. tbody.appendChild(tr);
  14102. });
  14103. }
  14104. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14105. const sel = document.getElementById(elemId);
  14106. if (!sel) return;
  14107. sel.innerHTML = '<option value="">Select interface...</option>';
  14108. const ifaces = state.interfaces || [];
  14109. ifaces.forEach(i => {
  14110. const opt = document.createElement('option');
  14111. opt.value = i.name;
  14112. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14113. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14114. sel.appendChild(opt);
  14115. });
  14116. }
  14117. function openAddVRRPModal() {
  14118. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14119. document.getElementById('modal-vrrp-id').value = '';
  14120. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14121. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14122. document.getElementById('modal-vrrp-priority').value = 100;
  14123. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14124. document.getElementById('modal-vrrp-version').value = '3';
  14125. document.getElementById('modal-vrrp-interval').value = 1;
  14126. document.getElementById('modal-vrrp-authtype').value = 'none';
  14127. document.getElementById('modal-vrrp-authpass').value = '';
  14128. document.getElementById('modal-vrrp-comment').value = '';
  14129. document.getElementById('modal-vrrp-preempt').checked = true;
  14130. document.getElementById('modal-vrrp-disabled').checked = false;
  14131. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14132. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14133. }
  14134. function openEditVRRPModal(id) {
  14135. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14136. if (!inst) return;
  14137. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14138. document.getElementById('modal-vrrp-id').value = inst.id;
  14139. document.getElementById('modal-vrrp-name').value = inst.name;
  14140. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14141. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14142. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14143. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14144. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14145. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14146. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14147. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14148. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14149. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14150. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14151. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14152. }
  14153. function closeVRRPModal() {
  14154. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14155. }
  14156. async function submitSaveVRRP(e) {
  14157. e.preventDefault();
  14158. const id = document.getElementById('modal-vrrp-id').value;
  14159. const name = document.getElementById('modal-vrrp-name').value.trim();
  14160. const iface = document.getElementById('modal-vrrp-iface').value;
  14161. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14162. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14163. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14164. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14165. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14166. const authType = document.getElementById('modal-vrrp-authtype').value;
  14167. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14168. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14169. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14170. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14171. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14172. try {
  14173. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14174. method: 'POST',
  14175. headers: { 'Content-Type': 'application/json' },
  14176. body: JSON.stringify({
  14177. id,
  14178. name,
  14179. interface: iface,
  14180. vrid,
  14181. priority,
  14182. virtual_ips: vips,
  14183. version,
  14184. interval,
  14185. auth_type: authType,
  14186. auth_password: authPass,
  14187. comment,
  14188. preempt,
  14189. disabled
  14190. })
  14191. });
  14192. if (res.ok) {
  14193. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14194. closeVRRPModal();
  14195. loadVRRP(false);
  14196. fetchData(false);
  14197. } else {
  14198. const err = await res.text();
  14199. showToast('Error', err, 'error');
  14200. }
  14201. } catch (err) {
  14202. showToast('Error', err.message, 'error');
  14203. }
  14204. }
  14205. async function deleteVRRP(id, name) {
  14206. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14207. try {
  14208. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14209. if (res.ok) {
  14210. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14211. loadVRRP(false);
  14212. fetchData(false);
  14213. } else {
  14214. const err = await res.text();
  14215. showToast('Error', err, 'error');
  14216. }
  14217. } catch (err) {
  14218. showToast('Error', err.message, 'error');
  14219. }
  14220. }
  14221. async function toggleVRRPState(id, disabled) {
  14222. try {
  14223. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14224. method: 'POST',
  14225. headers: { 'Content-Type': 'application/json' },
  14226. body: JSON.stringify({ disabled })
  14227. });
  14228. if (res.ok) {
  14229. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14230. loadVRRP(false);
  14231. fetchData(false);
  14232. } else {
  14233. const err = await res.text();
  14234. showToast('Error', err, 'error');
  14235. }
  14236. } catch (err) {
  14237. showToast('Error', err.message, 'error');
  14238. }
  14239. }
  14240. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14241. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14242. let docSortDebounce = null;
  14243. const docTableObserver = new MutationObserver((mutations) => {
  14244. let needsInit = false;
  14245. for (const m of mutations) {
  14246. for (const node of m.addedNodes) {
  14247. if (node.nodeType === 1) {
  14248. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14249. needsInit = true;
  14250. break;
  14251. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14252. needsInit = true;
  14253. break;
  14254. }
  14255. }
  14256. }
  14257. if (needsInit) break;
  14258. }
  14259. if (needsInit) {
  14260. clearTimeout(docSortDebounce);
  14261. docSortDebounce = setTimeout(initTableSorting, 100);
  14262. }
  14263. });
  14264. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14265. }
  14266. // =========================================================================
  14267. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14268. // =========================================================================
  14269. const bwtestState = {
  14270. running: false,
  14271. pollTimer: null,
  14272. eventSource: null,
  14273. chartPoints: [],
  14274. maxChartPoints: 60,
  14275. serverConfig: null,
  14276. peakTx: 0,
  14277. peakRx: 0,
  14278. targetDuration: 10,
  14279. lastSampleElapsed: -1,
  14280. sessionID: null
  14281. };
  14282. async function loadBwTestView() {
  14283. resizeBwTestCanvas();
  14284. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14285. }
  14286. async function fetchBwTestServerStatus() {
  14287. try {
  14288. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14289. if (!res.ok) return;
  14290. const s = await res.json();
  14291. bwtestState.serverConfig = s;
  14292. // Update indicator and badges
  14293. const indicator = document.getElementById('bwtest-server-indicator');
  14294. const badge = document.getElementById('bwtest-server-badge');
  14295. const sideBadge = document.getElementById('badge-bwtest-server');
  14296. if (s.enabled && s.running) {
  14297. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14298. if (badge) {
  14299. badge.innerText = `Port ${s.port} (Active)`;
  14300. badge.className = 'text-emerald-400 font-bold';
  14301. }
  14302. if (sideBadge) {
  14303. sideBadge.innerText = s.port;
  14304. 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';
  14305. }
  14306. } else {
  14307. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14308. if (badge) {
  14309. badge.innerText = `Disabled`;
  14310. badge.className = 'text-slate-500 font-bold';
  14311. }
  14312. if (sideBadge) {
  14313. sideBadge.innerText = 'Off';
  14314. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14315. }
  14316. }
  14317. // Modal fields
  14318. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14319. const serverModal = document.getElementById('modal-bwtest-server');
  14320. const editing = serverModal && !serverModal.classList.contains('hidden');
  14321. if (toggle && !editing) toggle.checked = !!s.enabled;
  14322. const portInp = document.getElementById('bwtest-server-port-input');
  14323. if (portInp && !editing) portInp.value = s.port || 2000;
  14324. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14325. if (actSess) actSess.innerText = s.active_sessions || 0;
  14326. const totServ = document.getElementById('bwtest-modal-total-served');
  14327. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14328. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14329. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14330. } catch (err) {
  14331. console.error('Failed to fetch BwTest server status:', err);
  14332. }
  14333. }
  14334. function openBwTestServerModal() {
  14335. const cfg = bwtestState.serverConfig;
  14336. if (cfg) {
  14337. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14338. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14339. }
  14340. fetchBwTestServerStatus();
  14341. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14342. }
  14343. function closeBwTestServerModal() {
  14344. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14345. }
  14346. async function submitBwTestServerSettings(e) {
  14347. e.preventDefault();
  14348. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14349. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14350. try {
  14351. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14352. method: 'POST',
  14353. headers: { 'Content-Type': 'application/json' },
  14354. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14355. });
  14356. if (!res.ok) {
  14357. const err = await res.json();
  14358. throw new Error(err.error || 'Failed to update server configuration');
  14359. }
  14360. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14361. closeBwTestServerModal();
  14362. fetchBwTestServerStatus();
  14363. } catch (err) {
  14364. showToast('Server Configuration Error', err.message, 'error');
  14365. }
  14366. }
  14367. function setBwTestTarget(target) {
  14368. const inp = document.getElementById('bwtest-input-target');
  14369. if (inp) inp.value = target;
  14370. }
  14371. function setBwTestProtocol(proto) {
  14372. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14373. if (hiddenInp) hiddenInp.value = proto;
  14374. const btnUdp = document.getElementById('bwtest-proto-udp');
  14375. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14376. const badge = document.getElementById('bwtest-proto-badge');
  14377. const pktField = document.getElementById('bwtest-field-pktsize');
  14378. 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';
  14379. 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';
  14380. 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';
  14381. if (proto === 'udp') {
  14382. if (btnUdp) {
  14383. btnUdp.className = activeUdpCls;
  14384. const dot = btnUdp.querySelector('span');
  14385. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14386. }
  14387. if (btnTcp) {
  14388. btnTcp.className = inactiveCls;
  14389. const dot = btnTcp.querySelector('span');
  14390. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14391. }
  14392. if (badge) {
  14393. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14394. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14395. }
  14396. if (pktField) pktField.classList.remove('opacity-40');
  14397. } else {
  14398. if (btnUdp) {
  14399. btnUdp.className = inactiveCls;
  14400. const dot = btnUdp.querySelector('span');
  14401. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14402. }
  14403. if (btnTcp) {
  14404. btnTcp.className = activeTcpCls;
  14405. const dot = btnTcp.querySelector('span');
  14406. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14407. }
  14408. if (badge) {
  14409. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14410. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14411. }
  14412. if (pktField) pktField.classList.add('opacity-40');
  14413. }
  14414. }
  14415. function setBwTestDirection(dir) {
  14416. const hiddenInp = document.getElementById('bwtest-input-direction');
  14417. if (hiddenInp) hiddenInp.value = dir;
  14418. const btnBoth = document.getElementById('bwtest-dir-both');
  14419. const btnTx = document.getElementById('bwtest-dir-tx');
  14420. const btnRx = document.getElementById('bwtest-dir-rx');
  14421. 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';
  14422. 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';
  14423. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14424. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14425. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14426. }
  14427. function setBwTestLimit(bps) {
  14428. const sel = document.getElementById('bwtest-input-limit');
  14429. if (sel) sel.value = String(bps);
  14430. }
  14431. async function checkActiveBwTest() {
  14432. try {
  14433. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14434. if (!res.ok) return;
  14435. const st = await res.json();
  14436. if (st.running) {
  14437. setBwTestRunningUI(true);
  14438. processBwTestStatus(st);
  14439. startBwTestTelemetry();
  14440. }
  14441. } catch (err) {
  14442. console.error('Failed to check active BwTest:', err);
  14443. }
  14444. }
  14445. async function startBwTest(e) {
  14446. if (e && e.preventDefault) e.preventDefault();
  14447. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14448. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14449. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14450. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14451. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14452. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14453. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14454. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14455. bwtestState.targetDuration = duration;
  14456. bwtestState.chartPoints = [];
  14457. bwtestState.peakTx = 0;
  14458. bwtestState.peakRx = 0;
  14459. bwtestState.lastSampleElapsed = -1;
  14460. bwtestState.sessionID = null;
  14461. // Clear UI elements
  14462. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14463. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14464. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14465. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14466. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14467. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14468. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14469. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14470. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14471. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14472. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14473. const tbody = document.getElementById('bwtest-samples-tbody');
  14474. if (tbody) tbody.innerHTML = '';
  14475. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14476. setBwTestRunningUI(true);
  14477. try {
  14478. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14479. method: 'POST',
  14480. headers: { 'Content-Type': 'application/json' },
  14481. body: JSON.stringify({
  14482. target,
  14483. port,
  14484. direction,
  14485. protocol,
  14486. bandwidth_limit,
  14487. packet_size,
  14488. streams,
  14489. duration
  14490. })
  14491. });
  14492. if (!res.ok) {
  14493. const err = await res.json();
  14494. throw new Error(err.error || 'Failed to start bandwidth test');
  14495. }
  14496. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14497. startBwTestTelemetry();
  14498. } catch (err) {
  14499. setBwTestRunningUI(false);
  14500. showToast('Start Failed', err.message, 'error');
  14501. }
  14502. }
  14503. function setBwTestRunningUI(running) {
  14504. bwtestState.running = running;
  14505. const startBtn = document.getElementById('bwtest-btn-start');
  14506. const stopBtn = document.getElementById('bwtest-btn-stop');
  14507. const badge = document.getElementById('bwtest-run-status-badge');
  14508. const ph = document.getElementById('bwtest-chart-placeholder');
  14509. if (running) {
  14510. if (startBtn) {
  14511. startBtn.disabled = true;
  14512. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14513. }
  14514. if (stopBtn) {
  14515. stopBtn.disabled = false;
  14516. stopBtn.classList.remove('opacity-40');
  14517. }
  14518. if (badge) {
  14519. badge.innerText = 'TESTING...';
  14520. 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';
  14521. }
  14522. if (ph) ph.style.display = 'none';
  14523. } else {
  14524. if (startBtn) {
  14525. startBtn.disabled = false;
  14526. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14527. }
  14528. if (stopBtn) {
  14529. stopBtn.disabled = true;
  14530. stopBtn.classList.add('opacity-40');
  14531. }
  14532. if (badge) {
  14533. badge.innerText = 'IDLE';
  14534. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14535. }
  14536. }
  14537. }
  14538. async function stopBwTest() {
  14539. try {
  14540. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14541. if (!res.ok) throw new Error(await responseError(res));
  14542. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14543. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14544. } catch (err) {
  14545. showToast('Stop Failed', err.message, 'error');
  14546. }
  14547. }
  14548. async function responseError(res) {
  14549. const text = await res.text();
  14550. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14551. catch { return text || `HTTP ${res.status}`; }
  14552. }
  14553. function processBwTestStatus(st) {
  14554. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14555. bwtestState.sessionID = st.session_id;
  14556. bwtestState.lastSampleElapsed = -1;
  14557. }
  14558. for (const sample of st.recent_samples || []) {
  14559. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14560. handleBwTestSample(sample);
  14561. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14562. }
  14563. }
  14564. if (!st.running) {
  14565. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14566. bwtestState.pollTimer = null;
  14567. setBwTestRunningUI(false);
  14568. handleBwTestFinish(st.summary, st.error);
  14569. }
  14570. }
  14571. function startBwTestTelemetry() {
  14572. if (!state.currentUser) return;
  14573. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14574. let busy = false;
  14575. const poll = async () => {
  14576. if (busy || !state.currentUser || document.hidden) return;
  14577. busy = true;
  14578. try {
  14579. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14580. if (!res.ok) throw new Error(await responseError(res));
  14581. processBwTestStatus(await res.json());
  14582. } catch (err) {
  14583. console.error('BwTest polling error:', err);
  14584. } finally { busy = false; }
  14585. };
  14586. bwtestState.pollTimer = setInterval(poll, 400);
  14587. poll();
  14588. }
  14589. function handleBwTestSample(s) {
  14590. if (!s) return;
  14591. const payloadHint = document.getElementById('bwtest-effective-payload');
  14592. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14593. const txMbps = s.tx_mbps || 0;
  14594. const rxMbps = s.rx_mbps || 0;
  14595. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14596. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14597. // KPI updates
  14598. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14599. if (elTx) {
  14600. elTx.innerText = txMbps.toFixed(2);
  14601. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14602. }
  14603. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14604. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14605. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14606. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14607. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14608. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14609. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14610. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14611. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14612. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14613. const elLoss = document.getElementById('bwtest-stat-loss');
  14614. if (elLoss) {
  14615. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14616. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14617. }
  14618. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14619. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14620. const elJitter = document.getElementById('bwtest-stat-jitter');
  14621. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14622. const elTime = document.getElementById('bwtest-stat-time');
  14623. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14624. const elData = document.getElementById('bwtest-stat-data');
  14625. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14626. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14627. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14628. // Append point to chart buffer
  14629. bwtestState.chartPoints.push({
  14630. elapsed: s.elapsed_sec || 0,
  14631. tx: txMbps,
  14632. rx: rxMbps
  14633. });
  14634. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14635. bwtestState.chartPoints.shift();
  14636. }
  14637. drawBwTestChart();
  14638. // Add row to breakdown table
  14639. const tbody = document.getElementById('bwtest-samples-tbody');
  14640. if (tbody) {
  14641. const tr = document.createElement('tr');
  14642. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14643. tr.innerHTML = `
  14644. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14645. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14646. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14647. <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>
  14648. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14649. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14650. `;
  14651. tbody.insertBefore(tr, tbody.firstChild);
  14652. const countEl = document.getElementById('bwtest-sample-count');
  14653. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14654. }
  14655. }
  14656. function handleBwTestFinish(summary, error) {
  14657. const badge = document.getElementById('bwtest-run-status-badge');
  14658. if (error) {
  14659. showToast('Benchmark Error', error, 'error');
  14660. if (badge) {
  14661. badge.innerText = 'ERROR';
  14662. 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';
  14663. }
  14664. } else if (summary) {
  14665. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14666. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14667. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14668. if (badge) {
  14669. badge.innerText = 'COMPLETED';
  14670. 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';
  14671. }
  14672. }
  14673. loadBwTestHistory();
  14674. fetchBwTestServerStatus();
  14675. }
  14676. function resizeBwTestCanvas() {
  14677. const canvas = document.getElementById('bwtest-chart');
  14678. if (!canvas || !canvas.parentElement) return;
  14679. const rect = canvas.parentElement.getBoundingClientRect();
  14680. const dpr = window.devicePixelRatio || 1;
  14681. canvas.width = rect.width * dpr;
  14682. canvas.height = rect.height * dpr;
  14683. const ctx = canvas.getContext('2d');
  14684. ctx.scale(dpr, dpr);
  14685. drawBwTestChart();
  14686. }
  14687. window.addEventListener('resize', () => {
  14688. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14689. });
  14690. function drawBwTestChart() {
  14691. const canvas = document.getElementById('bwtest-chart');
  14692. if (!canvas) return;
  14693. const ctx = canvas.getContext('2d');
  14694. const dpr = window.devicePixelRatio || 1;
  14695. const width = canvas.width / dpr;
  14696. const height = canvas.height / dpr;
  14697. ctx.clearRect(0, 0, width, height);
  14698. const points = bwtestState.chartPoints;
  14699. if (!points || points.length === 0) return;
  14700. // Determine scale ceiling
  14701. let maxRate = 10;
  14702. for (const p of points) {
  14703. if (p.tx > maxRate) maxRate = p.tx;
  14704. if (p.rx > maxRate) maxRate = p.rx;
  14705. }
  14706. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14707. const paddingLeft = 55;
  14708. const paddingBottom = 24;
  14709. const paddingTop = 12;
  14710. const paddingRight = 16;
  14711. const chartW = width - paddingLeft - paddingRight;
  14712. const chartH = height - paddingTop - paddingBottom;
  14713. // Grid Lines and Y-Axis labels
  14714. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14715. ctx.lineWidth = 1;
  14716. ctx.fillStyle = '#94a3b8';
  14717. ctx.font = '10px monospace';
  14718. ctx.textAlign = 'right';
  14719. const gridSteps = 4;
  14720. for (let i = 0; i <= gridSteps; i++) {
  14721. const val = (maxRate / gridSteps) * i;
  14722. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14723. ctx.beginPath();
  14724. ctx.moveTo(paddingLeft, y);
  14725. ctx.lineTo(width - paddingRight, y);
  14726. ctx.stroke();
  14727. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14728. }
  14729. // Draw TX Line (Cyan #22d3ee)
  14730. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14731. // Draw RX Line (Purple #a855f7)
  14732. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14733. }
  14734. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14735. if (points.length < 2) return;
  14736. const stepX = w / Math.max(points.length - 1, 1);
  14737. // Gradient area fill
  14738. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14739. grad.addColorStop(0, fillColor);
  14740. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14741. ctx.beginPath();
  14742. points.forEach((p, idx) => {
  14743. const x = left + idx * stepX;
  14744. const val = valFn(p);
  14745. const y = top + h - (val / maxVal) * h;
  14746. if (idx === 0) {
  14747. ctx.moveTo(x, y);
  14748. } else {
  14749. ctx.lineTo(x, y);
  14750. }
  14751. });
  14752. // Complete path for fill
  14753. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14754. ctx.lineTo(left, top + h);
  14755. ctx.closePath();
  14756. ctx.fillStyle = grad;
  14757. ctx.fill();
  14758. // Draw line stroke
  14759. ctx.beginPath();
  14760. ctx.lineWidth = 2.5;
  14761. ctx.strokeStyle = strokeColor;
  14762. points.forEach((p, idx) => {
  14763. const x = left + idx * stepX;
  14764. const val = valFn(p);
  14765. const y = top + h - (val / maxVal) * h;
  14766. if (idx === 0) {
  14767. ctx.moveTo(x, y);
  14768. } else {
  14769. ctx.lineTo(x, y);
  14770. }
  14771. });
  14772. ctx.stroke();
  14773. // Draw end point halo
  14774. const lastP = points[points.length - 1];
  14775. const lastX = left + (points.length - 1) * stepX;
  14776. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14777. ctx.fillStyle = strokeColor;
  14778. ctx.beginPath();
  14779. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14780. ctx.fill();
  14781. }
  14782. async function loadBwTestHistory() {
  14783. try {
  14784. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14785. if (!res.ok) return;
  14786. const list = await res.json();
  14787. renderBwTestHistory(Array.isArray(list) ? list : []);
  14788. } catch (err) {
  14789. console.error('Failed to load BwTest history:', err);
  14790. }
  14791. }
  14792. function renderBwTestHistory(list) {
  14793. const tbody = document.getElementById('bwtest-history-tbody');
  14794. if (!tbody) return;
  14795. if (list.length === 0) {
  14796. 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>`;
  14797. return;
  14798. }
  14799. tbody.innerHTML = '';
  14800. list.forEach(item => {
  14801. const s = item.summary || {};
  14802. const tr = document.createElement('tr');
  14803. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14804. const dirBadge = item.direction === 'both'
  14805. ? `<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>`
  14806. : item.direction === 'tx'
  14807. ? `<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>`
  14808. : `<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>`;
  14809. const protoBadge = item.protocol === 'tcp'
  14810. ? `<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>`
  14811. : `<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>`;
  14812. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14813. tr.innerHTML = `
  14814. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14815. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14816. <td class="py-2.5 px-4">${protoBadge}</td>
  14817. <td class="py-2.5 px-4">${dirBadge}</td>
  14818. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14819. <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>
  14820. <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>
  14821. <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>
  14822. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14823. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14824. `;
  14825. tbody.appendChild(tr);
  14826. });
  14827. }
  14828. // ======================== SETTINGS & ROUTER DNS ========================
  14829. state.settingsSubTab = 'dns';
  14830. state.dnsSettings = null;
  14831. state.dnsStaticRecords = [];
  14832. state.dnsStatus = null;
  14833. function switchSettingsSubTab(sub) {
  14834. state.settingsSubTab = sub;
  14835. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14836. const btnSys = document.getElementById('btn-settings-subtab-system');
  14837. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14838. const tabDns = document.getElementById('settings-subtab-dns');
  14839. const tabSys = document.getElementById('settings-subtab-system');
  14840. const tabBak = document.getElementById('settings-subtab-backup');
  14841. 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';
  14842. 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';
  14843. if (btnDns) btnDns.className = inactiveClass;
  14844. if (btnSys) btnSys.className = inactiveClass;
  14845. if (btnBak) btnBak.className = inactiveClass;
  14846. tabDns?.classList.add('hidden');
  14847. tabSys?.classList.add('hidden');
  14848. tabBak?.classList.add('hidden');
  14849. if (sub === 'dns') {
  14850. if (btnDns) btnDns.className = activeClass;
  14851. tabDns?.classList.remove('hidden');
  14852. loadDNSSettings();
  14853. } else if (sub === 'system') {
  14854. if (btnSys) btnSys.className = activeClass;
  14855. tabSys?.classList.remove('hidden');
  14856. loadSystemSettings();
  14857. } else if (sub === 'backup') {
  14858. if (btnBak) btnBak.className = activeClass;
  14859. tabBak?.classList.remove('hidden');
  14860. loadBackupList();
  14861. }
  14862. }
  14863. async function loadSettingsData(showLoading = false) {
  14864. if (state.settingsSubTab === 'system') {
  14865. await loadSystemSettings();
  14866. } else if (state.settingsSubTab === 'backup') {
  14867. await loadBackupList();
  14868. } else {
  14869. await loadDNSSettings();
  14870. }
  14871. }
  14872. async function loadDNSSettings() {
  14873. try {
  14874. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14875. fetch(`${API_BASE}/dns/settings`),
  14876. fetch(`${API_BASE}/dns/static`),
  14877. fetch(`${API_BASE}/dns/status`)
  14878. ]);
  14879. if (settingsRes.ok) {
  14880. state.dnsSettings = await settingsRes.json();
  14881. populateDNSSettingsForm(state.dnsSettings);
  14882. }
  14883. if (staticRes.ok) {
  14884. state.dnsStaticRecords = await staticRes.json();
  14885. renderStaticDNSList();
  14886. }
  14887. if (statusRes.ok) {
  14888. state.dnsStatus = await statusRes.json();
  14889. updateDNSStatusView(state.dnsStatus);
  14890. }
  14891. } catch (err) {
  14892. console.error('Failed to load DNS settings:', err);
  14893. }
  14894. }
  14895. function populateDNSSettingsForm(s) {
  14896. if (!s) return;
  14897. const dnsForm = document.getElementById('form-dns-settings');
  14898. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14899. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14900. if (dynamicEl) {
  14901. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14902. 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(' ');
  14903. } else {
  14904. dynamicEl.innerText = 'None';
  14905. }
  14906. }
  14907. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14908. if (isEditing) return;
  14909. const serversInput = document.getElementById('dns-servers-input');
  14910. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14911. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14912. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14913. const domainInput = document.getElementById('dns-domain-input');
  14914. if (domainInput) domainInput.value = s.domain || '';
  14915. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14916. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14917. }
  14918. function updateDNSStatusView(st) {
  14919. if (!st) return;
  14920. const preview = document.getElementById('dns-resolv-preview');
  14921. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14922. const pillText = document.getElementById('dns-live-status-text');
  14923. const pill = document.getElementById('dns-live-status-pill');
  14924. if (pill && pillText) {
  14925. if (st.service_running) {
  14926. 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';
  14927. pillText.innerText = 'DNS Service Active';
  14928. } else {
  14929. 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';
  14930. pillText.innerText = 'DNS Service Inactive';
  14931. }
  14932. }
  14933. }
  14934. function appendDNSPreset(preset) {
  14935. const input = document.getElementById('dns-servers-input');
  14936. if (!input) return;
  14937. const dnsForm = document.getElementById('form-dns-settings');
  14938. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14939. const current = input.value.trim();
  14940. if (!current) {
  14941. input.value = preset;
  14942. } else {
  14943. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14944. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14945. toAdd.forEach(ip => {
  14946. if (!existing.includes(ip)) existing.push(ip);
  14947. });
  14948. input.value = existing.join(', ');
  14949. }
  14950. }
  14951. async function saveDNSSettings(e) {
  14952. e.preventDefault();
  14953. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14954. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14955. if (servers.length === 0) {
  14956. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14957. return;
  14958. }
  14959. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14960. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14961. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14962. try {
  14963. const res = await fetch(`${API_BASE}/dns/settings`, {
  14964. method: 'POST',
  14965. headers: { 'Content-Type': 'application/json' },
  14966. body: JSON.stringify({
  14967. servers: servers,
  14968. cache_size: cacheSize,
  14969. domain: domain,
  14970. allow_remote_requests: allowRemote
  14971. })
  14972. });
  14973. const data = await res.json();
  14974. if (res.ok) {
  14975. const dnsForm = document.getElementById('form-dns-settings');
  14976. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14977. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14978. loadDNSSettings();
  14979. } else {
  14980. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14981. }
  14982. } catch (err) {
  14983. showToast('Error', err.message, 'error');
  14984. }
  14985. }
  14986. async function flushDNSCache() {
  14987. try {
  14988. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14989. if (res.ok) {
  14990. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14991. loadDNSSettings();
  14992. } else {
  14993. const err = await res.json();
  14994. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14995. }
  14996. } catch (err) {
  14997. showToast('Error', err.message, 'error');
  14998. }
  14999. }
  15000. function renderStaticDNSList() {
  15001. const tbody = document.getElementById('dns-static-tbody');
  15002. const empty = document.getElementById('dns-static-empty');
  15003. const badge = document.getElementById('dns-static-count-badge');
  15004. if (!tbody) return;
  15005. tbody.innerHTML = '';
  15006. const records = state.dnsStaticRecords || [];
  15007. if (badge) badge.innerText = `${records.length} Records`;
  15008. if (records.length === 0) {
  15009. empty?.classList.remove('hidden');
  15010. return;
  15011. }
  15012. empty?.classList.add('hidden');
  15013. records.forEach(rec => {
  15014. const tr = document.createElement('tr');
  15015. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15016. tr.innerHTML = `
  15017. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15018. <td class="py-2.5 px-4">
  15019. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15020. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15021. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15022. }">
  15023. ${rec.type || 'A'}
  15024. </span>
  15025. </td>
  15026. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15027. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15028. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15029. <td class="py-2.5 px-4">
  15030. <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'}">
  15031. ${rec.disabled ? 'Disabled' : 'Active'}
  15032. </span>
  15033. </td>
  15034. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15035. <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>
  15036. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15037. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15038. </td>
  15039. `;
  15040. tbody.appendChild(tr);
  15041. });
  15042. }
  15043. function openStaticDNSModal(id = null) {
  15044. const modal = document.getElementById('modal-static-dns');
  15045. const title = document.getElementById('modal-static-dns-title');
  15046. const form = document.getElementById('form-static-dns');
  15047. if (!modal || !form) return;
  15048. form.reset();
  15049. document.getElementById('modal-static-dns-id').value = '';
  15050. if (id) {
  15051. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15052. if (rec) {
  15053. if (title) title.innerText = 'Edit Static DNS Record';
  15054. document.getElementById('modal-static-dns-id').value = rec.id;
  15055. document.getElementById('modal-static-dns-name').value = rec.name;
  15056. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15057. document.getElementById('modal-static-dns-addr').value = rec.address;
  15058. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15059. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15060. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15061. }
  15062. } else {
  15063. if (title) title.innerText = 'Add Static DNS Record';
  15064. }
  15065. modal.classList.remove('hidden');
  15066. }
  15067. function closeStaticDNSModal() {
  15068. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15069. }
  15070. async function submitSaveStaticDNS(e) {
  15071. e.preventDefault();
  15072. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15073. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15074. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15075. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15076. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15077. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15078. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15079. if (!name || !address) {
  15080. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15081. return;
  15082. }
  15083. try {
  15084. const res = await fetch(`${API_BASE}/dns/static`, {
  15085. method: 'POST',
  15086. headers: { 'Content-Type': 'application/json' },
  15087. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15088. });
  15089. const data = await res.json();
  15090. if (res.ok) {
  15091. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15092. closeStaticDNSModal();
  15093. loadDNSSettings();
  15094. } else {
  15095. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15096. }
  15097. } catch (err) {
  15098. showToast('Error', err.message, 'error');
  15099. }
  15100. }
  15101. async function deleteStaticDNS(id) {
  15102. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15103. try {
  15104. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15105. if (res.ok) {
  15106. showToast('Deleted', 'Static DNS record deleted', 'success');
  15107. loadDNSSettings();
  15108. }
  15109. } catch (err) {
  15110. showToast('Error', err.message, 'error');
  15111. }
  15112. }
  15113. async function toggleStaticDNS(id, disabled) {
  15114. try {
  15115. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15116. method: 'POST',
  15117. headers: { 'Content-Type': 'application/json' },
  15118. body: JSON.stringify({ disabled })
  15119. });
  15120. if (res.ok) {
  15121. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15122. loadDNSSettings();
  15123. }
  15124. } catch (err) {
  15125. showToast('Error', err.message, 'error');
  15126. }
  15127. }
  15128. async function loadSystemSettings() {
  15129. try {
  15130. const sysForm = document.getElementById('form-system-settings');
  15131. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15132. const res = await fetch(`${API_BASE}/system/settings`);
  15133. if (res.ok) {
  15134. const data = await res.json();
  15135. if (!isEditing) {
  15136. const hostInput = document.getElementById('system-hostname-input');
  15137. if (hostInput) hostInput.value = data.hostname || '';
  15138. const tzInput = document.getElementById('system-timezone-input');
  15139. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15140. }
  15141. }
  15142. } catch (err) {
  15143. console.error('Failed to load system settings:', err);
  15144. }
  15145. }
  15146. async function saveSystemSettings(e) {
  15147. e.preventDefault();
  15148. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15149. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15150. try {
  15151. const res = await fetch(`${API_BASE}/system/settings`, {
  15152. method: 'POST',
  15153. headers: { 'Content-Type': 'application/json' },
  15154. body: JSON.stringify({ hostname, timezone })
  15155. });
  15156. const data = await res.json();
  15157. if (res.ok) {
  15158. const sysForm = document.getElementById('form-system-settings');
  15159. if (sysForm) sysForm.dataset.dirty = 'false';
  15160. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15161. const sideH = document.getElementById('side-hostname');
  15162. if (sideH) sideH.innerText = data.hostname;
  15163. } else {
  15164. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15165. }
  15166. } catch (err) {
  15167. showToast('Error', err.message, 'error');
  15168. }
  15169. }
  15170. // =============================================================================
  15171. // BACKUP & RESTORE MANAGER
  15172. // =============================================================================
  15173. state.selectedBackupFile = null;
  15174. state.inspectedBackupManifest = null;
  15175. state.pendingRestoreTarget = null;
  15176. state.backupsList = [];
  15177. async function exportBackupDownload() {
  15178. const btn = document.getElementById('btn-export-backup');
  15179. const commentInput = document.getElementById('backup-export-comment');
  15180. const comment = (commentInput?.value || '').trim();
  15181. const originalHtml = btn ? btn.innerHTML : '';
  15182. if (btn) {
  15183. btn.disabled = true;
  15184. 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...`;
  15185. }
  15186. try {
  15187. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15188. if (!res.ok) {
  15189. const err = await res.json().catch(() => ({}));
  15190. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15191. return;
  15192. }
  15193. const blob = await res.blob();
  15194. const disposition = res.headers.get('Content-Disposition') || '';
  15195. let filename = 'debtik-backup.zip';
  15196. const match = disposition.match(/filename="?([^";]+)"?/);
  15197. if (match && match[1]) {
  15198. filename = match[1];
  15199. }
  15200. const blobUrl = window.URL.createObjectURL(blob);
  15201. const a = document.createElement('a');
  15202. a.href = blobUrl;
  15203. a.download = filename;
  15204. document.body.appendChild(a);
  15205. a.click();
  15206. setTimeout(() => {
  15207. window.URL.revokeObjectURL(blobUrl);
  15208. a.remove();
  15209. }, 1000);
  15210. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15211. } catch (err) {
  15212. showToast('Export Error', err.message || 'Network error during download', 'error');
  15213. } finally {
  15214. if (btn) {
  15215. btn.disabled = false;
  15216. btn.innerHTML = originalHtml;
  15217. }
  15218. }
  15219. }
  15220. async function onBackupFileSelected(e) {
  15221. const file = e.target.files?.[0];
  15222. if (!file) return;
  15223. const label = document.getElementById('backup-file-label');
  15224. if (label) {
  15225. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15226. }
  15227. await inspectBackupFile(file);
  15228. }
  15229. async function inspectBackupFile(file) {
  15230. const preview = document.getElementById('backup-inspect-preview');
  15231. const restoreBtn = document.getElementById('btn-restore-backup');
  15232. const formData = new FormData();
  15233. formData.append('backup', file);
  15234. try {
  15235. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15236. method: 'POST',
  15237. body: formData
  15238. });
  15239. const data = await res.json();
  15240. if (!res.ok || !data.success || !data.manifest) {
  15241. if (preview) preview.classList.add('hidden');
  15242. if (restoreBtn) restoreBtn.disabled = true;
  15243. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15244. return;
  15245. }
  15246. const mf = data.manifest;
  15247. state.selectedBackupFile = file;
  15248. state.inspectedBackupManifest = mf;
  15249. const vEl = document.getElementById('backup-inspect-version');
  15250. const hEl = document.getElementById('backup-inspect-hostname');
  15251. const fEl = document.getElementById('backup-inspect-files');
  15252. const dEl = document.getElementById('backup-inspect-date');
  15253. const cEl = document.getElementById('backup-inspect-comment');
  15254. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15255. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15256. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15257. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15258. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15259. if (preview) preview.classList.remove('hidden');
  15260. if (restoreBtn) restoreBtn.disabled = false;
  15261. } catch (err) {
  15262. if (preview) preview.classList.add('hidden');
  15263. if (restoreBtn) restoreBtn.disabled = true;
  15264. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15265. }
  15266. }
  15267. function confirmRestoreBackup(localFilename = null) {
  15268. const modal = document.getElementById('modal-restore-confirm');
  15269. const details = document.getElementById('modal-restore-details');
  15270. const progress = document.getElementById('modal-restore-progress');
  15271. const cancelBtn = document.getElementById('btn-cancel-restore');
  15272. const execBtn = document.getElementById('btn-execute-restore');
  15273. if (progress) progress.classList.add('hidden');
  15274. if (cancelBtn) cancelBtn.disabled = false;
  15275. if (execBtn) {
  15276. execBtn.disabled = false;
  15277. execBtn.innerText = 'Yes, Restore & Reload';
  15278. }
  15279. if (localFilename) {
  15280. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15281. if (details) {
  15282. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15283. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15284. }
  15285. } else {
  15286. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15287. showToast('Error', 'Please select a valid backup archive first', 'error');
  15288. return;
  15289. }
  15290. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15291. const mf = state.inspectedBackupManifest;
  15292. if (details) {
  15293. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15294. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15295. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15296. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15297. }
  15298. }
  15299. if (modal) modal.classList.remove('hidden');
  15300. }
  15301. function closeRestoreModal() {
  15302. const modal = document.getElementById('modal-restore-confirm');
  15303. if (modal) modal.classList.add('hidden');
  15304. }
  15305. async function executeRestoreBackup() {
  15306. const target = state.pendingRestoreTarget;
  15307. if (!target) return;
  15308. const progress = document.getElementById('modal-restore-progress');
  15309. const progressText = document.getElementById('modal-restore-progress-text');
  15310. const cancelBtn = document.getElementById('btn-cancel-restore');
  15311. const execBtn = document.getElementById('btn-execute-restore');
  15312. if (cancelBtn) cancelBtn.disabled = true;
  15313. if (execBtn) execBtn.disabled = true;
  15314. if (progress) progress.classList.remove('hidden');
  15315. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15316. try {
  15317. let res;
  15318. if (target.type === 'file') {
  15319. const formData = new FormData();
  15320. formData.append('backup', target.file);
  15321. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15322. method: 'POST',
  15323. body: formData
  15324. });
  15325. } else {
  15326. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15327. method: 'POST'
  15328. });
  15329. }
  15330. const data = await res.json();
  15331. if (!res.ok || !data.success) {
  15332. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15333. if (cancelBtn) cancelBtn.disabled = false;
  15334. if (execBtn) execBtn.disabled = false;
  15335. if (progress) progress.classList.add('hidden');
  15336. return;
  15337. }
  15338. if (progressText) {
  15339. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15340. }
  15341. pollAfterRestoreReconnect();
  15342. } catch (err) {
  15343. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15344. if (cancelBtn) cancelBtn.disabled = false;
  15345. if (execBtn) execBtn.disabled = false;
  15346. if (progress) progress.classList.add('hidden');
  15347. }
  15348. }
  15349. function pollAfterRestoreReconnect() {
  15350. let attempts = 0;
  15351. const maxAttempts = 25;
  15352. const timer = setInterval(async () => {
  15353. attempts++;
  15354. try {
  15355. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15356. if (res.ok) {
  15357. clearInterval(timer);
  15358. closeRestoreModal();
  15359. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15360. setTimeout(() => {
  15361. window.location.reload();
  15362. }, 1200);
  15363. }
  15364. } catch (_) {
  15365. // Still restarting, retry
  15366. }
  15367. if (attempts >= maxAttempts) {
  15368. clearInterval(timer);
  15369. closeRestoreModal();
  15370. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15371. }
  15372. }, 1500);
  15373. }
  15374. async function loadBackupList() {
  15375. const tbody = document.getElementById('backups-table-tbody');
  15376. const empty = document.getElementById('backups-empty-state');
  15377. if (!tbody) return;
  15378. try {
  15379. const res = await fetch(`${API_BASE}/system/backups`);
  15380. if (!res.ok) return;
  15381. const list = await res.json();
  15382. state.backupsList = list || [];
  15383. renderBackupsTable(state.backupsList);
  15384. } catch (err) {
  15385. console.error('Failed to load backup list:', err);
  15386. }
  15387. }
  15388. function renderBackupsTable(backups) {
  15389. const tbody = document.getElementById('backups-table-tbody');
  15390. const empty = document.getElementById('backups-empty-state');
  15391. if (!tbody) return;
  15392. if (!backups || backups.length === 0) {
  15393. tbody.innerHTML = '';
  15394. if (empty) empty.classList.remove('hidden');
  15395. return;
  15396. }
  15397. if (empty) empty.classList.add('hidden');
  15398. tbody.innerHTML = backups.map(bk => {
  15399. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15400. const badge = isAuto
  15401. ? `<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>`
  15402. : `<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>`;
  15403. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15404. return `<tr class="hover:bg-slate-800/40 transition">
  15405. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15406. ${badge}
  15407. <span>${escapeHtml(bk.filename)}</span>
  15408. </td>
  15409. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15410. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15411. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15412. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15413. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15414. <td class="py-3 px-4 text-right space-x-2">
  15415. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15416. 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">
  15417. Download
  15418. </button>
  15419. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15420. 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">
  15421. Restore
  15422. </button>
  15423. </td>
  15424. </tr>`;
  15425. }).join('');
  15426. }
  15427. async function downloadLocalBackup(filename) {
  15428. try {
  15429. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15430. if (!res.ok) {
  15431. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15432. return;
  15433. }
  15434. const blob = await res.blob();
  15435. const blobUrl = window.URL.createObjectURL(blob);
  15436. const a = document.createElement('a');
  15437. a.href = blobUrl;
  15438. a.download = filename;
  15439. document.body.appendChild(a);
  15440. a.click();
  15441. setTimeout(() => {
  15442. window.URL.revokeObjectURL(blobUrl);
  15443. a.remove();
  15444. }, 1000);
  15445. } catch (err) {
  15446. showToast('Download Error', err.message, 'error');
  15447. }
  15448. }
  15449. // =============================================================================
  15450. // AUTHENTICATION & USER MANAGER
  15451. // =============================================================================
  15452. async function checkAuthStatus() {
  15453. try {
  15454. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15455. headers: {
  15456. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15457. }
  15458. });
  15459. if (res.ok) {
  15460. const user = await res.json();
  15461. state.currentUser = user;
  15462. updateUserProfileHeader(user);
  15463. hideLoginScreen();
  15464. state.isPolling = true;
  15465. fetchData();
  15466. initLiveTrafficStream();
  15467. return true;
  15468. } else {
  15469. showLoginScreen(false);
  15470. return false;
  15471. }
  15472. } catch (err) {
  15473. showLoginScreen(false);
  15474. return false;
  15475. }
  15476. }
  15477. function showLoginScreen(isExpired = false) {
  15478. const el = document.getElementById('login-screen');
  15479. if (el) el.classList.remove('hidden');
  15480. const errEl = document.getElementById('login-error');
  15481. const errTxt = document.getElementById('login-error-text');
  15482. if (isExpired && errEl && errTxt) {
  15483. errTxt.innerText = 'Session expired. Please sign in again.';
  15484. errEl.classList.remove('hidden');
  15485. } else if (errEl) {
  15486. errEl.classList.add('hidden');
  15487. }
  15488. const pwInput = document.getElementById('login-password');
  15489. if (pwInput) pwInput.value = '';
  15490. const userInput = document.getElementById('login-username');
  15491. if (userInput && !userInput.value) userInput.focus();
  15492. else if (pwInput) pwInput.focus();
  15493. }
  15494. function hideLoginScreen() {
  15495. const el = document.getElementById('login-screen');
  15496. if (el) el.classList.add('hidden');
  15497. const errEl = document.getElementById('login-error');
  15498. if (errEl) errEl.classList.add('hidden');
  15499. }
  15500. async function handleLoginSubmit(event) {
  15501. event.preventDefault();
  15502. const username = (document.getElementById('login-username')?.value || '').trim();
  15503. const password = document.getElementById('login-password')?.value || '';
  15504. const errEl = document.getElementById('login-error');
  15505. const errTxt = document.getElementById('login-error-text');
  15506. const btn = document.getElementById('login-submit-btn');
  15507. const btnText = document.getElementById('login-btn-text');
  15508. const spinner = document.getElementById('login-btn-spinner');
  15509. if (!username || !password) {
  15510. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15511. if (errEl) errEl.classList.remove('hidden');
  15512. return;
  15513. }
  15514. if (errEl) errEl.classList.add('hidden');
  15515. if (btn) btn.disabled = true;
  15516. if (btnText) btnText.innerText = 'Authenticating...';
  15517. if (spinner) spinner.classList.remove('hidden');
  15518. try {
  15519. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15520. method: 'POST',
  15521. headers: { 'Content-Type': 'application/json' },
  15522. body: JSON.stringify({ username, password })
  15523. });
  15524. const data = await res.json();
  15525. if (res.ok && data.success) {
  15526. localStorage.setItem('debtik_token', data.token);
  15527. state.currentUser = data.user;
  15528. updateUserProfileHeader(data.user);
  15529. hideLoginScreen();
  15530. state.isPolling = true;
  15531. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15532. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15533. navigate(hash);
  15534. fetchData();
  15535. initLiveTrafficStream();
  15536. // Ensure background telemetry polling is active
  15537. if (!window._telemetryInterval) {
  15538. window._telemetryInterval = setInterval(() => {
  15539. if (state.isPolling && state.currentUser && !document.hidden) {
  15540. fetchData(false);
  15541. }
  15542. }, 5000);
  15543. }
  15544. } else {
  15545. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15546. if (errEl) errEl.classList.remove('hidden');
  15547. }
  15548. } catch (err) {
  15549. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15550. if (errEl) errEl.classList.remove('hidden');
  15551. } finally {
  15552. if (btn) btn.disabled = false;
  15553. if (btnText) btnText.innerText = 'Sign In to Controller';
  15554. if (spinner) spinner.classList.add('hidden');
  15555. }
  15556. }
  15557. async function handleLogoutClick() {
  15558. try {
  15559. await originalFetch(`${API_BASE}/auth/logout`, {
  15560. method: 'POST',
  15561. headers: {
  15562. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15563. }
  15564. });
  15565. } catch (e) {}
  15566. stopSessionPolling();
  15567. localStorage.removeItem('debtik_token');
  15568. state.currentUser = null;
  15569. state.isPolling = false;
  15570. if (window._telemetryInterval) {
  15571. clearInterval(window._telemetryInterval);
  15572. window._telemetryInterval = null;
  15573. }
  15574. if (trafficEventSource) {
  15575. trafficEventSource.close();
  15576. trafficEventSource = null;
  15577. }
  15578. if (trafficPollFallback) {
  15579. clearInterval(trafficPollFallback);
  15580. trafficPollFallback = null;
  15581. }
  15582. showLoginScreen(false);
  15583. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15584. }
  15585. function togglePasswordVisibility(id) {
  15586. const input = document.getElementById(id);
  15587. if (!input) return;
  15588. input.type = input.type === 'password' ? 'text' : 'password';
  15589. }
  15590. function toggleUserMenu() {
  15591. const menu = document.getElementById('user-menu-dropdown');
  15592. if (menu) menu.classList.toggle('hidden');
  15593. }
  15594. function closeUserMenu() {
  15595. const menu = document.getElementById('user-menu-dropdown');
  15596. if (menu) menu.classList.add('hidden');
  15597. }
  15598. // Close user menu on outside click
  15599. document.addEventListener('click', (e) => {
  15600. const menu = document.getElementById('user-menu-dropdown');
  15601. if (!menu || menu.classList.contains('hidden')) return;
  15602. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15603. menu.classList.add('hidden');
  15604. }
  15605. });
  15606. function updateUserProfileHeader(user) {
  15607. if (!user) return;
  15608. const navName = document.getElementById('nav-user-name');
  15609. if (navName) navName.innerText = user.username;
  15610. const dropName = document.getElementById('dropdown-user-name');
  15611. if (dropName) dropName.innerText = user.username;
  15612. const navRole = document.getElementById('nav-user-role');
  15613. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15614. const navAvatar = document.getElementById('nav-user-avatar');
  15615. if (navAvatar) {
  15616. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15617. navAvatar.innerText = initials;
  15618. }
  15619. const statCurUser = document.getElementById('stat-current-user');
  15620. if (statCurUser) statCurUser.innerText = user.username;
  15621. const statCurRole = document.getElementById('stat-current-role');
  15622. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15623. // Role permissions UI visibility: hide user management for non-admins
  15624. const isFullAdmin = user.role === 'full';
  15625. const navUsers = document.getElementById('nav-users');
  15626. if (navUsers) {
  15627. if (isFullAdmin) navUsers.classList.remove('hidden');
  15628. else navUsers.classList.add('hidden');
  15629. }
  15630. const dropdownUsers = document.getElementById('dropdown-item-users');
  15631. if (dropdownUsers) {
  15632. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15633. else dropdownUsers.classList.add('hidden');
  15634. }
  15635. }
  15636. // ================= User Management CRUD =================
  15637. async function loadUsers(isManual = false) {
  15638. try {
  15639. const res = await fetch(`${API_BASE}/users`);
  15640. if (res.status === 403) {
  15641. const tbody = document.getElementById('users-table-tbody');
  15642. if (tbody) {
  15643. tbody.innerHTML = `
  15644. <tr>
  15645. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15646. <div class="inline-flex items-center gap-2">
  15647. <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>
  15648. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15649. </div>
  15650. </td>
  15651. </tr>
  15652. `;
  15653. }
  15654. return;
  15655. }
  15656. if (res.ok) {
  15657. state.users = await res.json();
  15658. renderUsersTable();
  15659. const totalUsers = document.getElementById('stat-total-users');
  15660. if (totalUsers) totalUsers.innerText = state.users.length;
  15661. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15662. const adminUsers = document.getElementById('stat-admin-users');
  15663. if (adminUsers) adminUsers.innerText = adminCount;
  15664. const badgeCount = document.getElementById('badge-users-count');
  15665. if (badgeCount) badgeCount.innerText = state.users.length;
  15666. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15667. }
  15668. } catch (err) {
  15669. console.error('Failed to load users:', err);
  15670. }
  15671. }
  15672. function renderUsersTable() {
  15673. const tbody = document.getElementById('users-table-tbody');
  15674. const emptyState = document.getElementById('users-empty-state');
  15675. if (!tbody) return;
  15676. tbody.innerHTML = '';
  15677. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15678. const filtered = (state.users || []).filter(u => {
  15679. if (!query) return true;
  15680. return u.username.toLowerCase().includes(query) ||
  15681. (u.role || '').toLowerCase().includes(query) ||
  15682. (u.comment || '').toLowerCase().includes(query);
  15683. });
  15684. if (filtered.length === 0) {
  15685. if (emptyState) emptyState.classList.remove('hidden');
  15686. return;
  15687. }
  15688. if (emptyState) emptyState.classList.add('hidden');
  15689. const currentAuthUser = state.currentUser?.username || '';
  15690. filtered.forEach(u => {
  15691. const isSelf = u.username === currentAuthUser;
  15692. const isFull = u.role === 'full';
  15693. const isWrite = u.role === 'write';
  15694. 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>`;
  15695. if (isFull) {
  15696. 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>`;
  15697. } else if (isWrite) {
  15698. 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>`;
  15699. }
  15700. const statusBadge = u.disabled
  15701. ? `<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>`
  15702. : `<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>`;
  15703. let lastLoginText = 'Never';
  15704. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15705. const dt = new Date(u.last_login_at);
  15706. lastLoginText = dt.toLocaleString();
  15707. }
  15708. const initials = u.username.slice(0, 2).toUpperCase();
  15709. const tr = document.createElement('tr');
  15710. tr.className = 'hover:bg-slate-800/40 transition group';
  15711. tr.innerHTML = `
  15712. <td class="py-3 px-4">
  15713. <div class="flex items-center gap-3">
  15714. <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">
  15715. ${initials}
  15716. </div>
  15717. <div>
  15718. <div class="font-bold text-white text-xs flex items-center gap-2">
  15719. <span>${escapeHtml(u.username)}</span>
  15720. ${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>' : ''}
  15721. </div>
  15722. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15723. </div>
  15724. </div>
  15725. </td>
  15726. <td class="py-3 px-4 font-sans">
  15727. ${roleBadge}
  15728. </td>
  15729. <td class="py-3 px-4 font-sans">
  15730. ${statusBadge}
  15731. </td>
  15732. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15733. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15734. </td>
  15735. <td class="py-3 px-4 text-slate-400 text-xs">
  15736. ${lastLoginText}
  15737. </td>
  15738. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15739. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15740. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15741. <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>
  15742. </button>
  15743. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15744. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15745. <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>
  15746. </button>
  15747. ${!isSelf ? `
  15748. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15749. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15750. <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>
  15751. </button>
  15752. ` : ''}
  15753. </td>
  15754. `;
  15755. tbody.appendChild(tr);
  15756. });
  15757. }
  15758. function openAddUserModal() {
  15759. document.getElementById('user-add-username').value = '';
  15760. document.getElementById('user-add-password').value = '';
  15761. document.getElementById('user-add-confirm').value = '';
  15762. document.getElementById('user-add-role').value = 'full';
  15763. document.getElementById('user-add-comment').value = '';
  15764. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15765. document.getElementById('user-add-username')?.focus();
  15766. }
  15767. function closeAddUserModal() {
  15768. document.getElementById('modal-add-user')?.classList.add('hidden');
  15769. }
  15770. async function submitAddUser(event) {
  15771. event.preventDefault();
  15772. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15773. const password = document.getElementById('user-add-password')?.value || '';
  15774. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15775. const role = document.getElementById('user-add-role')?.value || 'full';
  15776. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15777. if (password !== confirm) {
  15778. showToast('Validation Error', 'Passwords do not match', 'warning');
  15779. return;
  15780. }
  15781. if (password.length < 4) {
  15782. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15783. return;
  15784. }
  15785. try {
  15786. const res = await fetch(`${API_BASE}/users`, {
  15787. method: 'POST',
  15788. headers: { 'Content-Type': 'application/json' },
  15789. body: JSON.stringify({ username, password, role, comment })
  15790. });
  15791. const data = await res.json();
  15792. if (res.ok) {
  15793. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15794. closeAddUserModal();
  15795. loadUsers(false);
  15796. } else {
  15797. showToast('Error', data.message || 'Failed to create user', 'error');
  15798. }
  15799. } catch (err) {
  15800. showToast('Error', err.message, 'error');
  15801. }
  15802. }
  15803. function openEditUserModal(username) {
  15804. const user = (state.users || []).find(u => u.username === username);
  15805. if (!user) return;
  15806. document.getElementById('user-edit-username').value = user.username;
  15807. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15808. document.getElementById('user-edit-role').value = user.role || 'read';
  15809. document.getElementById('user-edit-comment').value = user.comment || '';
  15810. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15811. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15812. }
  15813. function closeEditUserModal() {
  15814. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15815. }
  15816. async function submitEditUser(event) {
  15817. event.preventDefault();
  15818. const username = document.getElementById('user-edit-username')?.value;
  15819. const role = document.getElementById('user-edit-role')?.value || 'read';
  15820. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15821. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15822. try {
  15823. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15824. method: 'PUT',
  15825. headers: { 'Content-Type': 'application/json' },
  15826. body: JSON.stringify({ role, comment, disabled })
  15827. });
  15828. const data = await res.json();
  15829. if (res.ok) {
  15830. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15831. closeEditUserModal();
  15832. loadUsers(false);
  15833. // If updated own role/disabled status, refresh self profile
  15834. if (username === state.currentUser?.username) {
  15835. checkAuthStatus();
  15836. }
  15837. } else {
  15838. showToast('Error', data.message || 'Failed to update user', 'error');
  15839. }
  15840. } catch (err) {
  15841. showToast('Error', err.message, 'error');
  15842. }
  15843. }
  15844. function openAdminResetPasswordModal(username) {
  15845. document.getElementById('admin-reset-username').value = username;
  15846. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15847. document.getElementById('admin-reset-new-pw').value = '';
  15848. document.getElementById('admin-reset-confirm-pw').value = '';
  15849. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15850. document.getElementById('admin-reset-new-pw')?.focus();
  15851. }
  15852. function closeAdminResetPasswordModal() {
  15853. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15854. }
  15855. async function submitAdminResetPassword(event) {
  15856. event.preventDefault();
  15857. const username = document.getElementById('admin-reset-username')?.value;
  15858. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15859. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15860. if (newPassword !== confirm) {
  15861. showToast('Validation Error', 'Passwords do not match', 'warning');
  15862. return;
  15863. }
  15864. if (newPassword.length < 4) {
  15865. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15866. return;
  15867. }
  15868. try {
  15869. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15870. method: 'POST',
  15871. headers: { 'Content-Type': 'application/json' },
  15872. body: JSON.stringify({ new_password: newPassword })
  15873. });
  15874. const data = await res.json();
  15875. if (res.ok) {
  15876. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15877. closeAdminResetPasswordModal();
  15878. } else {
  15879. showToast('Error', data.message || 'Failed to reset password', 'error');
  15880. }
  15881. } catch (err) {
  15882. showToast('Error', err.message, 'error');
  15883. }
  15884. }
  15885. async function deleteUser(username) {
  15886. if (username === state.currentUser?.username) {
  15887. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15888. return;
  15889. }
  15890. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15891. return;
  15892. }
  15893. try {
  15894. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15895. method: 'DELETE'
  15896. });
  15897. const data = await res.json();
  15898. if (res.ok) {
  15899. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15900. loadUsers(false);
  15901. } else {
  15902. showToast('Error', data.message || 'Failed to delete user', 'error');
  15903. }
  15904. } catch (err) {
  15905. showToast('Error', err.message, 'error');
  15906. }
  15907. }
  15908. function openSelfPasswordModal() {
  15909. document.getElementById('self-current-password').value = '';
  15910. document.getElementById('self-new-password').value = '';
  15911. document.getElementById('self-confirm-password').value = '';
  15912. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15913. document.getElementById('self-current-password')?.focus();
  15914. }
  15915. function closeSelfPasswordModal() {
  15916. document.getElementById('modal-self-password')?.classList.add('hidden');
  15917. }
  15918. async function submitSelfPassword(event) {
  15919. event.preventDefault();
  15920. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15921. const newPassword = document.getElementById('self-new-password')?.value || '';
  15922. const confirm = document.getElementById('self-confirm-password')?.value || '';
  15923. if (newPassword !== confirm) {
  15924. showToast('Validation Error', 'New passwords do not match', 'warning');
  15925. return;
  15926. }
  15927. if (newPassword.length < 4) {
  15928. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15929. return;
  15930. }
  15931. try {
  15932. const res = await fetch(`${API_BASE}/auth/change-password`, {
  15933. method: 'POST',
  15934. headers: { 'Content-Type': 'application/json' },
  15935. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15936. });
  15937. const data = await res.json();
  15938. if (res.ok) {
  15939. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15940. closeSelfPasswordModal();
  15941. } else {
  15942. showToast('Error', data.message || 'Failed to change password', 'error');
  15943. }
  15944. } catch (err) {
  15945. showToast('Error', err.message, 'error');
  15946. }
  15947. }
  15948. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15949. state.services = [];
  15950. async function loadServices(manual = false) {
  15951. try {
  15952. const res = await fetch(`${API_BASE}/system/services`);
  15953. if (!res.ok) throw new Error('Failed to load services');
  15954. const data = await res.json();
  15955. state.services = data || [];
  15956. renderServicesTable();
  15957. updateCertificatesBadges();
  15958. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15959. } catch (err) {
  15960. if (manual) showToast('Error', err.message, 'error');
  15961. }
  15962. }
  15963. function renderServicesTable() {
  15964. const tbody = document.getElementById('services-table-body');
  15965. if (!tbody) return;
  15966. if (!state.services || state.services.length === 0) {
  15967. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15968. return;
  15969. }
  15970. tbody.innerHTML = state.services.map(s => {
  15971. const isOff = s.disabled;
  15972. const statusBadge = isOff
  15973. ? '<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>'
  15974. : '<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>';
  15975. const toggleBtn = isOff
  15976. ? `<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>`
  15977. : `<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>`;
  15978. let certBadge = '';
  15979. if (s.name === 'www-ssl') {
  15980. if (s.certificate) {
  15981. 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>`;
  15982. } else {
  15983. 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>`;
  15984. }
  15985. }
  15986. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15987. return `
  15988. <tr class="hover:bg-slate-800/40 transition">
  15989. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15990. <td class="py-3 px-4">
  15991. <div class="flex items-center gap-2">
  15992. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15993. <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">
  15994. <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>
  15995. </button>
  15996. </div>
  15997. </td>
  15998. <td class="py-3 px-4">${statusBadge}</td>
  15999. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16000. <td class="py-3 px-4 text-right">
  16001. <div class="flex items-center justify-end gap-2">
  16002. <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">
  16003. <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>
  16004. <span>Edit</span>
  16005. </button>
  16006. ${toggleBtn}
  16007. </div>
  16008. </td>
  16009. </tr>
  16010. `;
  16011. }).join('');
  16012. }
  16013. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16014. document.getElementById('modal-service-name').value = serviceName;
  16015. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16016. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16017. document.getElementById('modal-service-port').value = currentPort;
  16018. const hintEl = document.getElementById('modal-service-port-hint');
  16019. const warnEl = document.getElementById('modal-service-warning');
  16020. const certGroup = document.getElementById('modal-service-cert-group');
  16021. const certSelect = document.getElementById('modal-service-cert-select');
  16022. if (serviceName === 'www') {
  16023. hintEl.textContent = 'Default HTTP web port: 80';
  16024. warnEl.classList.remove('hidden');
  16025. certGroup.classList.add('hidden');
  16026. } else if (serviceName === 'www-ssl') {
  16027. hintEl.textContent = 'Default HTTPS web port: 443';
  16028. warnEl.classList.remove('hidden');
  16029. certGroup.classList.remove('hidden');
  16030. const populateCertOptions = (certs) => {
  16031. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16032. (certs || []).forEach(c => {
  16033. const opt = document.createElement('option');
  16034. opt.value = c.name;
  16035. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16036. if (c.name === currentCert) opt.selected = true;
  16037. certSelect.appendChild(opt);
  16038. });
  16039. };
  16040. if (state.certificates && state.certificates.length > 0) {
  16041. populateCertOptions(state.certificates);
  16042. } else {
  16043. loadCertificates(false).then(() => {
  16044. populateCertOptions(state.certificates);
  16045. });
  16046. }
  16047. } else if (serviceName === 'telnet') {
  16048. hintEl.textContent = 'Default Telnet console port: 8282';
  16049. warnEl.classList.add('hidden');
  16050. certGroup.classList.add('hidden');
  16051. } else if (serviceName === 'ssh') {
  16052. hintEl.textContent = 'Default SSH port: 2222';
  16053. warnEl.classList.add('hidden');
  16054. certGroup.classList.add('hidden');
  16055. } else {
  16056. hintEl.textContent = '';
  16057. warnEl.classList.add('hidden');
  16058. certGroup.classList.add('hidden');
  16059. }
  16060. const modal = document.getElementById('modal-service-edit');
  16061. modal.classList.remove('hidden');
  16062. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16063. }
  16064. function closeEditServiceModal() {
  16065. const modal = document.getElementById('modal-service-edit');
  16066. if (modal) modal.classList.add('hidden');
  16067. }
  16068. async function submitSaveServicePort(event) {
  16069. event.preventDefault();
  16070. const name = document.getElementById('modal-service-name').value;
  16071. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16072. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16073. if (isNaN(port) || port < 1 || port > 65535) {
  16074. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16075. return;
  16076. }
  16077. const certSelect = document.getElementById('modal-service-cert-select');
  16078. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16079. try {
  16080. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16081. method: 'POST',
  16082. headers: { 'Content-Type': 'application/json' },
  16083. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16084. });
  16085. if (!res.ok) {
  16086. const errData = await res.json();
  16087. throw new Error(errData.message || 'Failed to update service settings');
  16088. }
  16089. closeEditServiceModal();
  16090. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16091. await loadServices();
  16092. } catch (err) {
  16093. showToast('Error', err.message, 'error');
  16094. }
  16095. }
  16096. async function toggleServiceState(serviceName, newDisabled) {
  16097. if (serviceName === 'www' && newDisabled) {
  16098. 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?")) {
  16099. return;
  16100. }
  16101. }
  16102. if (serviceName === 'www-ssl' && !newDisabled) {
  16103. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16104. if (!sslSvc || !sslSvc.certificate) {
  16105. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16106. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16107. return;
  16108. }
  16109. }
  16110. try {
  16111. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16112. method: 'POST',
  16113. headers: { 'Content-Type': 'application/json' },
  16114. body: JSON.stringify({ disabled: newDisabled })
  16115. });
  16116. if (!res.ok) {
  16117. const errData = await res.json();
  16118. throw new Error(errData.message || 'Failed to update service');
  16119. }
  16120. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16121. await loadServices();
  16122. } catch (err) {
  16123. showToast('Error', err.message, 'error');
  16124. }
  16125. }
  16126. // ==================== SYSTEM LOGS (/log) ====================
  16127. state.logs = [];
  16128. let logsTimer = null;
  16129. async function loadLogs(manual = false) {
  16130. const limitEl = document.getElementById('logs-limit-select');
  16131. const limit = limitEl ? limitEl.value : '100';
  16132. try {
  16133. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16134. if (!res.ok) throw new Error('Failed to load logs');
  16135. const data = await res.json();
  16136. state.logs = data.logs || [];
  16137. renderLogsTable();
  16138. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16139. } catch (err) {
  16140. if (manual) showToast('Error', err.message, 'error');
  16141. }
  16142. // Setup auto-refresh if enabled and on logs tab
  16143. if (!logsTimer && state.currentUser) {
  16144. logsTimer = setInterval(() => {
  16145. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16146. const auto = document.getElementById('logs-auto-refresh');
  16147. if (auto && auto.checked) {
  16148. loadLogs(false);
  16149. }
  16150. }
  16151. }, 3000);
  16152. }
  16153. }
  16154. function renderLogsTable() {
  16155. const tbody = document.getElementById('logs-table-body');
  16156. if (!tbody) return;
  16157. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16158. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16159. const filtered = state.logs.filter(entry => {
  16160. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16161. return false;
  16162. }
  16163. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16164. return false;
  16165. }
  16166. return true;
  16167. });
  16168. if (filtered.length === 0) {
  16169. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16170. return;
  16171. }
  16172. tbody.innerHTML = filtered.map(l => {
  16173. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16174. const topLower = l.topics.toLowerCase();
  16175. if (topLower.includes('auth')) {
  16176. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16177. } else if (topLower.includes('dhcp')) {
  16178. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16179. } else if (topLower.includes('route')) {
  16180. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16181. } else if (topLower.includes('firewall')) {
  16182. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16183. } else if (topLower.includes('error')) {
  16184. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16185. } else if (topLower.includes('system')) {
  16186. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16187. }
  16188. const d = new Date(l.time);
  16189. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16190. return `
  16191. <tr class="hover:bg-slate-800/40 transition">
  16192. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16193. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16194. <td class="py-2 px-3 whitespace-nowrap">
  16195. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16196. </td>
  16197. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16198. </tr>
  16199. `;
  16200. }).join('');
  16201. }
  16202. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16203. state.certificates = [];
  16204. async function loadCertificates(manual = false) {
  16205. try {
  16206. const res = await fetch(`${API_BASE}/certificates`);
  16207. if (!res.ok) throw new Error('Failed to load certificates');
  16208. state.certificates = await res.json() || [];
  16209. updateCertificatesBadges();
  16210. renderCertificatesTable();
  16211. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16212. } catch (err) {
  16213. if (manual) showToast('Error', err.message, 'error');
  16214. }
  16215. }
  16216. function updateCertificatesBadges() {
  16217. const total = (state.certificates || []).length;
  16218. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16219. const bCount = document.getElementById('badge-certs-count');
  16220. if (bCount) bCount.innerText = total;
  16221. const kpiTotal = document.getElementById('kpi-certs-total');
  16222. if (kpiTotal) kpiTotal.innerText = total;
  16223. const kpiCA = document.getElementById('kpi-certs-ca');
  16224. if (kpiCA) kpiCA.innerText = caCount;
  16225. const kpiHttps = document.getElementById('kpi-https-status');
  16226. if (kpiHttps) {
  16227. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16228. if (sslSvc) {
  16229. if (!sslSvc.disabled) {
  16230. 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>`;
  16231. } else {
  16232. 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>`;
  16233. }
  16234. }
  16235. }
  16236. }
  16237. function renderCertificatesTable() {
  16238. const tbody = document.getElementById('certs-table-body');
  16239. if (!tbody) return;
  16240. if (!state.certificates || state.certificates.length === 0) {
  16241. 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>';
  16242. return;
  16243. }
  16244. tbody.innerHTML = state.certificates.map(c => {
  16245. let typeBadge = '';
  16246. if (c.is_ca) {
  16247. 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>';
  16248. } else if (c.type === 'acme') {
  16249. 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>';
  16250. } else if (c.issuer && c.issuer !== c.common_name) {
  16251. 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>';
  16252. } else {
  16253. 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>';
  16254. }
  16255. const sansHtml = (c.sans && c.sans.length > 0)
  16256. ? 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('')
  16257. : '<span class="text-slate-500">-</span>';
  16258. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16259. let validStr = '-';
  16260. let validBadge = '';
  16261. if (validTo && !isNaN(validTo.getTime())) {
  16262. const now = new Date();
  16263. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16264. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16265. if (daysLeft < 0) {
  16266. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16267. } else if (daysLeft < 30) {
  16268. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16269. } else {
  16270. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16271. }
  16272. }
  16273. return `
  16274. <tr class="hover:bg-slate-800/40 transition">
  16275. <td class="py-3 px-4">${typeBadge}</td>
  16276. <td class="py-3 px-4">
  16277. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16278. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16279. </td>
  16280. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16281. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16282. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16283. <span>${validStr}</span> ${validBadge}
  16284. ${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>` : ''}
  16285. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16286. </td>
  16287. <td class="py-3 px-4 text-right whitespace-nowrap">
  16288. <div class="flex items-center justify-end gap-1.5">
  16289. <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">
  16290. <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>
  16291. <span>View</span>
  16292. </button>
  16293. <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">
  16294. <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>
  16295. </button>
  16296. </div>
  16297. </td>
  16298. </tr>
  16299. `;
  16300. }).join('');
  16301. }
  16302. // Create CA
  16303. function openCreateCAModal() {
  16304. document.getElementById('form-create-ca').reset();
  16305. document.getElementById('ca-days').value = '3650';
  16306. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16307. document.getElementById('ca-country').value = 'GR';
  16308. document.getElementById('ca-key-type').value = 'RSA-2048';
  16309. document.getElementById('modal-create-ca').classList.remove('hidden');
  16310. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16311. }
  16312. function closeCreateCAModal() {
  16313. document.getElementById('modal-create-ca').classList.add('hidden');
  16314. }
  16315. async function submitCreateCA(event) {
  16316. event.preventDefault();
  16317. const payload = {
  16318. name: document.getElementById('ca-name').value.trim(),
  16319. common_name: document.getElementById('ca-cn').value.trim(),
  16320. organization: document.getElementById('ca-org').value.trim(),
  16321. country: document.getElementById('ca-country').value.trim(),
  16322. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16323. key_type: document.getElementById('ca-key-type').value
  16324. };
  16325. try {
  16326. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16327. method: 'POST',
  16328. headers: { 'Content-Type': 'application/json' },
  16329. body: JSON.stringify(payload)
  16330. });
  16331. if (!res.ok) {
  16332. const errData = await res.json();
  16333. throw new Error(errData.message || 'Failed to create CA');
  16334. }
  16335. closeCreateCAModal();
  16336. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16337. await loadCertificates();
  16338. } catch (err) {
  16339. showToast('Error', err.message, 'error');
  16340. }
  16341. }
  16342. // Create Cert
  16343. function openCreateCertModal() {
  16344. document.getElementById('form-create-cert').reset();
  16345. document.getElementById('cert-days').value = '730';
  16346. document.getElementById('cert-key-type').value = 'RSA-2048';
  16347. const caSelect = document.getElementById('cert-ca-select');
  16348. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16349. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16350. const opt = document.createElement('option');
  16351. opt.value = ca.name;
  16352. opt.textContent = `${ca.name} (${ca.common_name})`;
  16353. caSelect.appendChild(opt);
  16354. });
  16355. document.getElementById('modal-create-cert').classList.remove('hidden');
  16356. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16357. }
  16358. function closeCreateCertModal() {
  16359. document.getElementById('modal-create-cert').classList.add('hidden');
  16360. }
  16361. async function submitCreateCert(event) {
  16362. event.preventDefault();
  16363. const rawSans = document.getElementById('cert-sans').value;
  16364. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16365. const caName = document.getElementById('cert-ca-select').value;
  16366. const payload = {
  16367. name: document.getElementById('cert-name').value.trim(),
  16368. common_name: document.getElementById('cert-cn').value.trim(),
  16369. ca_name: caName,
  16370. sans: sansList,
  16371. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16372. key_type: document.getElementById('cert-key-type').value,
  16373. is_server: true
  16374. };
  16375. try {
  16376. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16377. method: 'POST',
  16378. headers: { 'Content-Type': 'application/json' },
  16379. body: JSON.stringify(payload)
  16380. });
  16381. if (!res.ok) {
  16382. const errData = await res.json();
  16383. throw new Error(errData.message || 'Failed to issue certificate');
  16384. }
  16385. closeCreateCertModal();
  16386. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16387. await loadCertificates();
  16388. } catch (err) {
  16389. showToast('Error', err.message, 'error');
  16390. }
  16391. }
  16392. // Let's Encrypt
  16393. function openLetsEncryptModal() {
  16394. document.getElementById('form-letsencrypt').reset();
  16395. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16396. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16397. }
  16398. function closeLetsEncryptModal() {
  16399. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16400. }
  16401. async function submitLetsEncrypt(event) {
  16402. event.preventDefault();
  16403. const domain = document.getElementById('le-domain').value.trim();
  16404. const email = document.getElementById('le-email').value.trim();
  16405. let name = document.getElementById('le-name').value.trim();
  16406. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16407. const staging = document.getElementById('le-staging').checked;
  16408. const btn = document.getElementById('btn-submit-letsencrypt');
  16409. const origBtnHtml = btn.innerHTML;
  16410. btn.disabled = true;
  16411. 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>`;
  16412. try {
  16413. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16414. method: 'POST',
  16415. headers: { 'Content-Type': 'application/json' },
  16416. body: JSON.stringify({
  16417. name: name,
  16418. domain: domain,
  16419. email: email,
  16420. staging: staging
  16421. })
  16422. });
  16423. if (!res.ok) {
  16424. const errData = await res.json();
  16425. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16426. }
  16427. closeLetsEncryptModal();
  16428. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16429. await loadCertificates();
  16430. } catch (err) {
  16431. showToast('Let\'s Encrypt Error', err.message, 'error');
  16432. } finally {
  16433. btn.disabled = false;
  16434. btn.innerHTML = origBtnHtml;
  16435. }
  16436. }
  16437. // Import Cert
  16438. function openImportCertModal() {
  16439. document.getElementById('form-import-cert').reset();
  16440. document.getElementById('modal-import-cert').classList.remove('hidden');
  16441. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16442. }
  16443. function closeImportCertModal() {
  16444. document.getElementById('modal-import-cert').classList.add('hidden');
  16445. }
  16446. async function submitImportCert(event) {
  16447. event.preventDefault();
  16448. const payload = {
  16449. name: document.getElementById('import-cert-name').value.trim(),
  16450. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16451. key_pem: document.getElementById('import-key-pem').value.trim()
  16452. };
  16453. try {
  16454. const res = await fetch(`${API_BASE}/certificates/import`, {
  16455. method: 'POST',
  16456. headers: { 'Content-Type': 'application/json' },
  16457. body: JSON.stringify(payload)
  16458. });
  16459. if (!res.ok) {
  16460. const errData = await res.json();
  16461. throw new Error(errData.message || 'Failed to import certificate');
  16462. }
  16463. closeImportCertModal();
  16464. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16465. await loadCertificates();
  16466. } catch (err) {
  16467. showToast('Error', err.message, 'error');
  16468. }
  16469. }
  16470. // View / Export Modal
  16471. async function openViewCertModal(name) {
  16472. const c = (state.certificates || []).find(x => x.name === name);
  16473. if (!c) return;
  16474. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16475. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16476. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16477. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16478. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16479. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16480. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16481. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16482. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16483. document.getElementById('modal-view-cert').classList.remove('hidden');
  16484. try {
  16485. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16486. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16487. const data = await res.json();
  16488. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16489. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16490. } catch (err) {
  16491. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16492. document.getElementById('view-key-pem-text').value = '';
  16493. }
  16494. }
  16495. function closeViewCertModal() {
  16496. document.getElementById('modal-view-cert').classList.add('hidden');
  16497. }
  16498. function copyCertPEM() {
  16499. const text = document.getElementById('view-cert-pem-text').value;
  16500. if (!text) return;
  16501. navigator.clipboard.writeText(text).then(() => {
  16502. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16503. }).catch(() => {
  16504. showToast('Error', 'Failed to copy to clipboard', 'error');
  16505. });
  16506. }
  16507. function copyKeyPEM() {
  16508. const text = document.getElementById('view-key-pem-text').value;
  16509. if (!text) return;
  16510. navigator.clipboard.writeText(text).then(() => {
  16511. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16512. }).catch(() => {
  16513. showToast('Error', 'Failed to copy to clipboard', 'error');
  16514. });
  16515. }
  16516. async function deleteCertificate(name) {
  16517. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16518. return;
  16519. }
  16520. try {
  16521. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16522. method: 'DELETE'
  16523. });
  16524. if (!res.ok) {
  16525. const errData = await res.json();
  16526. throw new Error(errData.message || 'Failed to delete certificate');
  16527. }
  16528. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16529. await loadCertificates();
  16530. } catch (err) {
  16531. showToast('Error', err.message, 'error');
  16532. }
  16533. }
  16534. // Refresh immediately when returning to a backgrounded controller tab.
  16535. document.addEventListener('visibilitychange', () => {
  16536. if (!state.currentUser) return;
  16537. if (document.hidden) {
  16538. if (trafficEventSource) trafficEventSource.close();
  16539. trafficEventSource = null;
  16540. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16541. trafficPollFallback = null;
  16542. } else {
  16543. fetchData(false);
  16544. initLiveTrafficStream();
  16545. if (state.activeTab === 'bwtest') loadBwTestView();
  16546. }
  16547. });
  16548. async function loadUpdateStatus(populate = true) {
  16549. try {
  16550. const res = await fetch(`${API_BASE}/update/status`);
  16551. if (!res.ok) throw new Error(await responseError(res));
  16552. const data = await res.json();
  16553. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16554. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16555. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16556. document.getElementById('update-state').textContent = data.state || 'idle';
  16557. document.getElementById('update-log').textContent = data.log || '';
  16558. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16559. }
  16560. async function saveUpdateConfig() {
  16561. try {
  16562. const repository = document.getElementById('update-repository').value.trim();
  16563. const branch = 'master';
  16564. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16565. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16566. if (!res.ok) throw new Error(await responseError(res));
  16567. document.getElementById('update-install-button').disabled = true;
  16568. document.getElementById('update-available').textContent = '—';
  16569. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16570. await loadUpdateStatus(false);
  16571. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16572. }
  16573. async function checkUpdate() {
  16574. try {
  16575. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16576. if (!res.ok) throw new Error(await responseError(res));
  16577. const data = await res.json();
  16578. document.getElementById('update-available').textContent = data.available_version;
  16579. document.getElementById('update-install-button').disabled = !data.update_available;
  16580. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16581. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16582. }
  16583. async function startUpdate(action) {
  16584. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16585. try {
  16586. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16587. if (!res.ok) throw new Error(await responseError(res));
  16588. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16589. await loadUpdateStatus(false);
  16590. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16591. }
  16592. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16593. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16594. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16595. function safeFirewallRow(row) {
  16596. const result = {...row};
  16597. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16598. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16599. return result;
  16600. }
  16601. function setFirewallDays(prefix, days) {
  16602. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16603. 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); }
  16604. }
  16605. function getFirewallDays(prefix) {
  16606. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16607. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16608. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16609. return selected.join(',');
  16610. }
  16611. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16612. const id = document.getElementById(kind+'-modal-id')?.value;
  16613. if (!id) { resetDisplay(); return; }
  16614. try {
  16615. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16616. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16617. resetDisplay(); await loadFirewall(false);
  16618. } catch(error) { showToast('Error', error.message, 'error'); }
  16619. }
  16620. function reviewLegacyFirewallSettings(kind, id) {
  16621. if (!id) return true;
  16622. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16623. const rule = (rows || []).find(r => r.id === id);
  16624. if (!rule) return true;
  16625. 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'];
  16626. const present = unsupported.filter(key => rule[key]);
  16627. if (!present.length) return true;
  16628. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16629. }
  16630. function refreshFirewallRejectTypes() {
  16631. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16632. const old=select.value;
  16633. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16634. 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'];
  16635. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16636. if(types.includes(old))select.value=old;
  16637. }
  16638. function setFirewallActionSelection(kind, value) {
  16639. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16640. if(!Array.from(select.options).some(option=>option.value===value)) {
  16641. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16642. }
  16643. select.value=value;
  16644. }
  16645. // ==========================================
  16646. // REVERSE PROXY & APPLICATION GATEWAY
  16647. // ==========================================
  16648. state.proxyRules = [];
  16649. state.proxyConfig = null;
  16650. async function loadReverseProxy(manual = false) {
  16651. try {
  16652. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16653. fetch(`${API_BASE}/proxy/config`),
  16654. fetch(`${API_BASE}/proxy/rules`),
  16655. fetch(`${API_BASE}/certificates`).catch(() => null)
  16656. ]);
  16657. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16658. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16659. state.proxyConfig = await cfgRes.json();
  16660. state.proxyRules = await rulesRes.json() || [];
  16661. if (certsRes && certsRes.ok) {
  16662. state.certificates = await certsRes.json() || [];
  16663. }
  16664. renderProxyRules(state.proxyRules);
  16665. updateProxyMetrics();
  16666. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16667. } catch (err) {
  16668. console.error('loadReverseProxy error:', err);
  16669. if (manual) showToast('Error', err.message, 'error');
  16670. }
  16671. }
  16672. function updateProxyMetrics() {
  16673. const badge = document.getElementById('badge-proxy-count');
  16674. if (badge) badge.textContent = (state.proxyRules || []).length;
  16675. const metricRules = document.getElementById('proxy-metric-rules');
  16676. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16677. const cfg = state.proxyConfig;
  16678. const statusEl = document.getElementById('proxy-metric-status');
  16679. const portsEl = document.getElementById('proxy-metric-ports');
  16680. if (cfg) {
  16681. if (statusEl) {
  16682. if (cfg.enabled) {
  16683. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16684. } else {
  16685. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16686. }
  16687. }
  16688. if (portsEl) {
  16689. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16690. }
  16691. }
  16692. let totalRequests = 0;
  16693. const certSet = new Set();
  16694. (state.proxyRules || []).forEach(r => {
  16695. totalRequests += (r.stats && r.stats.requests) || 0;
  16696. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16697. });
  16698. const metricRequests = document.getElementById('proxy-metric-requests');
  16699. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16700. const metricCerts = document.getElementById('proxy-metric-certs');
  16701. if (metricCerts) metricCerts.textContent = certSet.size;
  16702. }
  16703. function renderProxyRules(rules) {
  16704. const tbody = document.getElementById('proxy-rules-table-body');
  16705. if (!tbody) return;
  16706. if (!rules || rules.length === 0) {
  16707. 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>';
  16708. return;
  16709. }
  16710. tbody.innerHTML = rules.map(r => {
  16711. const isEnabled = r.enabled !== false;
  16712. 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>';
  16713. 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>`;
  16714. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16715. 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>';
  16716. 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>';
  16717. 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>` : '';
  16718. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16719. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16720. return `
  16721. <tr class="hover:bg-slate-800/40 transition">
  16722. <td class="py-3 px-4">
  16723. <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'}">
  16724. <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>
  16725. </button>
  16726. </td>
  16727. <td class="py-3 px-4">
  16728. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16729. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16730. </td>
  16731. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16732. ${domainsStr}
  16733. </td>
  16734. <td class="py-3 px-4">
  16735. ${pathBadge}
  16736. </td>
  16737. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16738. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16739. </td>
  16740. <td class="py-3 px-4 whitespace-nowrap">
  16741. ${protoBadge}${certBadge}
  16742. </td>
  16743. <td class="py-3 px-4 font-mono">
  16744. ${stripBadge}
  16745. </td>
  16746. <td class="py-3 px-4 font-mono text-slate-300">
  16747. ${requests}
  16748. </td>
  16749. <td class="py-3 px-4 text-right whitespace-nowrap">
  16750. <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>
  16751. <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>
  16752. </td>
  16753. </tr>
  16754. `;
  16755. }).join('');
  16756. }
  16757. function populateProxyCertDropdown(selectedVal = '') {
  16758. const select = document.getElementById('proxy-rule-cert');
  16759. if (!select) return;
  16760. const certs = state.certificates || [];
  16761. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16762. certs.filter(c => !c.is_ca).forEach(c => {
  16763. const opt = document.createElement('option');
  16764. opt.value = c.name;
  16765. const cn = c.common_name ? ` (${c.common_name})` : '';
  16766. opt.textContent = `${c.name}${cn}`;
  16767. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16768. opt.selected = true;
  16769. }
  16770. select.appendChild(opt);
  16771. });
  16772. }
  16773. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16774. const select = document.getElementById('proxy-cfg-default-cert');
  16775. if (!select) return;
  16776. const certs = state.certificates || [];
  16777. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16778. certs.filter(c => !c.is_ca).forEach(c => {
  16779. const opt = document.createElement('option');
  16780. opt.value = c.name;
  16781. const cn = c.common_name ? ` (${c.common_name})` : '';
  16782. opt.textContent = `${c.name}${cn}`;
  16783. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16784. opt.selected = true;
  16785. }
  16786. select.appendChild(opt);
  16787. });
  16788. }
  16789. function onProxyProtoChange() {
  16790. const proto = document.getElementById('proxy-rule-proto')?.value;
  16791. const certSelect = document.getElementById('proxy-rule-cert');
  16792. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16793. if (proto === 'http') {
  16794. if (certSelect) certSelect.disabled = true;
  16795. if (redirectCheck) redirectCheck.disabled = true;
  16796. } else {
  16797. if (certSelect) certSelect.disabled = false;
  16798. if (redirectCheck) redirectCheck.disabled = false;
  16799. }
  16800. }
  16801. function openAddProxyRuleModal() {
  16802. const modal = document.getElementById('modal-proxy-rule');
  16803. if (!modal) return;
  16804. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16805. <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>
  16806. <span>Add Reverse Proxy Rule</span>
  16807. `;
  16808. document.getElementById('proxy-rule-id').value = '';
  16809. document.getElementById('proxy-rule-name').value = '';
  16810. document.getElementById('proxy-rule-domains').value = '';
  16811. document.getElementById('proxy-rule-path').value = '/';
  16812. document.getElementById('proxy-rule-target').value = '';
  16813. document.getElementById('proxy-rule-proto').value = 'both';
  16814. document.getElementById('proxy-rule-strip-path').checked = false;
  16815. document.getElementById('proxy-rule-http-to-https').checked = false;
  16816. document.getElementById('proxy-rule-preserve-host').checked = false;
  16817. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16818. document.getElementById('proxy-rule-enabled').checked = true;
  16819. document.getElementById('proxy-rule-comment').value = '';
  16820. populateProxyCertDropdown('');
  16821. onProxyProtoChange();
  16822. modal.classList.remove('hidden');
  16823. }
  16824. function openEditProxyRuleModal(id) {
  16825. const modal = document.getElementById('modal-proxy-rule');
  16826. if (!modal) return;
  16827. const rule = (state.proxyRules || []).find(r => r.id === id);
  16828. if (!rule) {
  16829. showToast('Error', 'Rule not found', 'error');
  16830. return;
  16831. }
  16832. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16833. <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>
  16834. <span>Edit Reverse Proxy Rule</span>
  16835. `;
  16836. document.getElementById('proxy-rule-id').value = rule.id || '';
  16837. document.getElementById('proxy-rule-name').value = rule.name || '';
  16838. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16839. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16840. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16841. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16842. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16843. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16844. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16845. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16846. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16847. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16848. populateProxyCertDropdown(rule.certificate || '');
  16849. onProxyProtoChange();
  16850. modal.classList.remove('hidden');
  16851. }
  16852. function closeProxyRuleModal() {
  16853. const modal = document.getElementById('modal-proxy-rule');
  16854. if (modal) modal.classList.add('hidden');
  16855. }
  16856. async function saveProxyRule(event) {
  16857. event.preventDefault();
  16858. const id = document.getElementById('proxy-rule-id').value;
  16859. const name = document.getElementById('proxy-rule-name').value.trim();
  16860. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16861. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16862. const target = document.getElementById('proxy-rule-target').value.trim();
  16863. const proto = document.getElementById('proxy-rule-proto').value;
  16864. const cert = document.getElementById('proxy-rule-cert').value;
  16865. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16866. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16867. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16868. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16869. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16870. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16871. let domains = [];
  16872. if (rawDomains && rawDomains !== '*') {
  16873. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16874. }
  16875. const payload = {
  16876. id: id || undefined,
  16877. name,
  16878. domains,
  16879. path: pathVal,
  16880. target_url: target,
  16881. protocol: proto,
  16882. certificate: cert,
  16883. strip_path: stripPath,
  16884. http_to_https: httpToHttps,
  16885. preserve_host: preserveHost,
  16886. insecure_tls: insecureTLS,
  16887. enabled,
  16888. comment
  16889. };
  16890. try {
  16891. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16892. const method = id ? 'PUT' : 'POST';
  16893. const res = await fetch(url, {
  16894. method,
  16895. headers: { 'Content-Type': 'application/json' },
  16896. body: JSON.stringify(payload)
  16897. });
  16898. if (!res.ok) {
  16899. const errData = await res.json().catch(() => ({}));
  16900. throw new Error(errData.message || 'Failed to save proxy rule');
  16901. }
  16902. closeProxyRuleModal();
  16903. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16904. await loadReverseProxy(false);
  16905. } catch (err) {
  16906. showToast('Error', err.message, 'error');
  16907. }
  16908. }
  16909. async function deleteProxyRule(id) {
  16910. const rule = (state.proxyRules || []).find(r => r.id === id);
  16911. const name = rule ? rule.name : id;
  16912. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  16913. return;
  16914. }
  16915. try {
  16916. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  16917. method: 'DELETE'
  16918. });
  16919. if (!res.ok) {
  16920. const errData = await res.json().catch(() => ({}));
  16921. throw new Error(errData.message || 'Failed to delete rule');
  16922. }
  16923. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  16924. await loadReverseProxy(false);
  16925. } catch (err) {
  16926. showToast('Error', err.message, 'error');
  16927. }
  16928. }
  16929. async function toggleProxyRuleState(id, currentState) {
  16930. try {
  16931. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  16932. method: 'POST',
  16933. headers: { 'Content-Type': 'application/json' },
  16934. body: JSON.stringify({ enabled: !currentState })
  16935. });
  16936. if (!res.ok) {
  16937. const errData = await res.json().catch(() => ({}));
  16938. throw new Error(errData.message || 'Failed to toggle rule state');
  16939. }
  16940. await loadReverseProxy(false);
  16941. } catch (err) {
  16942. showToast('Error', err.message, 'error');
  16943. }
  16944. }
  16945. function openProxyConfigModal() {
  16946. const modal = document.getElementById('modal-proxy-config');
  16947. if (!modal) return;
  16948. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  16949. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  16950. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  16951. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  16952. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  16953. modal.classList.remove('hidden');
  16954. }
  16955. function closeProxyConfigModal() {
  16956. const modal = document.getElementById('modal-proxy-config');
  16957. if (modal) modal.classList.add('hidden');
  16958. }
  16959. async function saveProxyConfig(event) {
  16960. event.preventDefault();
  16961. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  16962. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  16963. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  16964. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  16965. const payload = {
  16966. enabled,
  16967. http_port: httpPort,
  16968. https_port: httpsPort,
  16969. default_cert: defaultCert
  16970. };
  16971. try {
  16972. const res = await fetch(`${API_BASE}/proxy/config`, {
  16973. method: 'POST',
  16974. headers: { 'Content-Type': 'application/json' },
  16975. body: JSON.stringify(payload)
  16976. });
  16977. if (!res.ok) {
  16978. const errData = await res.json().catch(() => ({}));
  16979. throw new Error(errData.message || 'Failed to update proxy settings');
  16980. }
  16981. closeProxyConfigModal();
  16982. showToast('Success', 'Reverse proxy settings updated', 'success');
  16983. await loadReverseProxy(false);
  16984. } catch (err) {
  16985. showToast('Error', err.message, 'error');
  16986. }
  16987. }
  16988. // ==================== SD-WAN Controller ====================
  16989. async function loadSDWAN(manual = false) {
  16990. try {
  16991. const [groupsRes, telemetryRes] = await Promise.all([
  16992. fetch(`${API_BASE}/sdwan/groups`),
  16993. fetch(`${API_BASE}/sdwan/telemetry`)
  16994. ]);
  16995. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  16996. state.sdwanGroups = await groupsRes.json() || [];
  16997. if (telemetryRes.ok) {
  16998. state.sdwanTelemetry = await telemetryRes.json() || {};
  16999. }
  17000. renderSDWANGroups(state.sdwanGroups);
  17001. renderSDWANMembers(state.sdwanGroups);
  17002. updateSDWANMetrics(state.sdwanTelemetry);
  17003. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17004. } catch (err) {
  17005. console.error('loadSDWAN error:', err);
  17006. if (manual) showToast('Error', err.message, 'error');
  17007. }
  17008. }
  17009. function updateSDWANMetrics(telemetry) {
  17010. const groups = state.sdwanGroups || [];
  17011. const t = telemetry || {};
  17012. const badge = document.getElementById('badge-sdwan-count');
  17013. if (badge) badge.textContent = groups.length;
  17014. const metricGroups = document.getElementById('sdwan-metric-groups');
  17015. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17016. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17017. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17018. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17019. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17020. const metricDown = document.getElementById('sdwan-metric-down');
  17021. if (metricDown) metricDown.textContent = t.down_members || 0;
  17022. }
  17023. function renderSDWANGroups(groups) {
  17024. const tbody = document.getElementById('sdwan-groups-table-body');
  17025. if (!tbody) return;
  17026. if (!groups || groups.length === 0) {
  17027. 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>';
  17028. return;
  17029. }
  17030. tbody.innerHTML = groups.map(g => {
  17031. const isEnabled = g.disabled !== true;
  17032. const members = g.members || [];
  17033. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17034. // Build distribution progress bar
  17035. let distHtml = '';
  17036. if (members.length === 0) {
  17037. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17038. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17039. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17040. const segments = members.map((m, idx) => {
  17041. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17042. const col = colors[idx % colors.length];
  17043. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17044. }).join('');
  17045. const labels = members.map((m, idx) => {
  17046. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17047. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17048. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17049. }).join('');
  17050. distHtml = `
  17051. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17052. <div class="flex flex-wrap">${labels}</div>
  17053. `;
  17054. } else if (g.mode === 'lowest-latency') {
  17055. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17056. } else if (g.mode === 'lowest-loss') {
  17057. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17058. } else if (g.mode === 'failover') {
  17059. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17060. }
  17061. let modeBadge = '';
  17062. switch (g.mode) {
  17063. case 'weighted':
  17064. 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>';
  17065. break;
  17066. case 'pcc':
  17067. 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>';
  17068. break;
  17069. case 'lowest-latency':
  17070. 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>';
  17071. break;
  17072. case 'lowest-loss':
  17073. 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>';
  17074. break;
  17075. case 'failover':
  17076. 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>';
  17077. break;
  17078. default:
  17079. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17080. }
  17081. const autoNatBadge = g.auto_nat
  17082. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17083. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17084. return `
  17085. <tr class="hover:bg-slate-800/40 transition">
  17086. <td class="py-3 px-4">
  17087. <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'}">
  17088. <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>
  17089. </button>
  17090. </td>
  17091. <td class="py-3 px-4">
  17092. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17093. <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>
  17094. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17095. </div>
  17096. </td>
  17097. <td class="py-3 px-4">${modeBadge}</td>
  17098. <td class="py-3 px-4">${distHtml}</td>
  17099. <td class="py-3 px-4">
  17100. <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>
  17101. </td>
  17102. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17103. <td class="py-3 px-4">${autoNatBadge}</td>
  17104. <td class="py-3 px-4 text-right">
  17105. <div class="flex items-center justify-end gap-1.5">
  17106. <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">
  17107. <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>
  17108. </button>
  17109. <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">
  17110. <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>
  17111. </button>
  17112. <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">
  17113. <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>
  17114. </button>
  17115. </div>
  17116. </td>
  17117. </tr>
  17118. `;
  17119. }).join('');
  17120. }
  17121. function renderSDWANMembers(groups) {
  17122. const tbody = document.getElementById('sdwan-members-table-body');
  17123. if (!tbody) return;
  17124. const allMembers = [];
  17125. (groups || []).forEach(g => {
  17126. (g.members || []).forEach(m => {
  17127. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17128. });
  17129. });
  17130. if (allMembers.length === 0) {
  17131. 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>';
  17132. return;
  17133. }
  17134. tbody.innerHTML = allMembers.map(m => {
  17135. const isEnabled = m.disabled !== true;
  17136. 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>';
  17137. if (!isEnabled) {
  17138. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17139. } else if (m.status === 'DEGRADED') {
  17140. 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>';
  17141. } else if (m.status === 'DOWN') {
  17142. 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>';
  17143. }
  17144. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17145. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17146. return `
  17147. <tr class="hover:bg-slate-800/40 transition">
  17148. <td class="py-3 px-4">
  17149. <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'}">
  17150. <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>
  17151. </button>
  17152. </td>
  17153. <td class="py-3 px-4">
  17154. <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>
  17155. </td>
  17156. <td class="py-3 px-4">
  17157. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17158. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17159. </td>
  17160. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17161. <td class="py-3 px-4">
  17162. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17163. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17164. </td>
  17165. <td class="py-3 px-4">${statusBadge}</td>
  17166. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17167. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17168. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17169. </td>
  17170. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17171. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17172. </td>
  17173. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17174. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17175. </td>
  17176. <td class="py-3 px-4 text-right">
  17177. <div class="flex items-center justify-end gap-1.5">
  17178. <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">
  17179. <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>
  17180. </button>
  17181. <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">
  17182. <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>
  17183. </button>
  17184. </div>
  17185. </td>
  17186. </tr>
  17187. `;
  17188. }).join('');
  17189. }
  17190. // Modal handling for SD-WAN Groups
  17191. function openAddSDWANGroupModal() {
  17192. const modal = document.getElementById('modal-sdwan-group');
  17193. if (!modal) return;
  17194. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17195. document.getElementById('sdwan-group-id').value = '';
  17196. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17197. document.getElementById('sdwan-group-name').disabled = false;
  17198. document.getElementById('sdwan-group-mode').value = 'weighted';
  17199. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17200. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17201. document.getElementById('sdwan-group-probe-interval').value = 3;
  17202. document.getElementById('sdwan-group-auto-nat').checked = true;
  17203. document.getElementById('sdwan-group-comment').value = '';
  17204. modal.classList.remove('hidden');
  17205. }
  17206. function openEditSDWANGroupModal(id) {
  17207. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17208. if (!group) return;
  17209. const modal = document.getElementById('modal-sdwan-group');
  17210. if (!modal) return;
  17211. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17212. document.getElementById('sdwan-group-id').value = group.id;
  17213. document.getElementById('sdwan-group-name').value = group.name;
  17214. document.getElementById('sdwan-group-name').disabled = true;
  17215. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17216. if (group.mode === 'pcc') {
  17217. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17218. } else {
  17219. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17220. }
  17221. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17222. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17223. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17224. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17225. modal.classList.remove('hidden');
  17226. }
  17227. function closeSDWANGroupModal() {
  17228. const modal = document.getElementById('modal-sdwan-group');
  17229. if (modal) modal.classList.add('hidden');
  17230. }
  17231. function onSDWANModeChange() {
  17232. const mode = document.getElementById('sdwan-group-mode').value;
  17233. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17234. if (pccContainer) {
  17235. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17236. else pccContainer.classList.add('hidden');
  17237. }
  17238. }
  17239. async function saveSDWANGroup(event) {
  17240. event.preventDefault();
  17241. const id = document.getElementById('sdwan-group-id').value;
  17242. const name = document.getElementById('sdwan-group-name').value.trim();
  17243. const mode = document.getElementById('sdwan-group-mode').value;
  17244. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17245. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17246. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17247. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17248. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17249. const payload = {
  17250. id: id || undefined,
  17251. name,
  17252. mode,
  17253. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17254. probe_interval: probeInterval,
  17255. auto_nat: autoNAT,
  17256. comment,
  17257. members: existing ? existing.members : undefined
  17258. };
  17259. try {
  17260. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17261. method: 'POST',
  17262. headers: { 'Content-Type': 'application/json' },
  17263. body: JSON.stringify(payload)
  17264. });
  17265. if (!res.ok) {
  17266. const err = await res.json().catch(() => ({}));
  17267. throw new Error(err.message || 'Failed to save SD-WAN group');
  17268. }
  17269. closeSDWANGroupModal();
  17270. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17271. await loadSDWAN(false);
  17272. } catch (err) {
  17273. showToast('Error', err.message, 'error');
  17274. }
  17275. }
  17276. async function toggleSDWANGroupState(id, currentState) {
  17277. try {
  17278. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17279. method: 'POST',
  17280. headers: { 'Content-Type': 'application/json' },
  17281. body: JSON.stringify({ disabled: currentState })
  17282. });
  17283. if (!res.ok) throw new Error('Failed to update group state');
  17284. await loadSDWAN(false);
  17285. } catch (err) {
  17286. showToast('Error', err.message, 'error');
  17287. }
  17288. }
  17289. async function deleteSDWANGroup(id) {
  17290. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17291. const name = group ? group.name : id;
  17292. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17293. try {
  17294. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17295. method: 'DELETE'
  17296. });
  17297. if (!res.ok) {
  17298. const err = await res.json().catch(() => ({}));
  17299. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17300. }
  17301. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17302. await loadSDWAN(false);
  17303. } catch (err) {
  17304. showToast('Error', err.message, 'error');
  17305. }
  17306. }
  17307. // Modal handling for SD-WAN Members
  17308. function populateSDWANGroupsSelect(selectedId = '') {
  17309. const sel = document.getElementById('sdwan-member-group-id');
  17310. if (!sel) return;
  17311. sel.innerHTML = '';
  17312. (state.sdwanGroups || []).forEach(g => {
  17313. const opt = document.createElement('option');
  17314. opt.value = g.id;
  17315. opt.textContent = `${g.name} (${g.mode})`;
  17316. if (g.id === selectedId) opt.selected = true;
  17317. sel.appendChild(opt);
  17318. });
  17319. }
  17320. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17321. const sel = document.getElementById('sdwan-member-interface');
  17322. if (!sel) return;
  17323. sel.innerHTML = '';
  17324. (state.interfaces || []).forEach(i => {
  17325. const opt = document.createElement('option');
  17326. opt.value = i.name;
  17327. opt.textContent = `${i.name} (${i.role || i.type})`;
  17328. if (i.name === selectedVal) opt.selected = true;
  17329. sel.appendChild(opt);
  17330. });
  17331. }
  17332. function openAddSDWANMemberModal(defaultGroupId = null) {
  17333. const modal = document.getElementById('modal-sdwan-member');
  17334. if (!modal) return;
  17335. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17336. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17337. return;
  17338. }
  17339. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17340. document.getElementById('sdwan-member-id').value = '';
  17341. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17342. populateSDWANMemberInterfaceSelect();
  17343. document.getElementById('sdwan-member-gateway').value = '';
  17344. document.getElementById('sdwan-member-weight').value = 50;
  17345. document.getElementById('sdwan-member-priority').value = 1;
  17346. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17347. document.getElementById('sdwan-member-max-lat').value = 250;
  17348. document.getElementById('sdwan-member-max-loss').value = 20;
  17349. document.getElementById('sdwan-member-comment').value = '';
  17350. modal.classList.remove('hidden');
  17351. }
  17352. function openEditSDWANMemberModal(groupId, memberId) {
  17353. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17354. if (!group) return;
  17355. const member = (group.members || []).find(m => m.id === memberId);
  17356. if (!member) return;
  17357. const modal = document.getElementById('modal-sdwan-member');
  17358. if (!modal) return;
  17359. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17360. document.getElementById('sdwan-member-id').value = member.id;
  17361. populateSDWANGroupsSelect(group.id);
  17362. document.getElementById('sdwan-member-group-id').disabled = true;
  17363. populateSDWANMemberInterfaceSelect(member.interface);
  17364. document.getElementById('sdwan-member-interface').disabled = true;
  17365. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17366. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17367. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17368. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17369. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17370. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17371. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17372. modal.classList.remove('hidden');
  17373. }
  17374. function closeSDWANMemberModal() {
  17375. const modal = document.getElementById('modal-sdwan-member');
  17376. if (modal) {
  17377. document.getElementById('sdwan-member-group-id').disabled = false;
  17378. document.getElementById('sdwan-member-interface').disabled = false;
  17379. modal.classList.add('hidden');
  17380. }
  17381. }
  17382. async function saveSDWANMember(event) {
  17383. event.preventDefault();
  17384. const id = document.getElementById('sdwan-member-id').value;
  17385. let groupId = document.getElementById('sdwan-member-group-id').value;
  17386. let iface = document.getElementById('sdwan-member-interface').value;
  17387. // In edit mode with disabled selects, fallback to existing member data if needed
  17388. if (id) {
  17389. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17390. if (existingGroup) {
  17391. if (!groupId) groupId = existingGroup.id;
  17392. const mem = (existingGroup.members || []).find(m => m.id === id);
  17393. if (mem && !iface) iface = mem.interface;
  17394. }
  17395. }
  17396. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17397. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17398. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17399. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17400. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17401. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17402. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17403. const payload = {
  17404. id: id || undefined,
  17405. interface: iface,
  17406. gateway,
  17407. weight,
  17408. priority,
  17409. target_probe: targetProbe,
  17410. max_latency: maxLatency,
  17411. max_loss: maxLoss,
  17412. comment
  17413. };
  17414. try {
  17415. const method = id ? 'PUT' : 'POST';
  17416. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17417. method,
  17418. headers: { 'Content-Type': 'application/json' },
  17419. body: JSON.stringify(payload)
  17420. });
  17421. if (!res.ok) {
  17422. const err = await res.json().catch(() => ({}));
  17423. throw new Error(err.message || 'Failed to save member link');
  17424. }
  17425. closeSDWANMemberModal();
  17426. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17427. await loadSDWAN(false);
  17428. } catch (err) {
  17429. showToast('Error', err.message, 'error');
  17430. }
  17431. }
  17432. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17433. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17434. if (!group) return;
  17435. const member = (group.members || []).find(m => m.id === memberId);
  17436. if (!member) return;
  17437. const payload = {
  17438. ...member,
  17439. disabled: currentState
  17440. };
  17441. try {
  17442. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17443. method: 'PUT',
  17444. headers: { 'Content-Type': 'application/json' },
  17445. body: JSON.stringify(payload)
  17446. });
  17447. if (!res.ok) throw new Error('Failed to update member state');
  17448. await loadSDWAN(false);
  17449. } catch (err) {
  17450. showToast('Error', err.message, 'error');
  17451. }
  17452. }
  17453. async function deleteSDWANMember(groupId, iface) {
  17454. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17455. try {
  17456. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17457. method: 'DELETE'
  17458. });
  17459. if (!res.ok) {
  17460. const err = await res.json().catch(() => ({}));
  17461. throw new Error(err.message || 'Failed to remove member link');
  17462. }
  17463. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17464. await loadSDWAN(false);
  17465. } catch (err) {
  17466. showToast('Error', err.message, 'error');
  17467. }
  17468. }