app.js 664 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. initLiveTrafficStream();
  80. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  81. setInterval(() => {
  82. if (state.isPolling) {
  83. fetchData(false);
  84. }
  85. }, 5000);
  86. });
  87. let trafficEventSource = null;
  88. let trafficPollFallback = null;
  89. function initLiveTrafficStream() {
  90. if (trafficEventSource) {
  91. try { trafficEventSource.close(); } catch(e) {}
  92. trafficEventSource = null;
  93. }
  94. if (trafficPollFallback) {
  95. clearInterval(trafficPollFallback);
  96. trafficPollFallback = null;
  97. }
  98. if (window.EventSource) {
  99. try {
  100. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  101. trafficEventSource.onmessage = (event) => {
  102. try {
  103. const data = JSON.parse(event.data);
  104. updateLiveInterfaceTraffic(data);
  105. } catch (e) {
  106. console.error('Error parsing live traffic event:', e);
  107. }
  108. };
  109. trafficEventSource.onerror = () => {
  110. // Fallback polling if SSE disconnects
  111. if (!trafficPollFallback) {
  112. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  113. }
  114. };
  115. trafficEventSource.onopen = () => {
  116. if (trafficPollFallback) {
  117. clearInterval(trafficPollFallback);
  118. trafficPollFallback = null;
  119. }
  120. };
  121. return;
  122. } catch (e) {
  123. console.warn('EventSource failed, using 1s polling fallback:', e);
  124. }
  125. }
  126. // Fallback if EventSource is unavailable
  127. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  128. }
  129. async function pollLiveTrafficSnapshot() {
  130. try {
  131. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  132. if (res.ok) {
  133. const data = await res.json();
  134. updateLiveInterfaceTraffic(data);
  135. }
  136. } catch (e) {}
  137. }
  138. function updateLiveInterfaceTraffic(data) {
  139. if (!data || !data.interfaces) return;
  140. state.latestTraffic = data;
  141. // 1. Update Top & Dashboard Total Bandwidth Indicators
  142. const rxHuman = data.total_rx_human || '0 B/s';
  143. const txHuman = data.total_tx_human || '0 B/s';
  144. const statRx = document.getElementById('stat-traffic-rx');
  145. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  146. const statTx = document.getElementById('stat-traffic-tx');
  147. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  148. // 2. Update state.interfaces rates in-memory
  149. if (Array.isArray(state.interfaces)) {
  150. state.interfaces.forEach(i => {
  151. const live = data.interfaces[i.name];
  152. if (live) {
  153. i.rate = {
  154. rx_bytes_sec: live.rx_bytes_sec,
  155. tx_bytes_sec: live.tx_bytes_sec,
  156. rx_human: live.rx_human,
  157. tx_human: live.tx_human
  158. };
  159. i.stats = {
  160. rx_bytes: live.rx_bytes,
  161. tx_bytes: live.tx_bytes,
  162. rx_packets: live.rx_packets,
  163. tx_packets: live.tx_packets,
  164. rx_errors: live.rx_errors,
  165. tx_errors: live.tx_errors,
  166. rx_dropped: live.rx_dropped,
  167. tx_dropped: live.tx_dropped
  168. };
  169. }
  170. });
  171. }
  172. // 3. Update all live UI rate spans in-place (ZERO flicker)
  173. Object.keys(data.interfaces).forEach(name => {
  174. const live = data.interfaces[name];
  175. // Dashboard Port Matrix Card
  176. const cardRate = document.getElementById(`port-card-rate-${name}`);
  177. if (cardRate && cardRate.innerText !== live.rx_human) {
  178. cardRate.innerText = live.rx_human;
  179. }
  180. // Dashboard Quick Interfaces Table
  181. const quickRx = document.getElementById(`quick-rx-${name}`);
  182. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  183. const quickTx = document.getElementById(`quick-tx-${name}`);
  184. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  185. // Main Interfaces Tree Table
  186. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  187. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  188. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  189. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  190. // VLAN Sub-interfaces Table
  191. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  192. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  193. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  194. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  195. // VLAN Page Table
  196. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  197. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  198. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  199. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  200. });
  201. }
  202. // Navigation Handler
  203. function navigate(tabName) {
  204. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  205. navigate('bgp');
  206. return;
  207. }
  208. if (tabName === 'vlans') {
  209. navigate('interfaces');
  210. return;
  211. }
  212. state.activeTab = tabName;
  213. window.location.hash = tabName;
  214. // Update nav links styling
  215. document.querySelectorAll('.nav-link').forEach(link => {
  216. 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';
  217. });
  218. const activeNav = document.getElementById(`nav-${tabName}`);
  219. if (activeNav) {
  220. 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';
  221. }
  222. // Update page headers
  223. const titles = {
  224. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  225. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  226. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  227. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  228. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  229. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  230. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  231. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  232. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  233. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  234. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  235. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  236. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  237. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  238. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  239. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  240. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  241. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  242. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  243. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  244. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  245. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  246. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  247. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  248. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  249. };
  250. const header = titles[tabName] || titles.dashboard;
  251. const pTitle = document.getElementById('page-title');
  252. if (pTitle) pTitle.innerText = header.title;
  253. const pSub = document.getElementById('page-subtitle');
  254. if (pSub) pSub.innerText = header.sub;
  255. // Toggle sections dynamically for all section elements
  256. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  257. if (el.id === `section-${tabName}`) {
  258. el.classList.remove('hidden');
  259. } else {
  260. el.classList.add('hidden');
  261. }
  262. });
  263. if (tabName === 'interfaces') {
  264. loadRoles();
  265. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  266. else switchIfaceSubTab('tree');
  267. }
  268. if (tabName === 'bridge') loadBridge();
  269. if (tabName === 'firewall') loadFirewall();
  270. if (tabName === 'routes') loadRoutes();
  271. if (tabName === 'bgp') {
  272. loadDynamicRouting();
  273. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  274. }
  275. if (tabName === 'ospf') {
  276. loadDynamicRouting();
  277. switchOspfTab(state.activeOspfTab || 'instances');
  278. }
  279. if (tabName === 'routing-filters') loadDynamicRouting();
  280. if (tabName === 'dynamic-routing') loadDynamicRouting();
  281. if (tabName === 'ppp') loadPPP();
  282. if (tabName === 'eoip') loadEoIP();
  283. if (tabName === 'aerotun') loadAeroTUN();
  284. if (tabName === 'persistence') loadDebianConfig();
  285. if (tabName === 'pppoe') loadPPPoE();
  286. if (tabName === 'wireguard') loadWireGuard();
  287. if (tabName === 'ipsec') loadIPSec();
  288. if (tabName === 'l2tp') loadL2TP();
  289. if (tabName === 'pptp') loadPPTP();
  290. if (tabName === 'tools') loadToolsView();
  291. if (tabName === 'dhcp-client') loadDHCPClients();
  292. if (tabName === 'dhcp-server') loadDHCPServer();
  293. if (tabName === 'vrrp') loadVRRP();
  294. if (tabName === 'bwtest') loadBwTestView();
  295. if (tabName === 'settings') loadSettingsData();
  296. setTimeout(initTableSorting, 50);
  297. }
  298. // Fetch all core system, network and VPN telemetry
  299. async function fetchData(isManual = false) {
  300. const spinner = document.getElementById('refresh-spinner');
  301. if (isManual && spinner) spinner.classList.add('animate-spin');
  302. try {
  303. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  304. fetch(`${API_BASE}/system/status`),
  305. fetch(`${API_BASE}/interfaces`),
  306. fetch(`${API_BASE}/vlans`),
  307. fetch(`${API_BASE}/vpn/status`),
  308. fetch(`${API_BASE}/firewall/summary`),
  309. fetch(`${API_BASE}/routing/dynamic/summary`),
  310. fetch(`${API_BASE}/bridge/summary`),
  311. fetch(`${API_BASE}/dhcp/clients/summary`),
  312. fetch(`${API_BASE}/dhcp/clients`),
  313. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  314. fetch(`${API_BASE}/roles`).catch(() => null)
  315. ]);
  316. if (rolesRes && rolesRes.ok) {
  317. state.roles = await rolesRes.json();
  318. const countEl = document.getElementById('badge-roles-count');
  319. if (countEl) countEl.innerText = (state.roles || []).length;
  320. }
  321. if (vrrpSumRes && vrrpSumRes.ok) {
  322. state.vrrpSummary = await vrrpSumRes.json();
  323. renderVRRPSummary();
  324. }
  325. if (dhcpSumRes && dhcpSumRes.ok) {
  326. state.dhcpSummary = await dhcpSumRes.json();
  327. const bDhcp = document.getElementById('badge-dhcp-client-count');
  328. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  329. }
  330. if (dhcpClientsRes && dhcpClientsRes.ok) {
  331. state.dhcpClients = await dhcpClientsRes.json();
  332. }
  333. if (brSummaryRes.ok) {
  334. state.bridgeSummary = await brSummaryRes.json();
  335. const bBridge = document.getElementById('badge-bridge-count');
  336. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  337. const sBr = document.getElementById('bridge-stat-bridges');
  338. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  339. const sPorts = document.getElementById('bridge-stat-ports');
  340. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  341. const sHosts = document.getElementById('bridge-stat-hosts');
  342. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  343. }
  344. if (statusRes.ok) state.systemStatus = await statusRes.json();
  345. if (ifacesRes.ok) {
  346. const ifacesData = await ifacesRes.json();
  347. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  348. state.interfaces = rawIfaces.filter(i => {
  349. if (!i.name) return false;
  350. if (i.name.startsWith('ep_')) return false;
  351. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  352. });
  353. try { populateToolsInterfaces(); } catch (e) {}
  354. }
  355. if (vlansRes.ok) {
  356. const vlansData = await vlansRes.json();
  357. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  358. }
  359. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  360. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  361. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  362. updateSystemMetrics();
  363. updateBadges();
  364. if (state.activeTab === 'dashboard') renderDashboard();
  365. if (state.activeTab === 'interfaces') {
  366. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  367. else renderInterfacesList();
  368. }
  369. if (state.activeTab === 'vlans') renderVlansList();
  370. if (state.activeTab === 'firewall') loadFirewall(false);
  371. if (state.activeTab === 'routes') loadRoutes(false);
  372. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  373. if (state.activeTab === 'ppp') loadPPP(false);
  374. if (state.activeTab === 'eoip') loadEoIP(false);
  375. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  376. if (state.activeTab === 'pppoe') loadPPPoE(false);
  377. if (state.activeTab === 'wireguard') loadWireGuard(false);
  378. if (state.activeTab === 'ipsec') loadIPSec(false);
  379. if (state.activeTab === 'l2tp') loadL2TP(false);
  380. if (state.activeTab === 'pptp') loadPPTP(false);
  381. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  382. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  383. if (state.activeTab === 'vrrp') loadVRRP(false);
  384. if (state.activeTab === 'settings') loadSettingsData(false);
  385. fetchBwTestServerStatus();
  386. } catch (err) {
  387. console.error('Failed to fetch router state:', err);
  388. } finally {
  389. if (isManual && spinner) {
  390. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  391. }
  392. }
  393. }
  394. // Update Top KPI and Sidebar Telemetry
  395. function updateSystemMetrics() {
  396. const s = state.systemStatus;
  397. const v = state.vpnStatus;
  398. if (!s) return;
  399. // Sidebar Host & Uptime
  400. const sideHost = document.getElementById('side-hostname');
  401. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  402. const sideUp = document.getElementById('side-uptime');
  403. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  404. const sideGw = document.getElementById('side-gateway-ip');
  405. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  406. // Compute CPU Metrics
  407. let cpuPct = 0;
  408. if (s.cpu_pct !== undefined) {
  409. cpuPct = s.cpu_pct;
  410. } else if (s.cpu_load && s.cpu_load.length > 0) {
  411. const cores = s.cpu_cores || 1;
  412. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  413. }
  414. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  415. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  416. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  417. // Sidebar CPU
  418. const sideCpuVal = document.getElementById('side-cpu-val');
  419. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  420. const sideCpuBar = document.getElementById('side-cpu-bar');
  421. if (sideCpuBar) {
  422. sideCpuBar.style.width = cpuWidth;
  423. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  424. }
  425. // Dashboard CPU Card
  426. const dashCpuVal = document.getElementById('dash-cpu-val');
  427. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  428. const dashCpuBar = document.getElementById('dash-cpu-bar');
  429. if (dashCpuBar) {
  430. dashCpuBar.style.width = cpuWidth;
  431. if (cpuPct > 85) {
  432. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  433. } else if (cpuPct > 65) {
  434. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  435. } else {
  436. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  437. }
  438. }
  439. const dashCpuCores = document.getElementById('dash-cpu-cores');
  440. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  441. const dashCpuLoad = document.getElementById('dash-cpu-load');
  442. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  443. const dashCpuStatus = document.getElementById('dash-cpu-status');
  444. if (dashCpuStatus) {
  445. if (cpuPct > 85) {
  446. dashCpuStatus.innerText = 'High';
  447. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  448. } else if (cpuPct > 65) {
  449. dashCpuStatus.innerText = 'Heavy';
  450. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  451. } else {
  452. dashCpuStatus.innerText = 'Normal';
  453. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  454. }
  455. }
  456. // Compute RAM Metrics
  457. const memPct = Math.round(s.mem_usage_pct || 0);
  458. const memPctStr = `${memPct}%`;
  459. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  460. const usedMB = s.mem_used_mb || 0;
  461. const totalMB = s.mem_total_mb || 0;
  462. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  463. function fmtMemMB(mb) {
  464. if (mb >= 1024) {
  465. return `${(mb / 1024).toFixed(1)} GB`;
  466. }
  467. return `${mb} MB`;
  468. }
  469. // Sidebar RAM
  470. const sideRamVal = document.getElementById('side-ram-val');
  471. if (sideRamVal) sideRamVal.innerText = memPctStr;
  472. const sideRamBar = document.getElementById('side-ram-bar');
  473. if (sideRamBar) sideRamBar.style.width = memWidth;
  474. // Dashboard RAM Card
  475. const dashRamVal = document.getElementById('dash-ram-val');
  476. if (dashRamVal) dashRamVal.innerText = memPctStr;
  477. const dashRamBar = document.getElementById('dash-ram-bar');
  478. if (dashRamBar) {
  479. dashRamBar.style.width = memWidth;
  480. if (memPct > 85) {
  481. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  482. } else if (memPct > 70) {
  483. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  484. } else {
  485. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  486. }
  487. }
  488. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  489. if (dashRamUsedTotal) {
  490. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  491. }
  492. const dashRamFree = document.getElementById('dash-ram-free');
  493. if (dashRamFree) {
  494. dashRamFree.innerText = fmtMemMB(freeMB);
  495. }
  496. const dashRamStatus = document.getElementById('dash-ram-status');
  497. if (dashRamStatus) {
  498. if (memPct > 85) {
  499. dashRamStatus.innerText = 'High';
  500. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  501. } else {
  502. dashRamStatus.innerText = 'Active';
  503. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  504. }
  505. }
  506. // Legacy Dashboard Stats (Safe checks)
  507. const elIfacesUp = document.getElementById('stat-ifaces-up');
  508. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  509. const elIfacesTot = document.getElementById('stat-ifaces-total');
  510. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  511. const elIfacesDown = document.getElementById('stat-ifaces-down');
  512. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  513. const elVlans = document.getElementById('stat-vlans-count');
  514. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  515. // VPN Status Indicators
  516. if (v) {
  517. const totalActive = v.total_active_tunnels || 0;
  518. const statVpnActive = document.getElementById('stat-vpn-active');
  519. if (statVpnActive) statVpnActive.innerText = totalActive;
  520. const tunnelsDot = document.getElementById('tunnels-dot');
  521. const tunnelsLabel = document.getElementById('tunnels-label');
  522. if (tunnelsDot && tunnelsLabel) {
  523. if (totalActive > 0) {
  524. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  525. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  526. } else {
  527. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  528. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  529. }
  530. }
  531. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  532. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  533. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  534. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  535. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  536. }
  537. // Total Live Bandwidth Rate
  538. let totalRx = 0;
  539. let totalTx = 0;
  540. (state.interfaces || []).forEach(i => {
  541. if (i.rate) {
  542. totalRx += i.rate.rx_bytes_sec || 0;
  543. totalTx += i.rate.tx_bytes_sec || 0;
  544. }
  545. });
  546. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  547. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  548. }
  549. function setDotBadge(id, active) {
  550. const el = document.getElementById(id);
  551. if (!el) return;
  552. if (active) {
  553. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  554. } else {
  555. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  556. }
  557. }
  558. function updateBadges() {
  559. const bIfaces = document.getElementById('badge-ifaces-count');
  560. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  561. const bVlans = document.getElementById('badge-vlans-count');
  562. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  563. if (state.fwSummary) {
  564. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  565. const badgeFw = document.getElementById('badge-firewall-count');
  566. if (badgeFw) badgeFw.innerText = totalFwRules;
  567. }
  568. if (state.vpnStatus) {
  569. const v = state.vpnStatus;
  570. const bEoIP = document.getElementById('badge-eoip-count');
  571. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  572. const bAero = document.getElementById('badge-aerotun-count');
  573. if (bAero) bAero.innerText = v.total_aerotun || 0;
  574. const bPPPSess = document.getElementById('badge-ppp-sessions');
  575. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  576. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  577. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  578. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  579. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  580. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  581. }
  582. if (state.dynSummary) {
  583. const d = state.dynSummary;
  584. setDotBadge('badge-bgp-dot', d.bgp_running);
  585. setDotBadge('badge-ospf-dot', d.ospf_running);
  586. const bBgp = document.getElementById('badge-bgp-count');
  587. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  588. const bOspf = document.getElementById('badge-ospf-count');
  589. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  590. const bFilters = document.getElementById('badge-filters-count');
  591. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  592. }
  593. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  594. if (bDhcpServer) {
  595. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  596. }
  597. }
  598. // Render Dashboard View
  599. function renderDashboard() {
  600. const matrix = document.getElementById('port-matrix');
  601. if (!matrix) return;
  602. const ifaces = state.interfaces || [];
  603. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  604. if (matrix.dataset.sig === sig) {
  605. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  606. }
  607. matrix.dataset.sig = sig;
  608. matrix.innerHTML = '';
  609. (state.interfaces || []).forEach(iface => {
  610. const isUp = iface.state === 'UP';
  611. const isVlan = iface.is_vlan;
  612. const portCard = document.createElement('div');
  613. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  614. isUp
  615. ? (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')
  616. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  617. }`;
  618. portCard.onclick = () => openIfaceModal(iface.name);
  619. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  620. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  621. portCard.innerHTML = `
  622. <div class="flex items-center justify-between mb-2">
  623. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  624. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  625. </div>
  626. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  627. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  628. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  629. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  630. </div>
  631. `;
  632. matrix.appendChild(portCard);
  633. });
  634. const ifaceTbody = document.getElementById('quick-interfaces-table');
  635. if (ifaceTbody) {
  636. ifaceTbody.innerHTML = '';
  637. (state.interfaces || []).forEach(i => {
  638. const isUp = i.state === 'UP';
  639. const tr = document.createElement('tr');
  640. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  641. tr.onclick = () => openIfaceModal(i.name);
  642. const rxStr = i.rate?.rx_human || '0 B/s';
  643. const txStr = i.rate?.tx_human || '0 B/s';
  644. tr.innerHTML = `
  645. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  646. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  647. <span>${i.name}</span>
  648. </td>
  649. <td class="py-2.5 text-slate-300 font-sans">
  650. ${getRoleBadge(i.role || 'LAN')}
  651. </td>
  652. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  653. <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>
  654. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  655. <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>
  656. </td>
  657. <td class="py-2.5 text-right font-sans font-semibold">
  658. <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>
  659. </td>
  660. `;
  661. ifaceTbody.appendChild(tr);
  662. });
  663. }
  664. const vlanTbody = document.getElementById('quick-vlans-table');
  665. if (vlanTbody) {
  666. vlanTbody.innerHTML = '';
  667. }
  668. }
  669. // Expand / Collapse Handlers
  670. function toggleExpand(parentName) {
  671. if (state.expandedParents.has(parentName)) {
  672. state.expandedParents.delete(parentName);
  673. } else {
  674. state.expandedParents.add(parentName);
  675. }
  676. renderInterfacesList();
  677. }
  678. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  679. function supportsVLAN(iface) {
  680. if (!iface) return false;
  681. if (iface.is_vlan) return false;
  682. const name = (iface.name || '').toLowerCase();
  683. const type = (iface.type || '').toLowerCase();
  684. const role = (iface.role || '').toLowerCase();
  685. // Exclude loopback
  686. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  687. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  688. if (type === 'wireguard' || name.startsWith('wg')) return false;
  689. // Exclude PPP / PPPoE
  690. if (type === 'ppp' || name.startsWith('ppp')) return false;
  691. // Exclude other Layer 3 tunnels and dummy devices
  692. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  693. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  694. return false;
  695. }
  696. // If name already contains a dot, it's already a sub-interface
  697. if (name.includes('.')) return false;
  698. return true;
  699. }
  700. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  701. function supportsDHCPClient(iface) {
  702. if (!iface) return false;
  703. const name = (iface.name || '').toLowerCase();
  704. const type = (iface.type || '').toLowerCase();
  705. const role = (iface.role || '').toLowerCase();
  706. // Exclude loopback
  707. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  708. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  709. if (type === 'wireguard' || name.startsWith('wg')) return false;
  710. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  711. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  712. // Exclude other Layer 3 tunnels and dummy devices
  713. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  714. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  715. return false;
  716. }
  717. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  718. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  719. if (isBridgePort) return false;
  720. return true;
  721. }
  722. // Expand / Collapse Handlers
  723. function toggleExpand(parentName) {
  724. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  725. if (childVlans.length === 0) {
  726. // Cannot expand an interface with no VLANs
  727. state.expandedParents.delete(parentName);
  728. return;
  729. }
  730. if (state.expandedParents.has(parentName)) {
  731. state.expandedParents.delete(parentName);
  732. } else {
  733. state.expandedParents.add(parentName);
  734. }
  735. renderInterfacesList();
  736. }
  737. function expandAllIfaces(expand) {
  738. if (expand) {
  739. (state.interfaces || []).forEach(i => {
  740. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  741. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  742. });
  743. } else {
  744. state.expandedParents.clear();
  745. }
  746. renderInterfacesList();
  747. }
  748. // =========================================================================
  749. // INTERFACE ROLE TAGS MANAGEMENT
  750. // =========================================================================
  751. const ROLE_COLORS = {
  752. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  753. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  754. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  755. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  756. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  757. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  758. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  759. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  760. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  761. };
  762. function getRoleBadge(roleName) {
  763. const name = roleName || 'LAN';
  764. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  765. const colorKey = (role?.color || 'blue').toLowerCase();
  766. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  767. 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>`;
  768. }
  769. function switchIfaceSubTab(subTab) {
  770. state.activeIfaceSubTab = subTab;
  771. const treeTab = document.getElementById('ifaces-subtab-tree');
  772. const rolesTab = document.getElementById('ifaces-subtab-roles');
  773. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  774. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  775. if (subTab === 'roles') {
  776. treeTab?.classList.add('hidden');
  777. rolesTab?.classList.remove('hidden');
  778. if (btnRoles) {
  779. 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';
  780. }
  781. if (btnTree) {
  782. 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';
  783. }
  784. loadRoles();
  785. } else {
  786. rolesTab?.classList.add('hidden');
  787. treeTab?.classList.remove('hidden');
  788. if (btnTree) {
  789. 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';
  790. }
  791. if (btnRoles) {
  792. 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';
  793. }
  794. renderInterfacesList();
  795. }
  796. }
  797. async function loadRoles() {
  798. try {
  799. const res = await fetch(`${API_BASE}/roles`);
  800. if (res.ok) {
  801. state.roles = await res.json();
  802. const countEl = document.getElementById('badge-roles-count');
  803. if (countEl) countEl.innerText = (state.roles || []).length;
  804. renderRolesTable();
  805. populateRoleSelects();
  806. }
  807. } catch (err) {
  808. console.error('Failed to load role tags:', err);
  809. }
  810. }
  811. function renderRolesTable() {
  812. const tbody = document.getElementById('roles-table-body');
  813. const empty = document.getElementById('roles-empty-state');
  814. if (!tbody) return;
  815. const roles = state.roles || [];
  816. if (roles.length === 0) {
  817. tbody.innerHTML = '';
  818. empty?.classList.remove('hidden');
  819. return;
  820. }
  821. empty?.classList.add('hidden');
  822. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  823. if (tbody.dataset.sig === sig) return;
  824. tbody.dataset.sig = sig;
  825. tbody.innerHTML = roles.map(r => {
  826. const colorKey = (r.color || 'blue').toLowerCase();
  827. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  828. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  829. const ifacesChips = ifaces.length > 0
  830. ? 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('')
  831. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  832. return `
  833. <tr class="hover:bg-slate-800/40 transition">
  834. <td class="py-3 px-4">
  835. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  836. ${escapeHtml(r.name)}
  837. </span>
  838. </td>
  839. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  840. <span>${escapeHtml(r.name)}</span>
  841. ${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>' : ''}
  842. </td>
  843. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  844. <span class="inline-flex items-center gap-1.5">
  845. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  846. <span>${escapeHtml(r.color || 'blue')}</span>
  847. </span>
  848. </td>
  849. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  850. <td class="py-3 px-4 font-sans">
  851. <div class="flex flex-wrap items-center">
  852. ${ifacesChips}
  853. </div>
  854. </td>
  855. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  856. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  857. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  858. Edit
  859. </button>
  860. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  861. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  862. Delete
  863. </button>
  864. </td>
  865. </tr>
  866. `;
  867. }).join('');
  868. }
  869. function openRoleModal(id = null) {
  870. const modal = document.getElementById('role-modal');
  871. if (!modal) return;
  872. const idInput = document.getElementById('role-modal-id');
  873. const nameInput = document.getElementById('role-modal-name');
  874. const colorSelect = document.getElementById('role-modal-color');
  875. const descInput = document.getElementById('role-modal-desc');
  876. const title = document.getElementById('role-modal-title');
  877. if (id) {
  878. const role = (state.roles || []).find(r => r.id === id);
  879. if (role) {
  880. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  881. if (idInput) idInput.value = role.id;
  882. if (nameInput) nameInput.value = role.name;
  883. if (colorSelect) colorSelect.value = role.color || 'blue';
  884. if (descInput) descInput.value = role.description || '';
  885. }
  886. } else {
  887. if (title) title.innerText = 'Add Role Tag';
  888. if (idInput) idInput.value = '';
  889. if (nameInput) nameInput.value = '';
  890. if (colorSelect) colorSelect.value = 'blue';
  891. if (descInput) descInput.value = '';
  892. }
  893. updateRoleModalPreview();
  894. modal.classList.remove('hidden');
  895. }
  896. function closeRoleModal() {
  897. const modal = document.getElementById('role-modal');
  898. if (modal) modal.classList.add('hidden');
  899. }
  900. function updateRoleModalPreview() {
  901. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  902. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  903. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  904. const preview = document.getElementById('role-modal-preview');
  905. if (preview) {
  906. preview.innerText = name;
  907. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  908. }
  909. }
  910. async function submitSaveRole(e) {
  911. e.preventDefault();
  912. const id = document.getElementById('role-modal-id')?.value;
  913. const name = document.getElementById('role-modal-name')?.value.trim();
  914. const color = document.getElementById('role-modal-color')?.value;
  915. const desc = document.getElementById('role-modal-desc')?.value.trim();
  916. if (!name) return;
  917. try {
  918. const payload = { id, name, color, description: desc };
  919. const method = id ? 'PUT' : 'POST';
  920. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  921. const res = await fetch(url, {
  922. method,
  923. headers: { 'Content-Type': 'application/json' },
  924. body: JSON.stringify(payload)
  925. });
  926. if (res.ok) {
  927. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  928. closeRoleModal();
  929. await loadRoles();
  930. fetchData(false);
  931. } else {
  932. const err = await res.json();
  933. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  934. }
  935. } catch (err) {
  936. showToast('Error', err.message, 'error');
  937. }
  938. }
  939. async function deleteRoleTag(id, name) {
  940. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  941. try {
  942. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  943. method: 'DELETE'
  944. });
  945. if (res.ok) {
  946. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  947. await loadRoles();
  948. fetchData(false);
  949. } else {
  950. const err = await res.json();
  951. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  952. }
  953. } catch (err) {
  954. showToast('Error', err.message, 'error');
  955. }
  956. }
  957. function populateRoleSelects(selectedRole = '') {
  958. const ifaceSelect = document.getElementById('modal-iface-role');
  959. const vlanSelect = document.getElementById('vlan-role');
  960. const roles = state.roles || [];
  961. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  962. if (ifaceSelect) {
  963. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  964. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  965. ifaceSelect.innerHTML = optionsHtml;
  966. ifaceSelect.dataset.optionsSig = optionsHtml;
  967. }
  968. if (currentVal) ifaceSelect.value = currentVal;
  969. }
  970. if (vlanSelect) {
  971. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  972. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  973. vlanSelect.innerHTML = optionsHtml;
  974. vlanSelect.dataset.optionsSig = optionsHtml;
  975. }
  976. if (currentVal) vlanSelect.value = currentVal;
  977. }
  978. }
  979. // Filter and Render Hierarchical Interfaces List
  980. function filterIfaces(filter) {
  981. state.ifaceFilter = filter || 'all';
  982. renderInterfacesList();
  983. }
  984. function renderInterfacesList() {
  985. const tbody = document.getElementById('interfaces-tree-tbody');
  986. const emptyState = document.getElementById('interfaces-empty-state');
  987. const summary = document.getElementById('ifaces-list-summary');
  988. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  989. const allIfaces = state.interfaces || [];
  990. const allVlans = state.vlans || [];
  991. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  992. const filteredParents = parentIfaces.filter(parent => {
  993. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  994. if (query) {
  995. const matchName = parent.name.toLowerCase().includes(query);
  996. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  997. const matchRole = (parent.role || '').toLowerCase().includes(query);
  998. const matchType = (parent.type || '').toLowerCase().includes(query);
  999. const matchVlan = childVlans.some(v =>
  1000. v.name.toLowerCase().includes(query) ||
  1001. String(v.vlan_id).includes(query) ||
  1002. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1003. (v.description || '').toLowerCase().includes(query)
  1004. );
  1005. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1006. }
  1007. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1008. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1009. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1010. return true;
  1011. });
  1012. if (summary) {
  1013. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1014. }
  1015. if (filteredParents.length === 0) {
  1016. emptyState?.classList.remove('hidden');
  1017. tbody.innerHTML = '';
  1018. return;
  1019. }
  1020. emptyState?.classList.add('hidden');
  1021. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1022. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1023. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1024. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1025. }).join(';');
  1026. if (tbody.dataset.sig === sig) {
  1027. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1028. }
  1029. tbody.dataset.sig = sig;
  1030. tbody.innerHTML = '';
  1031. filteredParents.forEach(parent => {
  1032. const isUp = parent.state === 'UP';
  1033. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1034. const hasVlans = childVlans.length > 0;
  1035. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1036. const canHaveVlan = supportsVLAN(parent);
  1037. const parentRow = document.createElement('tr');
  1038. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1039. parentRow.innerHTML = `
  1040. <td class="py-3 px-3 text-center">
  1041. ${hasVlans ? `
  1042. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1043. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1044. <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">
  1045. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1046. </svg>
  1047. </button>
  1048. ` : `
  1049. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1050. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1051. </div>
  1052. `}
  1053. </td>
  1054. <td class="py-3 px-4">
  1055. <div class="flex items-center space-x-2.5">
  1056. <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">
  1057. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1058. </div>
  1059. <div>
  1060. <div class="flex items-center gap-2">
  1061. <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'}">
  1062. <span>${parent.name}</span>
  1063. <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>
  1064. </span>
  1065. ${hasVlans ? `
  1066. <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>
  1067. ` : `
  1068. <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>
  1069. `}
  1070. </div>
  1071. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1072. </div>
  1073. </div>
  1074. </td>
  1075. <td class="py-3 px-4 font-sans">
  1076. <div class="flex items-center gap-1.5">
  1077. ${getRoleBadge(parent.role || 'LAN')}
  1078. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1079. </div>
  1080. </td>
  1081. <td class="py-3 px-4">
  1082. ${parent.ipv4 && parent.ipv4.length > 0
  1083. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1084. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1085. }
  1086. ${(() => {
  1087. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1088. if (!c) return '';
  1089. 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');
  1090. 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>`;
  1091. })()}
  1092. </td>
  1093. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1094. <div>${parent.mac || 'N/A'}</div>
  1095. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1096. </td>
  1097. <td class="py-3 px-4 text-[11px]">
  1098. <div class="flex items-center space-x-2">
  1099. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1100. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1101. </div>
  1102. </td>
  1103. <td class="py-3 px-4 font-sans">
  1104. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1105. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1106. 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'
  1107. }" title="Click to toggle link status">
  1108. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1109. <span>${parent.state}</span>
  1110. </button>
  1111. </td>
  1112. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1113. ${(() => {
  1114. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1115. if (c) {
  1116. 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>`;
  1117. }
  1118. if (!supportsDHCPClient(parent)) {
  1119. return '';
  1120. }
  1121. 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>`;
  1122. })()}
  1123. ${canHaveVlan ? `
  1124. <button onclick="openVlanModal('${parent.name}')"
  1125. 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">
  1126. + Add VLAN
  1127. </button>
  1128. ` : ''}
  1129. <button onclick="openIfaceModal('${parent.name}')"
  1130. 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">
  1131. Edit
  1132. </button>
  1133. </td>
  1134. `;
  1135. tbody.appendChild(parentRow);
  1136. if (isExpanded) {
  1137. const drawerRow = document.createElement('tr');
  1138. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1139. const drawerCell = document.createElement('td');
  1140. drawerCell.colSpan = 8;
  1141. drawerCell.className = 'p-0';
  1142. drawerCell.innerHTML = `
  1143. <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">
  1144. <div class="flex items-center justify-between mb-3">
  1145. <div class="flex items-center space-x-3">
  1146. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1147. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1148. </span>
  1149. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1150. ${childVlans.length} Attached
  1151. </span>
  1152. </div>
  1153. <button onclick="openVlanModal('${parent.name}')"
  1154. 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">
  1155. <span>+ Create VLAN on ${parent.name}</span>
  1156. </button>
  1157. </div>
  1158. ${childVlans.length === 0 ? `
  1159. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1160. <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>
  1161. <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">
  1162. <span>+ Create Your First VLAN on ${parent.name}</span>
  1163. </button>
  1164. </div>
  1165. ` : `
  1166. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1167. <table class="w-full text-left text-xs font-mono">
  1168. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1169. <tr>
  1170. <th class="py-2.5 px-4">VLAN ID</th>
  1171. <th class="py-2.5 px-4">Interface Device</th>
  1172. <th class="py-2.5 px-4">Subnet Gateway</th>
  1173. <th class="py-2.5 px-4">Role / Alias</th>
  1174. <th class="py-2.5 px-4">MTU</th>
  1175. <th class="py-2.5 px-4">Throughput</th>
  1176. <th class="py-2.5 px-4">Status</th>
  1177. <th class="py-2.5 px-4 text-right">Actions</th>
  1178. </tr>
  1179. </thead>
  1180. <tbody class="divide-y divide-slate-800/70">
  1181. ${childVlans.map(v => {
  1182. const isVlanUp = v.state === 'UP';
  1183. return `
  1184. <tr class="hover:bg-slate-800/40 transition">
  1185. <td class="py-2.5 px-4">
  1186. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1187. VLAN ${v.vlan_id}
  1188. </span>
  1189. </td>
  1190. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1191. <span class="text-cyan-500">└─</span>
  1192. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1193. <span>${v.name}</span>
  1194. <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>
  1195. </span>
  1196. </td>
  1197. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1198. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1199. ${(() => {
  1200. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1201. if (!c) return '';
  1202. 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';
  1203. 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>`;
  1204. })()}
  1205. </td>
  1206. <td class="py-2.5 px-4 font-sans text-slate-300">
  1207. <div class="flex items-center gap-1.5">
  1208. ${getRoleBadge(v.role || 'LAN')}
  1209. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1210. </div>
  1211. </td>
  1212. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1213. <td class="py-2.5 px-4 text-[11px]">
  1214. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1215. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1216. </td>
  1217. <td class="py-2.5 px-4 font-sans">
  1218. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1219. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1220. 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'
  1221. }">
  1222. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1223. <span>${v.state}</span>
  1224. </button>
  1225. </td>
  1226. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1227. ${(() => {
  1228. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1229. if (c) {
  1230. 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>`;
  1231. }
  1232. if (!supportsDHCPClient(v)) {
  1233. return '';
  1234. }
  1235. 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>`;
  1236. })()}
  1237. <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>
  1238. <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>
  1239. </td>
  1240. </tr>
  1241. `;
  1242. }).join('')}
  1243. </tbody>
  1244. </table>
  1245. </div>
  1246. `}
  1247. </div>
  1248. `;
  1249. drawerRow.appendChild(drawerCell);
  1250. tbody.appendChild(drawerRow);
  1251. }
  1252. });
  1253. }
  1254. // Render VLANs Dedicated View
  1255. function renderVlansList() {
  1256. const tbody = document.getElementById('vlans-table-body');
  1257. if (!tbody) return;
  1258. const emptyState = document.getElementById('vlans-empty-state');
  1259. const countBadge = document.getElementById('vlans-table-count');
  1260. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1261. const allVlans = state.vlans || [];
  1262. if (countBadge) countBadge.innerText = allVlans.length;
  1263. const filtered = allVlans.filter(v => {
  1264. if (!query) return true;
  1265. return v.name.toLowerCase().includes(query) ||
  1266. String(v.vlan_id).includes(query) ||
  1267. (v.description || '').toLowerCase().includes(query) ||
  1268. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1269. });
  1270. if (allVlans.length === 0) {
  1271. emptyState.classList.remove('hidden');
  1272. tbody.innerHTML = '';
  1273. return;
  1274. }
  1275. emptyState.classList.add('hidden');
  1276. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1277. if (tbody.dataset.sig === sig) return;
  1278. tbody.dataset.sig = sig;
  1279. tbody.innerHTML = '';
  1280. filtered.forEach(v => {
  1281. const isUp = v.state === 'UP';
  1282. const tr = document.createElement('tr');
  1283. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1284. tr.innerHTML = `
  1285. <td class="py-3 px-4">
  1286. <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">
  1287. VLAN ${v.vlan_id}
  1288. </span>
  1289. </td>
  1290. <td class="py-3 px-4 font-bold text-white">
  1291. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1292. <span>${v.name}</span>
  1293. <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>
  1294. </span>
  1295. </td>
  1296. <td class="py-3 px-4 text-slate-300">
  1297. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1298. </td>
  1299. <td class="py-3 px-4 text-emerald-400 font-medium">
  1300. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1301. </td>
  1302. <td class="py-3 px-4 text-slate-300 font-sans">
  1303. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1304. </td>
  1305. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1306. <td class="py-3 px-4 font-sans">
  1307. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1308. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1309. 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'
  1310. }">
  1311. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1312. <span>${v.state}</span>
  1313. </button>
  1314. </td>
  1315. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1316. <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>
  1317. <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>
  1318. </td>
  1319. `;
  1320. tbody.appendChild(tr);
  1321. });
  1322. }
  1323. // Toggle interface UP / DOWN
  1324. async function toggleInterfaceState(name, newState) {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1327. method: 'POST',
  1328. headers: { 'Content-Type': 'application/json' },
  1329. body: JSON.stringify({ state: newState })
  1330. });
  1331. const data = await res.json();
  1332. if (res.ok) {
  1333. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1334. fetchData(false);
  1335. } else {
  1336. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1337. }
  1338. } catch (err) {
  1339. showToast('Error', err.message, 'error');
  1340. }
  1341. }
  1342. // ---------------- MikroTik Flag & Utilities ----------------
  1343. function renderMikroTikFlag(running, disabled) {
  1344. if (running) {
  1345. 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>`;
  1346. }
  1347. if (disabled) {
  1348. 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>`;
  1349. }
  1350. 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>`;
  1351. }
  1352. function copyToClipboard(text, label = 'Text') {
  1353. navigator.clipboard.writeText(text).then(() => {
  1354. showToast('Copied', `${label} copied to clipboard`, 'success');
  1355. }).catch(() => {
  1356. prompt('Copy value:', text);
  1357. });
  1358. }
  1359. // ======================== PPP Profiles Shared Helper ========================
  1360. async function fetchPPPProfilesList() {
  1361. try {
  1362. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1363. if (res.ok) {
  1364. state.pppProfiles = await res.json();
  1365. }
  1366. } catch (err) {
  1367. console.error('Failed to load PPP profiles:', err);
  1368. }
  1369. }
  1370. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1371. const sel = document.getElementById(selectId);
  1372. if (!sel) return;
  1373. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1374. { name: 'default', use_encryption: 'no' },
  1375. { name: 'default-encryption', use_encryption: 'required' }
  1376. ];
  1377. sel.innerHTML = '';
  1378. profiles.forEach(p => {
  1379. const opt = document.createElement('option');
  1380. opt.value = p.name;
  1381. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1382. opt.innerText = `${p.name}${encBadge}`;
  1383. sel.appendChild(opt);
  1384. });
  1385. if (selectedVal) {
  1386. sel.value = selectedVal;
  1387. } else {
  1388. sel.value = defaultVal;
  1389. }
  1390. if (!sel.value && sel.options.length > 0) {
  1391. sel.selectedIndex = 0;
  1392. }
  1393. }
  1394. // ======================== PPPoE Multi-Instance ========================
  1395. async function loadPPPoE(populateInputs = true) {
  1396. try {
  1397. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1398. await fetchPPPProfilesList();
  1399. }
  1400. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1401. const list = await res.json();
  1402. state.pppoeList = Array.isArray(list) ? list : [];
  1403. const badge = document.getElementById('pppoe-count-badge');
  1404. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1405. const tbody = document.getElementById('pppoe-table-body');
  1406. const empty = document.getElementById('pppoe-empty');
  1407. if (!tbody) return;
  1408. tbody.innerHTML = '';
  1409. if (state.pppoeList.length === 0) {
  1410. if (empty) empty.classList.remove('hidden');
  1411. } else {
  1412. if (empty) empty.classList.add('hidden');
  1413. state.pppoeList.forEach(inst => {
  1414. const tr = document.createElement('tr');
  1415. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1416. tr.innerHTML = `
  1417. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1418. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1419. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1420. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1421. <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>
  1422. <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>
  1423. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1424. <td class="py-2.5 px-3 text-center">
  1425. <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'}">
  1426. ${inst.default_route ? 'Yes' : 'No'}
  1427. </span>
  1428. </td>
  1429. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1430. ${inst.running ? `
  1431. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1432. ` : `
  1433. <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>
  1434. `}
  1435. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1436. ${inst.disabled ? 'Enable' : 'Disable'}
  1437. </button>
  1438. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1439. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1440. </td>
  1441. `;
  1442. tbody.appendChild(tr);
  1443. });
  1444. }
  1445. } catch (err) {
  1446. console.error('Failed to load PPPoE:', err);
  1447. }
  1448. }
  1449. function openAddPPPoEModal() {
  1450. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1451. document.getElementById('pppoe-modal-edit-orig').value = '';
  1452. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1453. document.getElementById('pppoe-modal-name').readOnly = false;
  1454. document.getElementById('pppoe-modal-user').value = '';
  1455. document.getElementById('pppoe-modal-pass').value = '';
  1456. document.getElementById('pppoe-modal-service').value = '';
  1457. document.getElementById('pppoe-modal-mtu').value = '1492';
  1458. document.getElementById('pppoe-modal-defroute').checked = true;
  1459. document.getElementById('pppoe-modal-reconnect').checked = true;
  1460. document.getElementById('pppoe-modal-disabled').checked = false;
  1461. // Populate profiles
  1462. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1463. // Populate interfaces
  1464. const sel = document.getElementById('pppoe-modal-iface');
  1465. sel.innerHTML = '';
  1466. (state.interfaces || []).forEach(i => {
  1467. if (i.name === 'lo') return;
  1468. const opt = document.createElement('option');
  1469. opt.value = i.name;
  1470. opt.innerText = `${i.name} (${i.role || i.type})`;
  1471. sel.appendChild(opt);
  1472. });
  1473. document.getElementById('pppoe-modal').classList.remove('hidden');
  1474. }
  1475. function openEditPPPoEModal(name) {
  1476. const inst = (state.pppoeList || []).find(i => i.name === name);
  1477. if (!inst) return;
  1478. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1479. document.getElementById('pppoe-modal-edit-orig').value = name;
  1480. document.getElementById('pppoe-modal-name').value = inst.name;
  1481. document.getElementById('pppoe-modal-name').readOnly = true;
  1482. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1483. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1484. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1485. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1486. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1487. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1488. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1489. // Populate profiles
  1490. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1491. const sel = document.getElementById('pppoe-modal-iface');
  1492. sel.innerHTML = '';
  1493. (state.interfaces || []).forEach(i => {
  1494. if (i.name === 'lo') return;
  1495. const opt = document.createElement('option');
  1496. opt.value = i.name;
  1497. opt.innerText = `${i.name} (${i.role || i.type})`;
  1498. if (i.name === inst.interface) opt.selected = true;
  1499. sel.appendChild(opt);
  1500. });
  1501. document.getElementById('pppoe-modal').classList.remove('hidden');
  1502. }
  1503. function closePPPoEModal() {
  1504. document.getElementById('pppoe-modal').classList.add('hidden');
  1505. }
  1506. async function submitSavePPPoE(e) {
  1507. e.preventDefault();
  1508. const name = document.getElementById('pppoe-modal-name').value.trim();
  1509. const iface = document.getElementById('pppoe-modal-iface').value;
  1510. const user = document.getElementById('pppoe-modal-user').value.trim();
  1511. const pass = document.getElementById('pppoe-modal-pass').value;
  1512. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1513. const service = document.getElementById('pppoe-modal-service').value.trim();
  1514. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1515. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1516. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1517. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1518. try {
  1519. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1520. method: 'POST',
  1521. headers: { 'Content-Type': 'application/json' },
  1522. body: JSON.stringify({
  1523. name,
  1524. interface: iface,
  1525. username: user,
  1526. password: pass,
  1527. profile: profile,
  1528. service_name: service,
  1529. mtu,
  1530. default_route: defRoute,
  1531. auto_reconnect: reconnect,
  1532. disabled
  1533. })
  1534. });
  1535. if (res.ok) {
  1536. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1537. closePPPoEModal();
  1538. loadPPPoE(false);
  1539. fetchData(false);
  1540. } else {
  1541. const err = await res.json();
  1542. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1543. }
  1544. } catch (err) {
  1545. showToast('Error', err.message, 'error');
  1546. }
  1547. }
  1548. async function connectPPPoEInstance(name) {
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1551. if (res.ok) {
  1552. showToast('Connecting', `Dialing ${name}...`, 'info');
  1553. setTimeout(() => loadPPPoE(false), 2000);
  1554. }
  1555. } catch (err) {
  1556. showToast('Error', err.message, 'error');
  1557. }
  1558. }
  1559. async function disconnectPPPoEInstance(name) {
  1560. try {
  1561. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1562. if (res.ok) {
  1563. showToast('Disconnected', `${name} session terminated`, 'info');
  1564. setTimeout(() => loadPPPoE(false), 1000);
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function togglePPPoEState(name, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ enabled: enable })
  1576. });
  1577. if (res.ok) {
  1578. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1579. loadPPPoE(false);
  1580. }
  1581. } catch (err) {
  1582. showToast('Error', err.message, 'error');
  1583. }
  1584. }
  1585. async function deletePPPoEInstance(name) {
  1586. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1587. try {
  1588. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1589. if (res.ok) {
  1590. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1591. loadPPPoE(false);
  1592. fetchData(false);
  1593. }
  1594. } catch (err) {
  1595. showToast('Error', err.message, 'error');
  1596. }
  1597. }
  1598. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1599. state.wgSubTab = 'ifaces';
  1600. function switchWGSubTab(tab) {
  1601. state.wgSubTab = tab;
  1602. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1603. const peersPanel = document.getElementById('wg-subtab-peers');
  1604. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1605. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1606. if (tab === 'ifaces') {
  1607. ifacesPanel?.classList.remove('hidden');
  1608. peersPanel?.classList.add('hidden');
  1609. 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';
  1610. 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';
  1611. } else {
  1612. ifacesPanel?.classList.add('hidden');
  1613. peersPanel?.classList.remove('hidden');
  1614. 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';
  1615. 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';
  1616. renderWGPeers();
  1617. }
  1618. }
  1619. async function loadWireGuard(populateInputs = true) {
  1620. try {
  1621. const [ifacesRes, peersRes] = await Promise.all([
  1622. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1623. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1624. ]);
  1625. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1626. const peers = peersRes.ok ? await peersRes.json() : [];
  1627. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1628. state.wgPeers = Array.isArray(peers) ? peers : [];
  1629. // Badges
  1630. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1631. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1632. const peersCountBadge = document.getElementById('wg-peers-count');
  1633. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1634. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1635. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1636. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1637. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1638. // Render Interfaces
  1639. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1640. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1641. if (ifacesTbody) {
  1642. ifacesTbody.innerHTML = '';
  1643. if (state.wgInterfaces.length === 0) {
  1644. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1645. } else {
  1646. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1647. state.wgInterfaces.forEach(iface => {
  1648. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1649. const tr = document.createElement('tr');
  1650. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1651. tr.innerHTML = `
  1652. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1653. <td class="py-2.5 px-3">
  1654. <div class="flex items-center gap-1.5">
  1655. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1656. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1657. </div>
  1658. </td>
  1659. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1660. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1661. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1662. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1663. ${(iface.public_key || '').substring(0, 10)}... 📋
  1664. </span>
  1665. </td>
  1666. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1667. <td class="py-2.5 px-3 text-center">
  1668. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1669. </td>
  1670. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1671. ${iface.running ? `
  1672. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1673. ` : `
  1674. <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>
  1675. `}
  1676. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1677. ${iface.disabled ? 'Enable' : 'Disable'}
  1678. </button>
  1679. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1680. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1681. </td>
  1682. `;
  1683. ifacesTbody.appendChild(tr);
  1684. });
  1685. }
  1686. }
  1687. // Populate filter dropdown in peers tab
  1688. const filterSel = document.getElementById('wg-peers-filter-iface');
  1689. if (filterSel) {
  1690. const currentVal = filterSel.value;
  1691. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1692. state.wgInterfaces.forEach(i => {
  1693. const opt = document.createElement('option');
  1694. opt.value = i.name;
  1695. opt.innerText = i.name;
  1696. if (i.name === currentVal) opt.selected = true;
  1697. filterSel.appendChild(opt);
  1698. });
  1699. }
  1700. renderWGPeers();
  1701. } catch (err) {
  1702. console.error('Failed to load WireGuard:', err);
  1703. }
  1704. }
  1705. function formatWGPeerEndpoint(address, port) {
  1706. if (!address || address === '(none)') return '--';
  1707. let addr = address.trim();
  1708. let p = port || 0;
  1709. while (addr.includes(':') && !addr.startsWith('[')) {
  1710. const lastColon = addr.lastIndexOf(':');
  1711. const maybePort = addr.substring(lastColon + 1);
  1712. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1713. if (!p) p = parseInt(maybePort, 10);
  1714. addr = addr.substring(0, lastColon);
  1715. } else {
  1716. break;
  1717. }
  1718. }
  1719. return p ? `${addr}:${p}` : addr;
  1720. }
  1721. function renderWGPeers() {
  1722. const filterSel = document.getElementById('wg-peers-filter-iface');
  1723. const selectedIface = filterSel ? filterSel.value : '';
  1724. const tbody = document.getElementById('wg-peers-table-body');
  1725. const empty = document.getElementById('wg-peers-empty');
  1726. if (!tbody) return;
  1727. tbody.innerHTML = '';
  1728. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1729. if (filtered.length === 0) {
  1730. if (empty) empty.classList.remove('hidden');
  1731. } else {
  1732. if (empty) empty.classList.add('hidden');
  1733. filtered.forEach(p => {
  1734. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1735. const tr = document.createElement('tr');
  1736. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1737. tr.innerHTML = `
  1738. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1739. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1740. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1741. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1742. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1743. ${(p.public_key || '').substring(0, 10)}... 📋
  1744. </span>
  1745. </td>
  1746. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1747. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1748. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1749. <td class="py-2.5 px-3 font-mono text-[11px]">
  1750. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1751. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1752. </td>
  1753. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1754. <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">
  1755. ${p.disabled ? 'Enable' : 'Disable'}
  1756. </button>
  1757. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1758. <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>
  1759. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1760. </td>
  1761. `;
  1762. tbody.appendChild(tr);
  1763. });
  1764. }
  1765. }
  1766. function openAddWGInterfaceModal() {
  1767. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1768. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1769. const nameEl = document.getElementById('wg-iface-modal-name');
  1770. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1771. nameEl.readOnly = false;
  1772. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1773. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1774. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1775. document.getElementById('wg-iface-modal-comment').value = '';
  1776. document.getElementById('wg-iface-modal-pubkey').value = '';
  1777. document.getElementById('wg-iface-modal-privkey').value = '';
  1778. document.getElementById('wg-iface-modal-disabled').checked = false;
  1779. generateWGInterfaceKeys();
  1780. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1781. }
  1782. function openEditWGInterfaceModal(name) {
  1783. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1784. if (!iface) return;
  1785. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1786. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1787. const nameEl = document.getElementById('wg-iface-modal-name');
  1788. nameEl.value = iface.name;
  1789. nameEl.readOnly = false; // ALLOW RENAMING
  1790. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1791. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1792. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1793. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1794. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1795. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1796. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1797. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1798. }
  1799. function closeAddWGInterfaceModal() {
  1800. document.getElementById('wg-iface-modal').classList.add('hidden');
  1801. }
  1802. async function generateWGInterfaceKeys() {
  1803. try {
  1804. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1805. const keys = await res.json();
  1806. if (res.ok) {
  1807. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1808. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1809. }
  1810. } catch (err) {
  1811. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1812. }
  1813. }
  1814. async function onWGInterfacePrivKeyInput() {
  1815. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1816. if (!privKey) return;
  1817. try {
  1818. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1819. method: 'POST',
  1820. headers: { 'Content-Type': 'application/json' },
  1821. body: JSON.stringify({ private_key: privKey })
  1822. });
  1823. if (res.ok) {
  1824. const data = await res.json();
  1825. if (data.public_key) {
  1826. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1827. }
  1828. }
  1829. } catch (err) {
  1830. // Ignore while typing
  1831. }
  1832. }
  1833. function toggleWGPrivKeyVisibility() {
  1834. const el = document.getElementById('wg-iface-modal-privkey');
  1835. const btn = document.getElementById('btn-toggle-wg-privkey');
  1836. if (el.type === 'password') {
  1837. el.type = 'text';
  1838. btn.innerText = '🙈 Hide';
  1839. } else {
  1840. el.type = 'password';
  1841. btn.innerText = '👁️ Show';
  1842. }
  1843. }
  1844. function copyWGInterfacePubKey() {
  1845. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1846. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1847. }
  1848. async function submitSaveWGInterface(e) {
  1849. e.preventDefault();
  1850. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1851. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1852. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1853. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1854. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1855. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1856. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1857. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1858. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1859. try {
  1860. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1861. method: 'POST',
  1862. headers: { 'Content-Type': 'application/json' },
  1863. body: JSON.stringify({
  1864. orig_name: origName,
  1865. name,
  1866. listen_port: port,
  1867. address: addr,
  1868. mtu,
  1869. comment,
  1870. public_key: pub,
  1871. private_key: priv,
  1872. disabled
  1873. })
  1874. });
  1875. const data = await res.json();
  1876. if (res.ok) {
  1877. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1878. closeAddWGInterfaceModal();
  1879. loadWireGuard(false);
  1880. fetchData(false);
  1881. } else {
  1882. showToast('Error', data.error || 'Failed to save interface', 'error');
  1883. }
  1884. } catch (err) {
  1885. showToast('Error', err.message, 'error');
  1886. }
  1887. }
  1888. async function startWGInterface(name) {
  1889. try {
  1890. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1891. if (res.ok) {
  1892. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1893. loadWireGuard(false);
  1894. fetchData(false);
  1895. }
  1896. } catch (err) {
  1897. showToast('Error', err.message, 'error');
  1898. }
  1899. }
  1900. async function stopWGInterface(name) {
  1901. try {
  1902. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1903. if (res.ok) {
  1904. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1905. loadWireGuard(false);
  1906. fetchData(false);
  1907. }
  1908. } catch (err) {
  1909. showToast('Error', err.message, 'error');
  1910. }
  1911. }
  1912. async function toggleWGInterfaceState(name, enable) {
  1913. try {
  1914. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1915. method: 'POST',
  1916. headers: { 'Content-Type': 'application/json' },
  1917. body: JSON.stringify({ enabled: enable })
  1918. });
  1919. if (res.ok) {
  1920. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1921. loadWireGuard(false);
  1922. fetchData(false);
  1923. }
  1924. } catch (err) {
  1925. showToast('Error', err.message, 'error');
  1926. }
  1927. }
  1928. async function deleteWGInterface(name) {
  1929. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1930. try {
  1931. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1932. if (res.ok) {
  1933. showToast('Deleted', `Interface ${name} removed`, 'success');
  1934. loadWireGuard(false);
  1935. fetchData(false);
  1936. }
  1937. } catch (err) {
  1938. showToast('Error', err.message, 'error');
  1939. }
  1940. }
  1941. function populateWGPeerIfaceSelect(selectedIface = '') {
  1942. const sel = document.getElementById('wg-peer-modal-iface');
  1943. if (!sel) return;
  1944. sel.innerHTML = '';
  1945. (state.wgInterfaces || []).forEach(i => {
  1946. const opt = document.createElement('option');
  1947. opt.value = i.name;
  1948. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1949. if (i.name === selectedIface) opt.selected = true;
  1950. sel.appendChild(opt);
  1951. });
  1952. }
  1953. function openAddWGPeerModal() {
  1954. if ((state.wgInterfaces || []).length === 0) {
  1955. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1956. openAddWGInterfaceModal();
  1957. return;
  1958. }
  1959. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1960. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1961. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1962. populateWGPeerIfaceSelect();
  1963. document.getElementById('wg-peer-modal-name').value = '';
  1964. document.getElementById('wg-peer-modal-pubkey').value = '';
  1965. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1966. document.getElementById('wg-peer-modal-endpoint').value = '';
  1967. document.getElementById('wg-peer-modal-port').value = '';
  1968. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1969. document.getElementById('wg-peer-modal-preshared').value = '';
  1970. document.getElementById('wg-peer-modal-disabled').checked = false;
  1971. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1972. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1973. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1974. }
  1975. function openEditWGPeerModal(ifaceName, pubKey) {
  1976. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1977. if (!peer) {
  1978. showToast('Not Found', 'Peer not found', 'warning');
  1979. return;
  1980. }
  1981. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1982. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1983. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1984. populateWGPeerIfaceSelect(peer.interface);
  1985. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1986. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1987. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1988. let epHost = (peer.endpoint_address || '').trim();
  1989. let epPort = peer.endpoint_port || '';
  1990. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1991. const lastColon = epHost.lastIndexOf(':');
  1992. const maybePort = epHost.substring(lastColon + 1);
  1993. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1994. if (!epPort) epPort = parseInt(maybePort, 10);
  1995. epHost = epHost.substring(0, lastColon);
  1996. } else {
  1997. break;
  1998. }
  1999. }
  2000. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2001. document.getElementById('wg-peer-modal-port').value = epPort;
  2002. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2003. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2004. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2005. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2006. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2007. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2008. }
  2009. function closeAddWGPeerModal() {
  2010. document.getElementById('wg-peer-modal').classList.add('hidden');
  2011. }
  2012. async function generatePeerKeypairHelper() {
  2013. try {
  2014. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2015. const keys = await res.json();
  2016. if (res.ok) {
  2017. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2018. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2019. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2020. checkWGPeerKeyValidity();
  2021. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2022. }
  2023. } catch (err) {
  2024. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2025. }
  2026. }
  2027. function copyGeneratedPeerPrivKey() {
  2028. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2029. if (priv) copyToClipboard(priv, 'Client Private Key');
  2030. }
  2031. async function generatePeerPSK() {
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2034. const keys = await res.json();
  2035. if (res.ok && keys.private_key) {
  2036. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2037. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2038. }
  2039. } catch (err) {
  2040. showToast('Error', err.message, 'error');
  2041. }
  2042. }
  2043. function checkWGPeerKeyValidity() {
  2044. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2045. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2046. const warningEl = document.getElementById('wg-peer-key-warning');
  2047. if (!warningEl) return;
  2048. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2049. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2050. warningEl.classList.remove('hidden');
  2051. } else {
  2052. warningEl.classList.add('hidden');
  2053. }
  2054. }
  2055. async function submitSaveWGPeer(e) {
  2056. e.preventDefault();
  2057. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2058. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2059. const iface = document.getElementById('wg-peer-modal-iface').value;
  2060. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2061. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2062. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2063. .split(',')
  2064. .map(s => s.trim())
  2065. .filter(s => s.length > 0);
  2066. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2067. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2068. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2069. const lastColon = epHost.lastIndexOf(':');
  2070. const maybePort = epHost.substring(lastColon + 1);
  2071. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2072. if (!epPort) epPort = parseInt(maybePort, 10);
  2073. epHost = epHost.substring(0, lastColon);
  2074. } else {
  2075. break;
  2076. }
  2077. }
  2078. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2079. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2080. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2081. // Validation
  2082. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2083. if (targetIface && targetIface.public_key === pub) {
  2084. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2085. return;
  2086. }
  2087. try {
  2088. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2089. method: 'POST',
  2090. headers: { 'Content-Type': 'application/json' },
  2091. body: JSON.stringify({
  2092. orig_interface: origIface,
  2093. orig_public_key: origPubKey,
  2094. interface: iface,
  2095. name,
  2096. public_key: pub,
  2097. allowed_ips: allowed,
  2098. endpoint_address: epHost,
  2099. endpoint_port: epPort,
  2100. persistent_keepalive: keepalive,
  2101. preshared_key: psk,
  2102. disabled
  2103. })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2108. closeAddWGPeerModal();
  2109. loadWireGuard(false);
  2110. } else {
  2111. showToast('Error', data.error || 'Failed to save peer', 'error');
  2112. }
  2113. } catch (err) {
  2114. showToast('Error', err.message, 'error');
  2115. }
  2116. }
  2117. async function toggleWGPeerState(iface, pubkey, enable) {
  2118. try {
  2119. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2120. method: 'POST',
  2121. headers: { 'Content-Type': 'application/json' },
  2122. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2123. });
  2124. const data = await res.json();
  2125. if (res.ok) {
  2126. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2127. loadWireGuard(false);
  2128. } else {
  2129. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2130. }
  2131. } catch (err) {
  2132. showToast('Error', err.message, 'error');
  2133. }
  2134. }
  2135. async function deleteWGPeer(iface, pubkey) {
  2136. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2137. try {
  2138. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2139. method: 'POST',
  2140. headers: { 'Content-Type': 'application/json' },
  2141. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2142. });
  2143. const data = await res.json();
  2144. if (res.ok) {
  2145. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2146. loadWireGuard(false);
  2147. } else {
  2148. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2149. }
  2150. } catch (err) {
  2151. showToast('Error', err.message, 'error');
  2152. }
  2153. }
  2154. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2155. function switchIpsecModalTab(tab) {
  2156. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2157. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2158. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2159. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2160. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2161. if (tab === 'p1') {
  2162. if (p1Tab) {
  2163. 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';
  2164. }
  2165. if (p2Tab) {
  2166. 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';
  2167. }
  2168. if (p1Content) p1Content.classList.remove('hidden');
  2169. if (p2Content) p2Content.classList.add('hidden');
  2170. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2171. } else {
  2172. if (p1Tab) {
  2173. 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';
  2174. }
  2175. if (p2Tab) {
  2176. 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';
  2177. }
  2178. if (p1Content) p1Content.classList.add('hidden');
  2179. if (p2Content) p2Content.classList.remove('hidden');
  2180. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2181. }
  2182. }
  2183. function toggleIpsecPhaseStep() {
  2184. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2185. if (p1Content && !p1Content.classList.contains('hidden')) {
  2186. switchIpsecModalTab('p2');
  2187. } else {
  2188. switchIpsecModalTab('p1');
  2189. }
  2190. }
  2191. function toggleIpsecPskVisibility() {
  2192. const pskInput = document.getElementById('ipsec-modal-psk');
  2193. if (!pskInput) return;
  2194. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2195. }
  2196. function addIpsecLocalSubnet(val = '') {
  2197. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2198. if (!container) return;
  2199. const row = document.createElement('div');
  2200. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2201. row.innerHTML = `
  2202. <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">
  2203. <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>
  2204. `;
  2205. container.appendChild(row);
  2206. }
  2207. function addIpsecRemoteSubnet(val = '') {
  2208. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2209. if (!container) return;
  2210. const row = document.createElement('div');
  2211. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2212. row.innerHTML = `
  2213. <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">
  2214. <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>
  2215. `;
  2216. container.appendChild(row);
  2217. }
  2218. function updateIpsecEspProposalFromPFS(val) {
  2219. const prop = document.getElementById('ipsec-modal-espprop');
  2220. if (!prop) return;
  2221. if (val === 'none') {
  2222. prop.value = 'aes256-sha256,aes128-sha256,default';
  2223. } else {
  2224. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2225. }
  2226. }
  2227. function updateIpsecIkeProposalFromDH(dh) {
  2228. const el = document.getElementById('ipsec-modal-ikeprop');
  2229. if (el) {
  2230. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2231. }
  2232. }
  2233. function safeSetVal(id, val) {
  2234. const el = document.getElementById(id);
  2235. if (el) el.value = val;
  2236. }
  2237. function safeSetChecked(id, val) {
  2238. const el = document.getElementById(id);
  2239. if (el) el.checked = !!val;
  2240. }
  2241. function safeGetVal(id, def = '') {
  2242. const el = document.getElementById(id);
  2243. return el ? el.value : def;
  2244. }
  2245. async function loadIPSec(populateInputs = true) {
  2246. try {
  2247. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2248. const list = await res.json();
  2249. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2250. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2251. const badge = document.getElementById('ipsec-sas-badge');
  2252. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2253. const tbody = document.getElementById('ipsec-table-body');
  2254. const empty = document.getElementById('ipsec-empty');
  2255. if (!tbody) return;
  2256. tbody.innerHTML = '';
  2257. if (state.ipsecTunnels.length === 0) {
  2258. if (empty) empty.classList.remove('hidden');
  2259. } else {
  2260. if (empty) empty.classList.add('hidden');
  2261. state.ipsecTunnels.forEach(c => {
  2262. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2263. const tr = document.createElement('tr');
  2264. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2265. // Local subnets tags
  2266. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2267. 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('');
  2268. // Remote subnets tags
  2269. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2270. 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('');
  2271. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2272. const p2Name = c.phase2_name || `${c.name}_p2`;
  2273. tr.innerHTML = `
  2274. <td class="py-2.5 px-3 text-center">
  2275. ${isEstablished ? `
  2276. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2277. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2278. <span>UP</span>
  2279. </span>
  2280. ` : (c.disabled ? `
  2281. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2282. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2283. <span>DOWN</span>
  2284. </span>
  2285. ` : `
  2286. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2287. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2288. <span>IDLE</span>
  2289. </span>
  2290. `)}
  2291. </td>
  2292. <td class="py-2.5 px-4 font-bold text-white">
  2293. <div class="flex items-center gap-2">
  2294. <span class="text-amber-400">🛡</span>
  2295. <div>
  2296. <div>${escapeHtml(c.name)}</div>
  2297. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2298. </div>
  2299. </div>
  2300. </td>
  2301. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2302. <td class="py-2.5 px-4 font-sans">
  2303. <div class="flex items-center gap-1.5">
  2304. <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>
  2305. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2306. </div>
  2307. </td>
  2308. <td class="py-2.5 px-4">
  2309. <div class="space-y-1">
  2310. <div class="flex items-center flex-wrap gap-1">
  2311. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2312. ${localBadges}
  2313. </div>
  2314. <div class="flex items-center flex-wrap gap-1">
  2315. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2316. ${remoteBadges}
  2317. </div>
  2318. </div>
  2319. </td>
  2320. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2321. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2322. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2323. </div>
  2324. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2325. </td>
  2326. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2327. ${isEstablished ? `
  2328. <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>
  2329. ` : `
  2330. <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>
  2331. `}
  2332. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2333. ${c.disabled ? 'Enable' : 'Disable'}
  2334. </button>
  2335. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2336. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2337. </td>
  2338. `;
  2339. tbody.appendChild(tr);
  2340. });
  2341. }
  2342. } catch (err) {
  2343. console.error('Failed to load IPSec:', err);
  2344. }
  2345. }
  2346. function openAddIPSecModal() {
  2347. const modal = document.getElementById('ipsec-modal');
  2348. if (!modal) return;
  2349. const title = document.getElementById('ipsec-modal-title');
  2350. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2351. // Phase 1 Fields
  2352. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2353. const nameEl = document.getElementById('ipsec-modal-name');
  2354. if (nameEl) nameEl.readOnly = false;
  2355. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2356. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2357. safeSetVal('ipsec-modal-remotegw', '');
  2358. safeSetVal('ipsec-modal-localaddrs', '');
  2359. safeSetVal('ipsec-modal-comments', '');
  2360. safeSetVal('ipsec-modal-psk', '');
  2361. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2362. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2363. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2364. safeSetVal('ipsec-modal-localid', '');
  2365. safeSetVal('ipsec-modal-remoteid', '');
  2366. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2367. // Phase 2 Fields
  2368. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2369. safeSetVal('ipsec-modal-espkeylife', '28800');
  2370. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2371. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2372. safeSetChecked('ipsec-modal-autostart', true);
  2373. safeSetChecked('ipsec-modal-disabled', false);
  2374. // Clear & Populate default dynamic subnets
  2375. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2376. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2377. if (localContainer) {
  2378. localContainer.innerHTML = '';
  2379. addIpsecLocalSubnet('192.168.10.0/24');
  2380. }
  2381. if (remoteContainer) {
  2382. remoteContainer.innerHTML = '';
  2383. addIpsecRemoteSubnet('192.168.20.0/24');
  2384. }
  2385. switchIpsecModalTab('p1');
  2386. modal.classList.remove('hidden');
  2387. }
  2388. function openEditIPSecModal(name) {
  2389. const modal = document.getElementById('ipsec-modal');
  2390. if (!modal) return;
  2391. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2392. if (!conn) return;
  2393. const title = document.getElementById('ipsec-modal-title');
  2394. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2395. // Phase 1 Fields
  2396. safeSetVal('ipsec-modal-name', conn.name);
  2397. const nameEl = document.getElementById('ipsec-modal-name');
  2398. if (nameEl) nameEl.readOnly = true;
  2399. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2400. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2401. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2402. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2403. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2404. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2405. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2406. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2407. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2408. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2409. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2410. // Phase 2 Fields
  2411. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2412. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2413. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2414. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2415. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2416. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2417. // Populate dynamic subnets
  2418. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2419. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2420. if (localContainer) {
  2421. localContainer.innerHTML = '';
  2422. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2423. locals.forEach(s => addIpsecLocalSubnet(s));
  2424. }
  2425. if (remoteContainer) {
  2426. remoteContainer.innerHTML = '';
  2427. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2428. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2429. }
  2430. switchIpsecModalTab('p1');
  2431. modal.classList.remove('hidden');
  2432. }
  2433. function closeAddIPSecModal() {
  2434. const modal = document.getElementById('ipsec-modal');
  2435. if (modal) modal.classList.add('hidden');
  2436. }
  2437. async function submitSaveIPSec(e) {
  2438. if (e) e.preventDefault();
  2439. const name = safeGetVal('ipsec-modal-name').trim();
  2440. if (!name) {
  2441. showToast('Error', 'Tunnel name is required', 'error');
  2442. return;
  2443. }
  2444. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2445. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2446. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2447. const comments = safeGetVal('ipsec-modal-comments').trim();
  2448. const psk = safeGetVal('ipsec-modal-psk');
  2449. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2450. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2451. const localId = safeGetVal('ipsec-modal-localid').trim();
  2452. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2453. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2454. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2455. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2456. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2457. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2458. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2459. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2460. // Scrape dynamic local and remote subnets
  2461. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2462. const localSubnets = [];
  2463. localInputs.forEach(inp => {
  2464. const v = inp.value.trim();
  2465. if (v) localSubnets.push(v);
  2466. });
  2467. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2468. const remoteSubnets = [];
  2469. remoteInputs.forEach(inp => {
  2470. const v = inp.value.trim();
  2471. if (v) remoteSubnets.push(v);
  2472. });
  2473. try {
  2474. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2475. method: 'POST',
  2476. headers: { 'Content-Type': 'application/json' },
  2477. body: JSON.stringify({
  2478. name,
  2479. comment: comments,
  2480. ike_version: ikeVersion,
  2481. local_addrs: localAddrs,
  2482. remote_addrs: remotegw,
  2483. preshared_key: psk,
  2484. ike_proposals: ikeProposals,
  2485. ike_keylife: ikeKeylife,
  2486. local_id: localId,
  2487. remote_id: remoteId,
  2488. dpd: dpd,
  2489. phase2_name: phase2Name,
  2490. esp_proposals: espProposals,
  2491. esp_keylife: espKeylife,
  2492. pfs_group: pfsGroup,
  2493. pfs: pfsGroup !== 'none',
  2494. local_subnets: localSubnets,
  2495. remote_subnets: remoteSubnets,
  2496. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2497. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2498. auto_start: autostart,
  2499. disabled
  2500. })
  2501. });
  2502. if (res.ok) {
  2503. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2504. closeAddIPSecModal();
  2505. loadIPSec(false);
  2506. } else {
  2507. const err = await res.json();
  2508. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2509. }
  2510. } catch (err) {
  2511. showToast('Error', err.message, 'error');
  2512. }
  2513. }
  2514. async function startIPSecTunnel(name) {
  2515. try {
  2516. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2517. if (res.ok) {
  2518. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2519. setTimeout(() => loadIPSec(false), 2000);
  2520. }
  2521. } catch (err) {
  2522. showToast('Error', err.message, 'error');
  2523. }
  2524. }
  2525. async function stopIPSecTunnel(name) {
  2526. try {
  2527. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2528. if (res.ok) {
  2529. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2530. loadIPSec(false);
  2531. }
  2532. } catch (err) {
  2533. showToast('Error', err.message, 'error');
  2534. }
  2535. }
  2536. async function toggleIPSecState(name, enable) {
  2537. try {
  2538. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2539. method: 'POST',
  2540. headers: { 'Content-Type': 'application/json' },
  2541. body: JSON.stringify({ enabled: enable })
  2542. });
  2543. if (res.ok) {
  2544. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2545. loadIPSec(false);
  2546. }
  2547. } catch (err) {
  2548. showToast('Error', err.message, 'error');
  2549. }
  2550. }
  2551. async function deleteIPSecConn(name) {
  2552. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2553. try {
  2554. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2555. if (res.ok) {
  2556. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2557. loadIPSec(false);
  2558. fetchData(false);
  2559. }
  2560. } catch (err) {
  2561. showToast('Error', err.message, 'error');
  2562. }
  2563. }
  2564. // ======================== L2TP Multi-Instance ========================
  2565. async function loadL2TP(populateInputs = true) {
  2566. try {
  2567. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2568. await fetchPPPProfilesList();
  2569. }
  2570. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2571. const list = await res.json();
  2572. state.l2tpList = Array.isArray(list) ? list : [];
  2573. const badge = document.getElementById('l2tp-count-badge');
  2574. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2575. const tbody = document.getElementById('l2tp-table-body');
  2576. const empty = document.getElementById('l2tp-empty');
  2577. if (!tbody) return;
  2578. tbody.innerHTML = '';
  2579. if (state.l2tpList.length === 0) {
  2580. if (empty) empty.classList.remove('hidden');
  2581. } else {
  2582. if (empty) empty.classList.add('hidden');
  2583. state.l2tpList.forEach(inst => {
  2584. const tr = document.createElement('tr');
  2585. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2586. tr.innerHTML = `
  2587. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2588. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2589. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2590. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2591. <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>
  2592. <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>
  2593. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2594. <td class="py-2.5 px-3 text-center">
  2595. <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'}">
  2596. ${inst.default_route ? 'Yes' : 'No'}
  2597. </span>
  2598. </td>
  2599. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2600. ${inst.running ? `
  2601. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2602. ` : `
  2603. <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>
  2604. `}
  2605. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2606. ${inst.disabled ? 'Enable' : 'Disable'}
  2607. </button>
  2608. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2609. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2610. </td>
  2611. `;
  2612. tbody.appendChild(tr);
  2613. });
  2614. }
  2615. } catch (err) {
  2616. console.error('Failed to load L2TP:', err);
  2617. }
  2618. }
  2619. async function openAddL2TPModal() {
  2620. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2621. await fetchPPPProfilesList();
  2622. }
  2623. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2624. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2625. document.getElementById('l2tp-modal-name').readOnly = false;
  2626. document.getElementById('l2tp-modal-server').value = '';
  2627. document.getElementById('l2tp-modal-user').value = '';
  2628. document.getElementById('l2tp-modal-pass').value = '';
  2629. document.getElementById('l2tp-modal-ipsec').value = '';
  2630. document.getElementById('l2tp-modal-defroute').checked = true;
  2631. document.getElementById('l2tp-modal-disabled').checked = false;
  2632. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2633. document.getElementById('l2tp-modal').classList.remove('hidden');
  2634. }
  2635. async function openEditL2TPModal(name) {
  2636. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2637. await fetchPPPProfilesList();
  2638. }
  2639. const inst = (state.l2tpList || []).find(i => i.name === name);
  2640. if (!inst) return;
  2641. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2642. document.getElementById('l2tp-modal-name').value = inst.name;
  2643. document.getElementById('l2tp-modal-name').readOnly = true;
  2644. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2645. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2646. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2647. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2648. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2649. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2650. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2651. document.getElementById('l2tp-modal').classList.remove('hidden');
  2652. }
  2653. function closeL2TPModal() {
  2654. document.getElementById('l2tp-modal').classList.add('hidden');
  2655. }
  2656. async function submitSaveL2TP(e) {
  2657. e.preventDefault();
  2658. const name = document.getElementById('l2tp-modal-name').value.trim();
  2659. const server = document.getElementById('l2tp-modal-server').value.trim();
  2660. const user = document.getElementById('l2tp-modal-user').value.trim();
  2661. const pass = document.getElementById('l2tp-modal-pass').value;
  2662. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2663. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2664. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2665. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2666. try {
  2667. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2668. method: 'POST',
  2669. headers: { 'Content-Type': 'application/json' },
  2670. body: JSON.stringify({
  2671. name,
  2672. connect_to: server,
  2673. username: user,
  2674. password: pass,
  2675. profile: profile,
  2676. ipsec_secret: ipsec,
  2677. default_route: defRoute,
  2678. disabled
  2679. })
  2680. });
  2681. if (res.ok) {
  2682. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2683. closeL2TPModal();
  2684. loadL2TP(false);
  2685. fetchData(false);
  2686. }
  2687. } catch (err) {
  2688. showToast('Error', err.message, 'error');
  2689. }
  2690. }
  2691. async function connectL2TPInstance(name) {
  2692. try {
  2693. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2694. if (res.ok) {
  2695. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2696. setTimeout(() => loadL2TP(false), 2000);
  2697. }
  2698. } catch (err) {
  2699. showToast('Error', err.message, 'error');
  2700. }
  2701. }
  2702. async function disconnectL2TPInstance(name) {
  2703. try {
  2704. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2705. if (res.ok) {
  2706. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2707. loadL2TP(false);
  2708. }
  2709. } catch (err) {
  2710. showToast('Error', err.message, 'error');
  2711. }
  2712. }
  2713. async function toggleL2TPState(name, enable) {
  2714. try {
  2715. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2716. method: 'POST',
  2717. headers: { 'Content-Type': 'application/json' },
  2718. body: JSON.stringify({ enabled: enable })
  2719. });
  2720. if (res.ok) {
  2721. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2722. loadL2TP(false);
  2723. }
  2724. } catch (err) {
  2725. showToast('Error', err.message, 'error');
  2726. }
  2727. }
  2728. async function deleteL2TPInstance(name) {
  2729. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2730. try {
  2731. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2732. if (res.ok) {
  2733. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2734. loadL2TP(false);
  2735. fetchData(false);
  2736. }
  2737. } catch (err) {
  2738. showToast('Error', err.message, 'error');
  2739. }
  2740. }
  2741. // ======================== PPTP Multi-Instance ========================
  2742. async function loadPPTP(populateInputs = true) {
  2743. try {
  2744. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2745. await fetchPPPProfilesList();
  2746. }
  2747. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2748. const list = await res.json();
  2749. state.pptpList = Array.isArray(list) ? list : [];
  2750. const badge = document.getElementById('pptp-count-badge');
  2751. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2752. const tbody = document.getElementById('pptp-table-body');
  2753. const empty = document.getElementById('pptp-empty');
  2754. if (!tbody) return;
  2755. tbody.innerHTML = '';
  2756. if (state.pptpList.length === 0) {
  2757. if (empty) empty.classList.remove('hidden');
  2758. } else {
  2759. if (empty) empty.classList.add('hidden');
  2760. state.pptpList.forEach(inst => {
  2761. const tr = document.createElement('tr');
  2762. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2763. tr.innerHTML = `
  2764. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2765. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2766. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2767. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2768. <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>
  2769. <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>
  2770. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2771. <td class="py-2.5 px-3 text-center">
  2772. <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'}">
  2773. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2774. </span>
  2775. </td>
  2776. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2777. ${inst.running ? `
  2778. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2779. ` : `
  2780. <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>
  2781. `}
  2782. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2783. ${inst.disabled ? 'Enable' : 'Disable'}
  2784. </button>
  2785. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2786. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2787. </td>
  2788. `;
  2789. tbody.appendChild(tr);
  2790. });
  2791. }
  2792. } catch (err) {
  2793. console.error('Failed to load PPTP:', err);
  2794. }
  2795. }
  2796. async function openAddPPTPModal() {
  2797. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2798. await fetchPPPProfilesList();
  2799. }
  2800. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2801. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2802. document.getElementById('pptp-modal-name').readOnly = false;
  2803. document.getElementById('pptp-modal-server').value = '';
  2804. document.getElementById('pptp-modal-user').value = '';
  2805. document.getElementById('pptp-modal-pass').value = '';
  2806. document.getElementById('pptp-modal-mppe').checked = true;
  2807. document.getElementById('pptp-modal-defroute').checked = true;
  2808. document.getElementById('pptp-modal-disabled').checked = false;
  2809. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2810. document.getElementById('pptp-modal').classList.remove('hidden');
  2811. }
  2812. async function openEditPPTPModal(name) {
  2813. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2814. await fetchPPPProfilesList();
  2815. }
  2816. const inst = (state.pptpList || []).find(i => i.name === name);
  2817. if (!inst) return;
  2818. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2819. document.getElementById('pptp-modal-name').value = inst.name;
  2820. document.getElementById('pptp-modal-name').readOnly = true;
  2821. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2822. document.getElementById('pptp-modal-user').value = inst.username || '';
  2823. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2824. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2825. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2826. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2827. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2828. document.getElementById('pptp-modal').classList.remove('hidden');
  2829. }
  2830. function closePPTPModal() {
  2831. document.getElementById('pptp-modal').classList.add('hidden');
  2832. }
  2833. async function submitSavePPTP(e) {
  2834. e.preventDefault();
  2835. const name = document.getElementById('pptp-modal-name').value.trim();
  2836. const server = document.getElementById('pptp-modal-server').value.trim();
  2837. const user = document.getElementById('pptp-modal-user').value.trim();
  2838. const pass = document.getElementById('pptp-modal-pass').value;
  2839. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2840. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2841. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2842. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2843. try {
  2844. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2845. method: 'POST',
  2846. headers: { 'Content-Type': 'application/json' },
  2847. body: JSON.stringify({
  2848. name,
  2849. connect_to: server,
  2850. username: user,
  2851. password: pass,
  2852. profile: profile,
  2853. require_mppe: mppe,
  2854. default_route: defRoute,
  2855. auto_reconnect: true,
  2856. disabled
  2857. })
  2858. });
  2859. if (res.ok) {
  2860. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2861. closePPTPModal();
  2862. loadPPTP(false);
  2863. fetchData(false);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function connectPPTPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2874. setTimeout(() => loadPPTP(false), 2000);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function disconnectPPTPInstance(name) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2883. if (res.ok) {
  2884. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2885. loadPPTP(false);
  2886. }
  2887. } catch (err) {
  2888. showToast('Error', err.message, 'error');
  2889. }
  2890. }
  2891. async function togglePPTPState(name, enable) {
  2892. try {
  2893. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2894. method: 'POST',
  2895. headers: { 'Content-Type': 'application/json' },
  2896. body: JSON.stringify({ enabled: enable })
  2897. });
  2898. if (res.ok) {
  2899. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2900. loadPPTP(false);
  2901. }
  2902. } catch (err) {
  2903. showToast('Error', err.message, 'error');
  2904. }
  2905. }
  2906. async function deletePPTPInstance(name) {
  2907. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2908. try {
  2909. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2910. if (res.ok) {
  2911. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2912. loadPPTP(false);
  2913. fetchData(false);
  2914. }
  2915. } catch (err) {
  2916. showToast('Error', err.message, 'error');
  2917. }
  2918. }
  2919. // ---------------- Modal & Helper Functions ----------------
  2920. function openVlanModal(defaultParent = '') {
  2921. const select = document.getElementById('vlan-parent');
  2922. select.innerHTML = '';
  2923. const allIfaces = state.interfaces || [];
  2924. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2925. if (eligible.length === 0) {
  2926. const opt = document.createElement('option');
  2927. opt.value = '';
  2928. opt.innerText = 'No VLAN-capable interfaces available';
  2929. select.appendChild(opt);
  2930. } else {
  2931. eligible.forEach(i => {
  2932. const opt = document.createElement('option');
  2933. opt.value = i.name;
  2934. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2935. if (i.name === defaultParent) opt.selected = true;
  2936. select.appendChild(opt);
  2937. });
  2938. }
  2939. document.getElementById('vlan-id').value = '';
  2940. document.getElementById('vlan-name').value = '';
  2941. document.getElementById('vlan-ip').value = '';
  2942. document.getElementById('vlan-desc').value = '';
  2943. populateRoleSelects('LAN');
  2944. autoSuggestVlanName();
  2945. document.getElementById('vlan-modal').classList.remove('hidden');
  2946. }
  2947. function closeVlanModal() {
  2948. document.getElementById('vlan-modal').classList.add('hidden');
  2949. }
  2950. function autoSuggestVlanName() {
  2951. const parent = document.getElementById('vlan-parent').value;
  2952. if (!parent) return;
  2953. const id = document.getElementById('vlan-id').value;
  2954. const nameInput = document.getElementById('vlan-name');
  2955. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2956. }
  2957. function setSubnetPreset(cidr) {
  2958. const ipInput = document.getElementById('vlan-ip');
  2959. const id = document.getElementById('vlan-id').value || '10';
  2960. ipInput.value = `192.168.${id}.1${cidr}`;
  2961. }
  2962. async function submitCreateVlan(e) {
  2963. e.preventDefault();
  2964. const btn = document.getElementById('vlan-submit-btn');
  2965. btn.disabled = true;
  2966. btn.innerText = 'Creating...';
  2967. const parent = document.getElementById('vlan-parent').value;
  2968. if (!parent) {
  2969. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2970. btn.disabled = false;
  2971. btn.innerText = 'Create VLAN';
  2972. return;
  2973. }
  2974. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2975. const name = document.getElementById('vlan-name').value.trim();
  2976. const ip = document.getElementById('vlan-ip').value.trim();
  2977. const role = document.getElementById('vlan-role').value;
  2978. const desc = document.getElementById('vlan-desc').value.trim();
  2979. try {
  2980. const res = await fetch(`${API_BASE}/vlans`, {
  2981. method: 'POST',
  2982. headers: { 'Content-Type': 'application/json' },
  2983. body: JSON.stringify({
  2984. parent_name: parent,
  2985. vlan_id: id,
  2986. name: name,
  2987. ip_address: ip,
  2988. role: role,
  2989. description: desc,
  2990. mtu: 1500,
  2991. auto_up: true
  2992. })
  2993. });
  2994. const data = await res.json();
  2995. if (res.ok) {
  2996. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2997. state.expandedParents.add(parent);
  2998. closeVlanModal();
  2999. await fetchData(true);
  3000. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3001. } else {
  3002. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3003. }
  3004. } catch (err) {
  3005. showToast('Error', err.message, 'error');
  3006. } finally {
  3007. btn.disabled = false;
  3008. btn.innerText = 'Create VLAN';
  3009. }
  3010. }
  3011. async function confirmDeleteVlan(name) {
  3012. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3013. try {
  3014. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3015. if (res.ok) {
  3016. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3017. closeIfaceModal();
  3018. fetchData(true);
  3019. }
  3020. } catch (err) {
  3021. showToast('Error', err.message, 'error');
  3022. }
  3023. }
  3024. function openIfaceModal(name) {
  3025. const iface = (state.interfaces || []).find(i => i.name === name);
  3026. if (!iface) return;
  3027. state.currentModalIface = iface.name;
  3028. document.getElementById('modal-iface-name').innerText = iface.name;
  3029. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3030. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3031. populateRoleSelects(iface.role || 'LAN');
  3032. document.getElementById('modal-iface-desc').value = iface.description || '';
  3033. const nameInput = document.getElementById('modal-iface-new-name');
  3034. const renameBtn = document.getElementById('modal-btn-rename');
  3035. const renameHelp = document.getElementById('modal-iface-rename-help');
  3036. if (nameInput) {
  3037. nameInput.value = iface.name;
  3038. if (iface.name === 'lo' || iface.type === 'loopback') {
  3039. nameInput.disabled = true;
  3040. if (renameBtn) renameBtn.disabled = true;
  3041. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3042. } else {
  3043. nameInput.disabled = false;
  3044. if (renameBtn) renameBtn.disabled = false;
  3045. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3046. }
  3047. }
  3048. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3049. if (iface.is_vlan) {
  3050. delBtn.classList.remove('hidden');
  3051. } else {
  3052. delBtn.classList.add('hidden');
  3053. }
  3054. renderModalIPs(iface);
  3055. document.getElementById('iface-modal').classList.remove('hidden');
  3056. }
  3057. function renderModalIPs(iface) {
  3058. const container = document.getElementById('modal-ip-list');
  3059. container.innerHTML = '';
  3060. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3061. if (addrs.length === 0) {
  3062. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3063. return;
  3064. }
  3065. addrs.forEach(addr => {
  3066. const row = document.createElement('div');
  3067. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3068. row.innerHTML = `
  3069. <span class="text-white">${addr}</span>
  3070. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3071. `;
  3072. container.appendChild(row);
  3073. });
  3074. }
  3075. function closeIfaceModal() {
  3076. document.getElementById('iface-modal').classList.add('hidden');
  3077. state.currentModalIface = null;
  3078. }
  3079. async function setIfaceState(name, newState) {
  3080. const target = name || state.currentModalIface;
  3081. if (!target) return;
  3082. await toggleInterfaceState(target, newState);
  3083. const updated = (state.interfaces || []).find(i => i.name === target);
  3084. if (updated) openIfaceModal(target);
  3085. }
  3086. async function applyMTU() {
  3087. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3088. try {
  3089. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3090. method: 'POST',
  3091. headers: { 'Content-Type': 'application/json' },
  3092. body: JSON.stringify({ mtu })
  3093. });
  3094. if (res.ok) {
  3095. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3096. fetchData(false);
  3097. }
  3098. } catch (err) {
  3099. showToast('Error', err.message, 'error');
  3100. }
  3101. }
  3102. async function addInterfaceIP() {
  3103. const ip = document.getElementById('modal-new-ip').value.trim();
  3104. if (!ip) return;
  3105. try {
  3106. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3107. method: 'POST',
  3108. headers: { 'Content-Type': 'application/json' },
  3109. body: JSON.stringify({ ip })
  3110. });
  3111. if (res.ok) {
  3112. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3113. document.getElementById('modal-new-ip').value = '';
  3114. await fetchData(false);
  3115. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3116. if (iface) renderModalIPs(iface);
  3117. } else {
  3118. const err = await res.json();
  3119. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3120. }
  3121. } catch (err) {
  3122. showToast('Error', err.message, 'error');
  3123. }
  3124. }
  3125. async function removeInterfaceIP(ip) {
  3126. if (!confirm(`Remove IP ${ip}?`)) return;
  3127. try {
  3128. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3129. method: 'DELETE',
  3130. headers: { 'Content-Type': 'application/json' },
  3131. body: JSON.stringify({ ip })
  3132. });
  3133. if (res.ok) {
  3134. showToast('IP Removed', `Removed ${ip}`, 'success');
  3135. await fetchData(false);
  3136. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3137. if (iface) renderModalIPs(iface);
  3138. }
  3139. } catch (err) {
  3140. showToast('Error', err.message, 'error');
  3141. }
  3142. }
  3143. async function renameInterface() {
  3144. const oldName = state.currentModalIface;
  3145. const newNameInput = document.getElementById('modal-iface-new-name');
  3146. const newName = (newNameInput?.value || '').trim();
  3147. if (!oldName) return;
  3148. if (!newName) {
  3149. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3150. return;
  3151. }
  3152. if (newName === oldName) {
  3153. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3154. return;
  3155. }
  3156. if (newName.length > 15) {
  3157. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3158. return;
  3159. }
  3160. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3161. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3162. return;
  3163. }
  3164. const renameBtn = document.getElementById('modal-btn-rename');
  3165. if (renameBtn) {
  3166. renameBtn.disabled = true;
  3167. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3168. }
  3169. try {
  3170. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3171. method: 'POST',
  3172. headers: { 'Content-Type': 'application/json' },
  3173. body: JSON.stringify({ new_name: newName })
  3174. });
  3175. const data = await res.json();
  3176. if (!res.ok) {
  3177. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3178. return;
  3179. }
  3180. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3181. state.currentModalIface = newName;
  3182. document.getElementById('modal-iface-name').innerText = newName;
  3183. // Refresh application state
  3184. await fetchData(false);
  3185. const updated = (state.interfaces || []).find(i => i.name === newName);
  3186. if (updated) {
  3187. openIfaceModal(newName);
  3188. } else {
  3189. closeIfaceModal();
  3190. }
  3191. } catch (err) {
  3192. showToast('Error', err.message, 'error');
  3193. } finally {
  3194. if (renameBtn) {
  3195. renameBtn.disabled = false;
  3196. renameBtn.innerHTML = `
  3197. <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>
  3198. <span>Rename</span>
  3199. `;
  3200. }
  3201. }
  3202. }
  3203. async function saveInterfaceMetadata() {
  3204. const oldName = state.currentModalIface;
  3205. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3206. const role = document.getElementById('modal-iface-role').value;
  3207. const desc = document.getElementById('modal-iface-desc').value.trim();
  3208. let targetName = oldName;
  3209. // If user changed the name before clicking Save Changes, execute rename first
  3210. if (newName && newName !== oldName && oldName !== 'lo') {
  3211. try {
  3212. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3213. method: 'POST',
  3214. headers: { 'Content-Type': 'application/json' },
  3215. body: JSON.stringify({ new_name: newName })
  3216. });
  3217. const data = await renameRes.json();
  3218. if (!renameRes.ok) {
  3219. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3220. return;
  3221. }
  3222. targetName = newName;
  3223. state.currentModalIface = newName;
  3224. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3225. } catch (err) {
  3226. showToast('Error', err.message, 'error');
  3227. return;
  3228. }
  3229. }
  3230. try {
  3231. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3232. method: 'POST',
  3233. headers: { 'Content-Type': 'application/json' },
  3234. body: JSON.stringify({ role, description: desc })
  3235. });
  3236. if (res.ok) {
  3237. showToast('Saved', 'Interface configuration updated', 'success');
  3238. closeIfaceModal();
  3239. fetchData(false);
  3240. } else {
  3241. const err = await res.json();
  3242. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3243. }
  3244. } catch (err) {
  3245. showToast('Error', err.message, 'error');
  3246. }
  3247. }
  3248. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3249. state.fwSubTab = 'filter';
  3250. state.routesSubTab = 'routes';
  3251. function renderRuleFlag(disabled, hasComment) {
  3252. let flags = '';
  3253. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3254. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3255. return flags || '<span class="text-slate-600">-</span>';
  3256. }
  3257. function renderActionBadge(action) {
  3258. const act = (action || '').toLowerCase();
  3259. let color = 'bg-slate-800 text-slate-300';
  3260. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3261. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3262. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3263. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3264. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3265. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3266. }
  3267. function switchFWSubTab(tab) {
  3268. state.fwSubTab = tab;
  3269. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3270. tabs.forEach(t => {
  3271. const panel = document.getElementById(`fw-subtab-${t}`);
  3272. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3273. if (panel) {
  3274. if (t === tab) panel.classList.remove('hidden');
  3275. else panel.classList.add('hidden');
  3276. }
  3277. if (btn) {
  3278. if (t === tab) {
  3279. 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';
  3280. } else {
  3281. 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';
  3282. }
  3283. }
  3284. });
  3285. const addBtn = document.getElementById('fw-primary-add-btn');
  3286. if (addBtn) {
  3287. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3288. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3289. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3290. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3291. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3292. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3293. }
  3294. if (tab === 'geo') loadGeoIP();
  3295. if (tab === 'connections') loadConnections();
  3296. setTimeout(initTableSorting, 50);
  3297. }
  3298. function openCurrentFWModal() {
  3299. if (state.fwSubTab === 'filter') openAddFilterModal();
  3300. else if (state.fwSubTab === 'nat') openAddNATModal();
  3301. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3302. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3303. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3304. else if (state.fwSubTab === 'connections') loadConnections();
  3305. }
  3306. async function loadFirewall(populateDropdowns = true) {
  3307. try {
  3308. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3309. fetch(`${API_BASE}/firewall/summary`),
  3310. fetch(`${API_BASE}/firewall/filter`),
  3311. fetch(`${API_BASE}/firewall/nat`),
  3312. fetch(`${API_BASE}/firewall/mangle`),
  3313. fetch(`${API_BASE}/firewall/address-lists`),
  3314. fetch(`${API_BASE}/firewall/geoip/status`),
  3315. fetch(`${API_BASE}/firewall/geoip/countries`)
  3316. ]);
  3317. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3318. if (filterRes.ok) state.filterRules = await filterRes.json();
  3319. if (natRes.ok) state.natRules = await natRes.json();
  3320. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3321. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3322. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3323. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3324. // Badges
  3325. const bFilter = document.getElementById('fw-badge-filter');
  3326. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3327. const bNat = document.getElementById('fw-badge-nat');
  3328. if (bNat) bNat.innerText = (state.natRules || []).length;
  3329. const bMangle = document.getElementById('fw-badge-mangle');
  3330. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3331. const bAddr = document.getElementById('fw-badge-addrlist');
  3332. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3333. const bGeo = document.getElementById('fw-badge-geo');
  3334. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3335. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3336. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3337. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3338. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3339. const tbodyFilter = document.getElementById('filter-rules-table-body');
  3340. if (tbodyFilter && (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter)) {
  3341. tbodyFilter.dataset.sig = sigFilter;
  3342. renderFilterRules();
  3343. }
  3344. const tbodyNat = document.getElementById('nat-rules-table-body');
  3345. if (tbodyNat && (populateDropdowns || tbodyNat.dataset.sig !== sigNat)) {
  3346. tbodyNat.dataset.sig = sigNat;
  3347. renderNATRules();
  3348. }
  3349. const tbodyMangle = document.getElementById('mangle-rules-table-body');
  3350. if (tbodyMangle && (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle)) {
  3351. tbodyMangle.dataset.sig = sigMangle;
  3352. renderMangleRules();
  3353. }
  3354. const tbodyAddr = document.getElementById('addr-list-table-body');
  3355. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3356. tbodyAddr.dataset.sig = sigAddr;
  3357. renderAddressLists();
  3358. }
  3359. renderGeoCountries();
  3360. if (state.fwSubTab === 'connections') {
  3361. loadConnections();
  3362. }
  3363. } catch (err) {
  3364. console.error('Failed to load firewall:', err);
  3365. }
  3366. }
  3367. // ----------------- Filter Rules -----------------
  3368. function renderFilterRules() {
  3369. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3370. const tbody = document.getElementById('filter-table-body');
  3371. const empty = document.getElementById('filter-empty');
  3372. if (!tbody) return;
  3373. tbody.innerHTML = '';
  3374. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3375. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3376. if (rules.length === 0) {
  3377. empty?.classList.remove('hidden');
  3378. return;
  3379. }
  3380. empty?.classList.add('hidden');
  3381. rules.forEach((r, idx) => {
  3382. const tr = document.createElement('tr');
  3383. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3384. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3385. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3386. let actionExtra = '';
  3387. if (r.action === 'reject') {
  3388. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3389. } else if (r.action === 'jump') {
  3390. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3391. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3392. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3393. } else if (r.action === 'log' && r.log_prefix) {
  3394. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3395. }
  3396. tr.innerHTML = `
  3397. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3398. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3399. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3400. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3401. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3402. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3403. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3404. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3405. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3406. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3407. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3408. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3409. </td>
  3410. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3411. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3412. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3413. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3414. <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>
  3415. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3416. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3417. </td>
  3418. `;
  3419. tbody.appendChild(tr);
  3420. });
  3421. }
  3422. function formatTarget(addr, list, geo) {
  3423. const parts = [];
  3424. if (addr) parts.push(`<span>${addr}</span>`);
  3425. if (list) {
  3426. const inv = list.startsWith('!') ? '!' : '';
  3427. const clean = list.replace(/^!/, '');
  3428. 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>`);
  3429. }
  3430. if (geo) {
  3431. const inv = geo.startsWith('!') ? '!' : '';
  3432. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3433. 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>`);
  3434. }
  3435. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3436. return parts.join(' ');
  3437. }
  3438. function populateInterfaceSelect(selectId, currentVal = '') {
  3439. const sel = document.getElementById(selectId);
  3440. if (!sel) return;
  3441. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3442. (state.interfaces || []).forEach(i => {
  3443. const opt = document.createElement('option');
  3444. opt.value = i.name;
  3445. opt.innerText = `${i.name} (${i.role || i.type})`;
  3446. if (i.name === currentVal) opt.selected = true;
  3447. sel.appendChild(opt);
  3448. });
  3449. }
  3450. function populateAddressListSelect(selectId, currentVal = '') {
  3451. const sel = document.getElementById(selectId);
  3452. if (!sel) return;
  3453. sel.innerHTML = '<option value="">(None)</option>';
  3454. const cleanVal = (currentVal || '').replace(/^!/, '');
  3455. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3456. customNames.forEach(name => {
  3457. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3458. const opt = document.createElement('option');
  3459. opt.value = name;
  3460. opt.innerText = `${name} (${count} entries)`;
  3461. if (name === cleanVal) opt.selected = true;
  3462. sel.appendChild(opt);
  3463. });
  3464. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3465. const opt = document.createElement('option');
  3466. opt.value = cleanVal;
  3467. opt.innerText = cleanVal;
  3468. opt.selected = true;
  3469. sel.appendChild(opt);
  3470. }
  3471. populateCommonAddrListDatalist();
  3472. }
  3473. function populateCommonAddrListDatalist() {
  3474. const dl = document.getElementById('fw-addrlist-datalist');
  3475. if (!dl) return;
  3476. dl.innerHTML = '';
  3477. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3478. names.forEach(name => {
  3479. const opt = document.createElement('option');
  3480. opt.value = name;
  3481. dl.appendChild(opt);
  3482. });
  3483. }
  3484. function populateGeoIPSelect(selectId, currentVal = '') {
  3485. const sel = document.getElementById(selectId);
  3486. if (!sel) return;
  3487. sel.innerHTML = '<option value="">(None)</option>';
  3488. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3489. // Presets optgroup
  3490. const grpPresets = document.createElement('optgroup');
  3491. grpPresets.label = '⚡ Regional Presets';
  3492. const presets = [
  3493. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3494. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3495. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3496. ];
  3497. presets.forEach(p => {
  3498. const opt = document.createElement('option');
  3499. opt.value = p.code;
  3500. opt.innerText = p.label;
  3501. if (p.code === cleanVal) opt.selected = true;
  3502. grpPresets.appendChild(opt);
  3503. });
  3504. sel.appendChild(grpPresets);
  3505. // All Countries optgroup
  3506. const grpCountries = document.createElement('optgroup');
  3507. grpCountries.label = '🌍 All Countries';
  3508. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3509. countries.forEach(c => {
  3510. const opt = document.createElement('option');
  3511. opt.value = c.code;
  3512. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3513. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3514. if (c.code === cleanVal) opt.selected = true;
  3515. grpCountries.appendChild(opt);
  3516. });
  3517. sel.appendChild(grpCountries);
  3518. }
  3519. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3520. function switchFwRuleTab(tab) {
  3521. state.activeFwRuleTab = tab;
  3522. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3523. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3524. btn.classList.add('text-slate-400', 'border-transparent');
  3525. });
  3526. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3527. if (activeBtn) {
  3528. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3529. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3530. }
  3531. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3532. const activePane = document.getElementById(`fw-pane-${tab}`);
  3533. if (activePane) activePane.classList.remove('hidden');
  3534. if (tab === 'statistics') {
  3535. startFwStatPolling();
  3536. } else {
  3537. stopFwStatPolling();
  3538. }
  3539. }
  3540. function toggleFwField(fieldKey, expand) {
  3541. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3542. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3543. if (!plusBtn || !fieldBox) return;
  3544. if (expand) {
  3545. plusBtn.classList.add('hidden');
  3546. fieldBox.classList.remove('hidden');
  3547. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3548. if (valInput) valInput.focus();
  3549. } else {
  3550. fieldBox.classList.add('hidden');
  3551. plusBtn.classList.remove('hidden');
  3552. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3553. if (valInput) {
  3554. if (valInput.tagName === 'SELECT') {
  3555. valInput.selectedIndex = 0;
  3556. } else {
  3557. valInput.value = '';
  3558. }
  3559. }
  3560. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3561. if (invInput) invInput.checked = false;
  3562. if (fieldKey === 'cs') {
  3563. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3564. const el = document.getElementById(id);
  3565. if (el) el.checked = false;
  3566. });
  3567. }
  3568. if (fieldKey === 'natstate') {
  3569. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3570. const el = document.getElementById(id);
  3571. if (el) el.checked = false;
  3572. });
  3573. }
  3574. if (fieldKey === 'days') {
  3575. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3576. const el = document.getElementById(`fw-day-${d}`);
  3577. if (el) el.checked = true;
  3578. });
  3579. }
  3580. }
  3581. }
  3582. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3583. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3584. toggleFwField(fieldKey, true);
  3585. let strVal = String(value);
  3586. if (hasInvert) {
  3587. const inv = strVal.startsWith('!');
  3588. if (inv) strVal = strVal.slice(1);
  3589. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3590. if (invEl) invEl.checked = inv;
  3591. }
  3592. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3593. if (valEl) valEl.value = strVal;
  3594. } else {
  3595. toggleFwField(fieldKey, false);
  3596. }
  3597. }
  3598. function getFwFieldVal(fieldKey, hasInvert = false) {
  3599. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3600. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3601. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3602. let v = valEl ? valEl.value.trim() : '';
  3603. if (!v) return '';
  3604. if (hasInvert) {
  3605. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3606. if (invEl && invEl.checked) {
  3607. v = '!' + v.replace(/^!/, '');
  3608. }
  3609. }
  3610. return v;
  3611. }
  3612. function toggleMaximizeFilterModal() {
  3613. const win = document.getElementById('filter-modal-window');
  3614. if (!win) return;
  3615. if (win.classList.contains('max-w-[720px]')) {
  3616. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3617. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3618. } else {
  3619. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3620. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3621. }
  3622. }
  3623. function openAddFilterModal() {
  3624. switchFwRuleTab('general');
  3625. const badge = document.getElementById('fw-modal-badge');
  3626. if (badge) badge.innerText = 'New...';
  3627. document.getElementById('filter-modal-id').value = '';
  3628. document.getElementById('filter-modal-enabled').checked = true;
  3629. document.getElementById('filter-modal-comment').value = '';
  3630. document.getElementById('filter-modal-chain').value = 'forward';
  3631. document.getElementById('filter-modal-action').value = 'accept';
  3632. document.getElementById('filter-modal-log').checked = false;
  3633. populateInterfaceSelect('fw-val-iniface');
  3634. populateInterfaceSelect('fw-val-outiface');
  3635. populateAddressListSelect('fw-val-srclist');
  3636. populateAddressListSelect('fw-val-dstlist');
  3637. populateGeoIPSelect('fw-val-srcgeo');
  3638. populateGeoIPSelect('fw-val-dstgeo');
  3639. const allFieldKeys = [
  3640. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3641. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3642. 'routingmark', 'conntype', 'cs', 'natstate',
  3643. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3644. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3645. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3646. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3647. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3648. ];
  3649. allFieldKeys.forEach(k => toggleFwField(k, false));
  3650. resetCurrentRuleCounters();
  3651. toggleFilterActionFields();
  3652. document.getElementById('filter-modal').classList.remove('hidden');
  3653. }
  3654. function openEditFilterModal(id) {
  3655. const r = (state.filterRules || []).find(rule => rule.id === id);
  3656. if (!r) return;
  3657. switchFwRuleTab('general');
  3658. const badge = document.getElementById('fw-modal-badge');
  3659. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3660. document.getElementById('filter-modal-id').value = r.id;
  3661. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3662. document.getElementById('filter-modal-comment').value = r.comment || '';
  3663. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3664. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3665. document.getElementById('filter-modal-log').checked = !!r.log;
  3666. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3667. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3668. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3669. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3670. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3671. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3672. setFwFieldVal('src', r.src_address, true);
  3673. setFwFieldVal('dst', r.dst_address, true);
  3674. setFwFieldVal('srclist', r.src_address_list, true);
  3675. setFwFieldVal('dstlist', r.dst_address_list, true);
  3676. setFwFieldVal('srcgeo', r.src_geoip, true);
  3677. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3678. if (r.protocol && r.protocol !== 'all') {
  3679. setFwFieldVal('proto', r.protocol, true);
  3680. } else {
  3681. toggleFwField('proto', false);
  3682. }
  3683. setFwFieldVal('sport', r.src_port, true);
  3684. setFwFieldVal('dport', r.dst_port, true);
  3685. setFwFieldVal('anyport', r.any_port, true);
  3686. setFwFieldVal('iniface', r.in_interface, true);
  3687. setFwFieldVal('outiface', r.out_interface, true);
  3688. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3689. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3690. setFwFieldVal('pktmark', r.packet_mark, true);
  3691. setFwFieldVal('connmark', r.connection_mark, true);
  3692. setFwFieldVal('routingmark', r.routing_mark, true);
  3693. setFwFieldVal('conntype', r.connection_type, false);
  3694. const states = r.connection_state || [];
  3695. if (states.length > 0) {
  3696. toggleFwField('cs', true);
  3697. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3698. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3699. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3700. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3701. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3702. } else {
  3703. toggleFwField('cs', false);
  3704. }
  3705. const natStates = r.connection_nat_state || [];
  3706. if (natStates.length > 0) {
  3707. toggleFwField('natstate', true);
  3708. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3709. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3710. } else {
  3711. toggleFwField('natstate', false);
  3712. }
  3713. // Advanced tab fields
  3714. setFwFieldVal('layer7', r.layer7_protocol, false);
  3715. setFwFieldVal('content', r.content, false);
  3716. setFwFieldVal('connbytes', r.connection_bytes, false);
  3717. setFwFieldVal('connrate', r.connection_rate, false);
  3718. setFwFieldVal('pcc', r.pcc, false);
  3719. setFwFieldVal('srcmac', r.src_mac_address, true);
  3720. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3721. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3722. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3723. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3724. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3725. setFwFieldVal('tlshost', r.tls_host, false);
  3726. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3727. setFwFieldVal('priority', r.priority, false);
  3728. setFwFieldVal('dscp', r.dscp, false);
  3729. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3730. if (r.tos) {
  3731. const tosEl = document.getElementById('fw-val-tos');
  3732. if (tosEl) tosEl.value = r.tos;
  3733. }
  3734. setFwFieldVal('pktsize', r.packet_size, false);
  3735. setFwFieldVal('random', r.random, false);
  3736. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3737. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3738. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3739. setFwFieldVal('ttl', r.ttl, false);
  3740. // Extra tab fields
  3741. setFwFieldVal('time', r.time, false);
  3742. if (r.days) {
  3743. toggleFwField('days', true);
  3744. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3745. const chk = document.getElementById(`fw-day-${d}`);
  3746. if (chk) chk.checked = r.days.includes(d);
  3747. });
  3748. } else {
  3749. toggleFwField('days', false);
  3750. }
  3751. setFwFieldVal('limit', r.limit, false);
  3752. setFwFieldVal('dstlimit', r.dst_limit, false);
  3753. setFwFieldVal('psd', r.psd, false);
  3754. // Action fields
  3755. if (r.reject_with) {
  3756. const rwEl = document.getElementById('filter-modal-rejectwith');
  3757. if (rwEl) rwEl.value = r.reject_with;
  3758. }
  3759. if (r.jump_target) {
  3760. const jtEl = document.getElementById('filter-modal-jumptarget');
  3761. if (jtEl) jtEl.value = r.jump_target;
  3762. }
  3763. if (r.address_list) {
  3764. const alEl = document.getElementById('filter-modal-action-addrlist');
  3765. if (alEl) alEl.value = r.address_list;
  3766. }
  3767. if (r.address_list_timeout) {
  3768. const toEl = document.getElementById('filter-modal-action-timeout');
  3769. if (toEl) toEl.value = r.address_list_timeout;
  3770. }
  3771. setFwFieldVal('logprefix', r.log_prefix, false);
  3772. // Statistics
  3773. const bEl = document.getElementById('fw-stat-bytes');
  3774. const pEl = document.getElementById('fw-stat-packets');
  3775. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3776. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3777. state.fwLastBytes = r.bytes || 0;
  3778. state.fwLastPackets = r.packets || 0;
  3779. state.fwLastTimestamp = Date.now();
  3780. state.fwStatRateHistory = new Array(30).fill(0);
  3781. state.fwStatPktHistory = new Array(30).fill(0);
  3782. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3783. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3784. toggleFilterActionFields();
  3785. document.getElementById('filter-modal').classList.remove('hidden');
  3786. }
  3787. function closeFilterModal() {
  3788. stopFwStatPolling();
  3789. document.getElementById('filter-modal').classList.add('hidden');
  3790. }
  3791. function toggleFilterActionFields() {
  3792. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3793. const rejectBox = document.getElementById('filter-action-reject-box');
  3794. const jumpBox = document.getElementById('filter-action-jump-box');
  3795. const addrBox = document.getElementById('filter-action-addrlist-box');
  3796. if (rejectBox) {
  3797. if (act === 'reject') rejectBox.classList.remove('hidden');
  3798. else rejectBox.classList.add('hidden');
  3799. }
  3800. if (jumpBox) {
  3801. if (act === 'jump') jumpBox.classList.remove('hidden');
  3802. else jumpBox.classList.add('hidden');
  3803. }
  3804. if (addrBox) {
  3805. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3806. addrBox.classList.remove('hidden');
  3807. } else {
  3808. addrBox.classList.add('hidden');
  3809. }
  3810. }
  3811. if (act === 'log') {
  3812. const logEl = document.getElementById('filter-modal-log');
  3813. if (logEl) logEl.checked = true;
  3814. toggleFwField('logprefix', true);
  3815. }
  3816. }
  3817. function toggleFwLogPrefix() {
  3818. const isLog = document.getElementById('filter-modal-log')?.checked;
  3819. toggleFwField('logprefix', !!isLog);
  3820. }
  3821. function copyFilterRule() {
  3822. document.getElementById('filter-modal-id').value = '';
  3823. const badge = document.getElementById('fw-modal-badge');
  3824. if (badge) badge.innerText = 'New...';
  3825. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3826. }
  3827. function resetCurrentRuleCounters() {
  3828. state.fwStatRateHistory = new Array(30).fill(0);
  3829. state.fwStatPktHistory = new Array(30).fill(0);
  3830. state.fwLastBytes = 0;
  3831. state.fwLastPackets = 0;
  3832. state.fwLastTimestamp = Date.now();
  3833. const bEl = document.getElementById('fw-stat-bytes');
  3834. const pEl = document.getElementById('fw-stat-packets');
  3835. const rEl = document.getElementById('fw-stat-rate');
  3836. const prEl = document.getElementById('fw-stat-pktrate');
  3837. if (bEl) bEl.value = '0 B';
  3838. if (pEl) pEl.value = '0';
  3839. if (rEl) rEl.value = '0 bps';
  3840. if (prEl) prEl.value = '0 p/s';
  3841. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3842. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3843. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3844. }
  3845. async function resetAllFwCounters() {
  3846. try {
  3847. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3848. if (res.ok) {
  3849. resetCurrentRuleCounters();
  3850. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3851. loadFirewall(false);
  3852. }
  3853. } catch (err) {
  3854. showToast('Error', err.message, 'error');
  3855. }
  3856. }
  3857. async function applyFilterRule(closeAfter = false) {
  3858. const id = document.getElementById('filter-modal-id').value;
  3859. const chain = document.getElementById('filter-modal-chain').value;
  3860. const action = document.getElementById('filter-modal-action').value;
  3861. const comment = document.getElementById('filter-modal-comment').value.trim();
  3862. const enabled = document.getElementById('filter-modal-enabled').checked;
  3863. const src = getFwFieldVal('src', true);
  3864. const dst = getFwFieldVal('dst', true);
  3865. const srclist = getFwFieldVal('srclist', true);
  3866. const dstlist = getFwFieldVal('dstlist', true);
  3867. const srcgeo = getFwFieldVal('srcgeo', true);
  3868. const dstgeo = getFwFieldVal('dstgeo', true);
  3869. const proto = getFwFieldVal('proto', true);
  3870. const sport = getFwFieldVal('sport', true);
  3871. const dport = getFwFieldVal('dport', true);
  3872. const anyport = getFwFieldVal('anyport', true);
  3873. const iniface = getFwFieldVal('iniface', true);
  3874. const outiface = getFwFieldVal('outiface', true);
  3875. const inifacelist = getFwFieldVal('inifacelist', true);
  3876. const outifacelist = getFwFieldVal('outifacelist', true);
  3877. const pktmark = getFwFieldVal('pktmark', true);
  3878. const connmark = getFwFieldVal('connmark', true);
  3879. const routingmark = getFwFieldVal('routingmark', true);
  3880. const conntype = getFwFieldVal('conntype', false);
  3881. const states = [];
  3882. const csBox = document.getElementById('fw-field-cs');
  3883. if (csBox && !csBox.classList.contains('hidden')) {
  3884. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3885. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3886. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3887. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3888. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3889. }
  3890. const natStates = [];
  3891. const natBox = document.getElementById('fw-field-natstate');
  3892. if (natBox && !natBox.classList.contains('hidden')) {
  3893. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3894. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3895. }
  3896. const payload = {
  3897. id,
  3898. chain,
  3899. action,
  3900. protocol: proto || 'all',
  3901. src_address: src,
  3902. dst_address: dst,
  3903. src_port: sport,
  3904. dst_port: dport,
  3905. any_port: anyport,
  3906. in_interface: iniface,
  3907. out_interface: outiface,
  3908. in_interface_list: inifacelist,
  3909. out_interface_list: outifacelist,
  3910. packet_mark: pktmark,
  3911. connection_mark: connmark,
  3912. routing_mark: routingmark,
  3913. connection_type: conntype,
  3914. connection_state: states,
  3915. connection_nat_state: natStates,
  3916. src_address_list: srclist,
  3917. dst_address_list: dstlist,
  3918. src_geoip: srcgeo,
  3919. dst_geoip: dstgeo,
  3920. comment,
  3921. disabled: !enabled,
  3922. // Advanced tab
  3923. layer7_protocol: getFwFieldVal('layer7', false),
  3924. content: getFwFieldVal('content', false),
  3925. connection_bytes: getFwFieldVal('connbytes', false),
  3926. connection_rate: getFwFieldVal('connrate', false),
  3927. pcc: getFwFieldVal('pcc', false),
  3928. src_mac_address: getFwFieldVal('srcmac', true),
  3929. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3930. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3931. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3932. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3933. ipsec_policy: getFwFieldVal('ipsec', false),
  3934. tls_host: getFwFieldVal('tlshost', false),
  3935. ingress_priority: getFwFieldVal('ingresspriority', false),
  3936. priority: getFwFieldVal('priority', false),
  3937. dscp: getFwFieldVal('dscp', false),
  3938. tcp_mss: getFwFieldVal('tcpmss', false),
  3939. tos: document.getElementById('fw-val-tos')?.value || '',
  3940. packet_size: getFwFieldVal('pktsize', false),
  3941. random: getFwFieldVal('random', false),
  3942. tcp_flags: getFwFieldVal('tcpflags', false),
  3943. icmp_options: getFwFieldVal('icmpoptions', false),
  3944. ipv4_options: getFwFieldVal('ipv4options', false),
  3945. ttl: getFwFieldVal('ttl', false),
  3946. // Extra tab
  3947. time: getFwFieldVal('time', false),
  3948. limit: getFwFieldVal('limit', false),
  3949. dst_limit: getFwFieldVal('dstlimit', false),
  3950. psd: getFwFieldVal('psd', false),
  3951. // Action tab
  3952. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3953. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3954. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3955. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3956. log: document.getElementById('filter-modal-log')?.checked || false,
  3957. log_prefix: getFwFieldVal('logprefix', false)
  3958. };
  3959. try {
  3960. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3961. method: 'POST',
  3962. headers: { 'Content-Type': 'application/json' },
  3963. body: JSON.stringify(payload)
  3964. });
  3965. if (res.ok) {
  3966. const data = await res.json();
  3967. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3968. loadFirewall(false);
  3969. if (closeAfter) {
  3970. closeFilterModal();
  3971. } else {
  3972. if (data.id) {
  3973. document.getElementById('filter-modal-id').value = data.id;
  3974. const badge = document.getElementById('fw-modal-badge');
  3975. if (badge) badge.innerText = `#${data.id}`;
  3976. }
  3977. }
  3978. } else {
  3979. const err = await res.json();
  3980. showToast('Error', err.message || 'Failed to save rule', 'error');
  3981. }
  3982. } catch (err) {
  3983. showToast('Error', err.message, 'error');
  3984. }
  3985. }
  3986. function submitSaveFilterRule(e) {
  3987. if (e && e.preventDefault) e.preventDefault();
  3988. return applyFilterRule(true);
  3989. }
  3990. function startFwStatPolling() {
  3991. stopFwStatPolling();
  3992. pollRuleStats();
  3993. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3994. }
  3995. function stopFwStatPolling() {
  3996. if (state.fwStatInterval) {
  3997. clearInterval(state.fwStatInterval);
  3998. state.fwStatInterval = null;
  3999. }
  4000. }
  4001. async function pollRuleStats() {
  4002. const id = document.getElementById('filter-modal-id')?.value;
  4003. if (!id) {
  4004. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4005. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4006. return;
  4007. }
  4008. try {
  4009. const res = await fetch(`${API_BASE}/firewall/filter`);
  4010. if (!res.ok) return;
  4011. const rules = await res.json();
  4012. const r = rules.find(x => x.id === id);
  4013. if (!r) return;
  4014. const now = Date.now();
  4015. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4016. state.fwLastTimestamp = now;
  4017. const curBytes = r.bytes || 0;
  4018. const curPackets = r.packets || 0;
  4019. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4020. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4021. state.fwLastBytes = curBytes;
  4022. state.fwLastPackets = curPackets;
  4023. const rateBps = Math.round((deltaBytes * 8) / dt);
  4024. const ratePkt = Math.round(deltaPkts / dt);
  4025. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4026. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4027. state.fwStatRateHistory.push(rateBps);
  4028. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4029. state.fwStatPktHistory.push(ratePkt);
  4030. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4031. const bEl = document.getElementById('fw-stat-bytes');
  4032. const pEl = document.getElementById('fw-stat-packets');
  4033. const rEl = document.getElementById('fw-stat-rate');
  4034. const prEl = document.getElementById('fw-stat-pktrate');
  4035. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4036. if (pEl) pEl.value = curPackets.toLocaleString();
  4037. if (rEl) rEl.value = formatBps(rateBps);
  4038. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4039. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4040. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4041. } catch (e) {
  4042. console.error('Error polling rule stats', e);
  4043. }
  4044. }
  4045. function formatBps(bps) {
  4046. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4047. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4048. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4049. return bps + ' bps';
  4050. }
  4051. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4052. const svg = document.getElementById(svgId);
  4053. if (!svg) return;
  4054. const w = 500;
  4055. const h = 100;
  4056. const paddingRight = 45;
  4057. const graphWidth = w - paddingRight;
  4058. const maxVal = Math.max(5, ...dataArray);
  4059. const currentVal = dataArray[dataArray.length - 1] || 0;
  4060. const leg = document.getElementById(legendId);
  4061. if (leg) {
  4062. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4063. }
  4064. let gridLines = '';
  4065. for (let i = 0; i <= 5; i++) {
  4066. const y = 8 + (i * (h - 18) / 5);
  4067. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4068. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4069. gridLines += `
  4070. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4071. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4072. `;
  4073. }
  4074. const step = graphWidth / (dataArray.length - 1);
  4075. const points = dataArray.map((val, idx) => {
  4076. const x = idx * step;
  4077. const y = (h - 10) - (val / maxVal) * (h - 20);
  4078. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4079. });
  4080. const polylineStr = points.join(' ');
  4081. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4082. svg.innerHTML = `
  4083. ${gridLines}
  4084. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4085. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4086. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4087. `;
  4088. }
  4089. async function moveFilterRule(id, dir) {
  4090. try {
  4091. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4092. method: 'POST',
  4093. headers: { 'Content-Type': 'application/json' },
  4094. body: JSON.stringify({ direction: dir })
  4095. });
  4096. if (res.ok) loadFirewall(false);
  4097. } catch (err) {
  4098. showToast('Error', err.message, 'error');
  4099. }
  4100. }
  4101. async function toggleFilterRuleState(id, disabled) {
  4102. try {
  4103. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4104. method: 'POST',
  4105. headers: { 'Content-Type': 'application/json' },
  4106. body: JSON.stringify({ disabled })
  4107. });
  4108. if (res.ok) loadFirewall(false);
  4109. } catch (err) {
  4110. showToast('Error', err.message, 'error');
  4111. }
  4112. }
  4113. async function deleteFilterRule(id) {
  4114. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4115. try {
  4116. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4117. if (res.ok) {
  4118. showToast('Deleted', 'Filter rule removed', 'success');
  4119. loadFirewall(false);
  4120. }
  4121. } catch (err) {
  4122. showToast('Error', err.message, 'error');
  4123. }
  4124. }
  4125. // ----------------- NAT Rules -----------------
  4126. function renderNATRules() {
  4127. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4128. const tbody = document.getElementById('nat-table-body');
  4129. const empty = document.getElementById('nat-empty');
  4130. if (!tbody) return;
  4131. tbody.innerHTML = '';
  4132. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4133. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4134. if (rules.length === 0) {
  4135. empty?.classList.remove('hidden');
  4136. return;
  4137. }
  4138. empty?.classList.add('hidden');
  4139. rules.forEach((r, idx) => {
  4140. const tr = document.createElement('tr');
  4141. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4142. let toTarget = '-';
  4143. if (r.action === 'jump') {
  4144. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4145. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4146. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4147. } else if (r.action === 'redirect') {
  4148. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4149. } else if (r.action === 'masquerade') {
  4150. 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>`;
  4151. } else if (r.action === 'log') {
  4152. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4153. } else {
  4154. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4155. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4156. }
  4157. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4158. tr.innerHTML = `
  4159. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4160. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4161. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4162. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4163. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4164. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4165. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4166. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4167. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4168. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4169. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4170. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4171. </td>
  4172. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4173. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4174. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4175. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4176. <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>
  4177. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4178. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4179. </td>
  4180. `;
  4181. tbody.appendChild(tr);
  4182. });
  4183. }
  4184. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4185. function switchNATRuleTab(tab) {
  4186. state.activeNATRuleTab = tab;
  4187. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4188. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4189. btn.classList.add('text-slate-400', 'border-transparent');
  4190. });
  4191. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4192. if (activeBtn) {
  4193. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4194. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4195. }
  4196. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4197. const activePane = document.getElementById(`nat-pane-${tab}`);
  4198. if (activePane) activePane.classList.remove('hidden');
  4199. if (tab === 'statistics') {
  4200. startNATStatPolling();
  4201. } else {
  4202. stopNATStatPolling();
  4203. }
  4204. }
  4205. function toggleNATField(fieldKey, expand) {
  4206. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4207. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4208. if (!plusBtn || !fieldBox) return;
  4209. if (expand) {
  4210. plusBtn.classList.add('hidden');
  4211. fieldBox.classList.remove('hidden');
  4212. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4213. if (valInput) valInput.focus();
  4214. } else {
  4215. fieldBox.classList.add('hidden');
  4216. plusBtn.classList.remove('hidden');
  4217. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4218. if (valInput) {
  4219. if (valInput.tagName === 'SELECT') {
  4220. valInput.selectedIndex = 0;
  4221. } else {
  4222. valInput.value = '';
  4223. }
  4224. }
  4225. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4226. if (invInput) invInput.checked = false;
  4227. if (fieldKey === 'days') {
  4228. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4229. const el = document.getElementById(`nat-day-${d}`);
  4230. if (el) el.checked = true;
  4231. });
  4232. }
  4233. }
  4234. }
  4235. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4236. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4237. toggleNATField(fieldKey, true);
  4238. let strVal = String(value);
  4239. if (hasInvert) {
  4240. const inv = strVal.startsWith('!');
  4241. if (inv) strVal = strVal.slice(1);
  4242. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4243. if (invEl) invEl.checked = inv;
  4244. }
  4245. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4246. if (valEl) valEl.value = strVal;
  4247. } else {
  4248. toggleNATField(fieldKey, false);
  4249. }
  4250. }
  4251. function getNATFieldVal(fieldKey, hasInvert = false) {
  4252. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4253. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4254. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4255. let v = valEl ? valEl.value.trim() : '';
  4256. if (!v) return '';
  4257. if (hasInvert) {
  4258. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4259. if (invEl && invEl.checked) {
  4260. v = '!' + v.replace(/^!/, '');
  4261. }
  4262. }
  4263. return v;
  4264. }
  4265. function toggleMaximizeNATModal() {
  4266. const win = document.getElementById('nat-modal-window');
  4267. if (!win) return;
  4268. if (win.classList.contains('max-w-[720px]')) {
  4269. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4270. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4271. } else {
  4272. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4273. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4274. }
  4275. }
  4276. function handleNATChainChange() {
  4277. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4278. const actSel = document.getElementById('nat-modal-action');
  4279. if (actSel) {
  4280. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4281. actSel.value = 'masquerade';
  4282. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4283. actSel.value = 'dst-nat';
  4284. }
  4285. }
  4286. toggleNATActionFields();
  4287. }
  4288. function toggleNATActionFields() {
  4289. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4290. const rowAddr = document.getElementById('nat-row-toaddr');
  4291. const rowPort = document.getElementById('nat-row-toport');
  4292. const jumpBox = document.getElementById('nat-action-jump-box');
  4293. const addrBox = document.getElementById('nat-action-addrlist-box');
  4294. // Hide all dynamic rows first
  4295. if (rowAddr) rowAddr.classList.add('hidden');
  4296. if (rowPort) rowPort.classList.add('hidden');
  4297. if (jumpBox) jumpBox.classList.add('hidden');
  4298. if (addrBox) addrBox.classList.add('hidden');
  4299. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4300. if (rowAddr) rowAddr.classList.remove('hidden');
  4301. if (rowPort) rowPort.classList.remove('hidden');
  4302. } else if (act === 'redirect' || act === 'masquerade') {
  4303. if (rowPort) rowPort.classList.remove('hidden');
  4304. } else if (act === 'jump') {
  4305. if (jumpBox) jumpBox.classList.remove('hidden');
  4306. } else if (act.includes('address-list') || act.includes('address list')) {
  4307. if (addrBox) addrBox.classList.remove('hidden');
  4308. }
  4309. if (act === 'log') {
  4310. const logEl = document.getElementById('nat-modal-log');
  4311. if (logEl) logEl.checked = true;
  4312. toggleNATField('logprefix', true);
  4313. }
  4314. }
  4315. function toggleNATLogPrefix() {
  4316. const isLog = document.getElementById('nat-modal-log')?.checked;
  4317. toggleNATField('logprefix', !!isLog);
  4318. }
  4319. function openAddNATModal() {
  4320. switchNATRuleTab('general');
  4321. const badge = document.getElementById('nat-modal-badge');
  4322. if (badge) badge.innerText = 'New...';
  4323. document.getElementById('nat-modal-id').value = '';
  4324. document.getElementById('nat-modal-enabled').checked = true;
  4325. document.getElementById('nat-modal-comment').value = '';
  4326. document.getElementById('nat-modal-chain').value = 'srcnat';
  4327. document.getElementById('nat-modal-action').value = 'masquerade';
  4328. document.getElementById('nat-modal-toaddr').value = '';
  4329. document.getElementById('nat-modal-toport').value = '';
  4330. document.getElementById('nat-modal-log').checked = false;
  4331. populateInterfaceSelect('nat-val-iniface');
  4332. populateInterfaceSelect('nat-val-outiface');
  4333. populateAddressListSelect('nat-val-srclist');
  4334. populateAddressListSelect('nat-val-dstlist');
  4335. populateGeoIPSelect('nat-val-srcgeo');
  4336. populateGeoIPSelect('nat-val-dstgeo');
  4337. const allFieldKeys = [
  4338. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4339. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4340. 'routingmark', 'conntype',
  4341. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4342. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4343. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4344. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4345. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4346. ];
  4347. allFieldKeys.forEach(k => toggleNATField(k, false));
  4348. resetCurrentNATRuleCounters();
  4349. toggleNATActionFields();
  4350. document.getElementById('nat-modal').classList.remove('hidden');
  4351. }
  4352. function openEditNATModal(id) {
  4353. const r = (state.natRules || []).find(rule => rule.id === id);
  4354. if (!r) return;
  4355. switchNATRuleTab('general');
  4356. const badge = document.getElementById('nat-modal-badge');
  4357. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4358. document.getElementById('nat-modal-id').value = r.id;
  4359. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4360. document.getElementById('nat-modal-comment').value = r.comment || '';
  4361. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4362. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4363. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4364. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4365. document.getElementById('nat-modal-log').checked = !!r.log;
  4366. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4367. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4368. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4369. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4370. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4371. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4372. setNATFieldVal('src', r.src_address, true);
  4373. setNATFieldVal('dst', r.dst_address, true);
  4374. setNATFieldVal('srclist', r.src_address_list, true);
  4375. setNATFieldVal('dstlist', r.dst_address_list, true);
  4376. setNATFieldVal('srcgeo', r.src_geoip, true);
  4377. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4378. if (r.protocol && r.protocol !== 'all') {
  4379. setNATFieldVal('proto', r.protocol, true);
  4380. } else {
  4381. toggleNATField('proto', false);
  4382. }
  4383. setNATFieldVal('sport', r.src_port, true);
  4384. setNATFieldVal('dport', r.dst_port, true);
  4385. setNATFieldVal('anyport', r.any_port, true);
  4386. setNATFieldVal('iniface', r.in_interface, true);
  4387. setNATFieldVal('outiface', r.out_interface, true);
  4388. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4389. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4390. setNATFieldVal('pktmark', r.packet_mark, true);
  4391. setNATFieldVal('connmark', r.connection_mark, true);
  4392. setNATFieldVal('routingmark', r.routing_mark, true);
  4393. setNATFieldVal('conntype', r.connection_type, false);
  4394. // Advanced tab fields
  4395. setNATFieldVal('layer7', r.layer7_protocol, false);
  4396. setNATFieldVal('content', r.content, false);
  4397. setNATFieldVal('connbytes', r.connection_bytes, false);
  4398. setNATFieldVal('connrate', r.connection_rate, false);
  4399. setNATFieldVal('pcc', r.pcc, false);
  4400. setNATFieldVal('srcmac', r.src_mac_address, true);
  4401. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4402. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4403. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4404. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4405. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4406. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4407. setNATFieldVal('priority', r.priority, false);
  4408. setNATFieldVal('dscp', r.dscp, false);
  4409. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4410. if (r.tos) {
  4411. const tosEl = document.getElementById('nat-val-tos');
  4412. if (tosEl) tosEl.value = r.tos;
  4413. }
  4414. setNATFieldVal('pktsize', r.packet_size, false);
  4415. setNATFieldVal('random', r.random, false);
  4416. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4417. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4418. setNATFieldVal('ttl', r.ttl, false);
  4419. // Extra tab fields
  4420. setNATFieldVal('time', r.time, false);
  4421. if (r.days) {
  4422. toggleNATField('days', true);
  4423. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4424. const chk = document.getElementById(`nat-day-${d}`);
  4425. if (chk) chk.checked = r.days.includes(d);
  4426. });
  4427. } else {
  4428. toggleNATField('days', false);
  4429. }
  4430. setNATFieldVal('limit', r.limit, false);
  4431. setNATFieldVal('dstlimit', r.dst_limit, false);
  4432. setNATFieldVal('psd', r.psd, false);
  4433. // Action fields
  4434. if (r.jump_target) {
  4435. const jtEl = document.getElementById('nat-modal-jumptarget');
  4436. if (jtEl) jtEl.value = r.jump_target;
  4437. }
  4438. if (r.address_list) {
  4439. const alEl = document.getElementById('nat-modal-action-addrlist');
  4440. if (alEl) alEl.value = r.address_list;
  4441. }
  4442. if (r.address_list_timeout) {
  4443. const toEl = document.getElementById('nat-modal-action-timeout');
  4444. if (toEl) toEl.value = r.address_list_timeout;
  4445. }
  4446. setNATFieldVal('logprefix', r.log_prefix, false);
  4447. // Statistics
  4448. const bEl = document.getElementById('nat-stat-bytes');
  4449. const pEl = document.getElementById('nat-stat-packets');
  4450. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4451. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4452. state.natLastBytes = r.bytes || 0;
  4453. state.natLastPackets = r.packets || 0;
  4454. state.natLastTimestamp = Date.now();
  4455. state.natStatRateHistory = new Array(30).fill(0);
  4456. state.natStatPktHistory = new Array(30).fill(0);
  4457. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4458. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4459. toggleNATActionFields();
  4460. document.getElementById('nat-modal').classList.remove('hidden');
  4461. }
  4462. function closeNATModal() {
  4463. stopNATStatPolling();
  4464. document.getElementById('nat-modal').classList.add('hidden');
  4465. }
  4466. function copyNATRule() {
  4467. document.getElementById('nat-modal-id').value = '';
  4468. const badge = document.getElementById('nat-modal-badge');
  4469. if (badge) badge.innerText = 'New...';
  4470. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4471. }
  4472. function resetCurrentNATRuleCounters() {
  4473. state.natStatRateHistory = new Array(30).fill(0);
  4474. state.natStatPktHistory = new Array(30).fill(0);
  4475. state.natLastBytes = 0;
  4476. state.natLastPackets = 0;
  4477. state.natLastTimestamp = Date.now();
  4478. const bEl = document.getElementById('nat-stat-bytes');
  4479. const pEl = document.getElementById('nat-stat-packets');
  4480. const rEl = document.getElementById('nat-stat-rate');
  4481. const prEl = document.getElementById('nat-stat-pktrate');
  4482. if (bEl) bEl.value = '0 B';
  4483. if (pEl) pEl.value = '0';
  4484. if (rEl) rEl.value = '0 bps';
  4485. if (prEl) prEl.value = '0 p/s';
  4486. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4487. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4488. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4489. }
  4490. async function applyNATRule(closeAfter = false) {
  4491. const id = document.getElementById('nat-modal-id').value;
  4492. const chain = document.getElementById('nat-modal-chain').value;
  4493. const action = document.getElementById('nat-modal-action').value;
  4494. const comment = document.getElementById('nat-modal-comment').value.trim();
  4495. const enabled = document.getElementById('nat-modal-enabled').checked;
  4496. const src = getNATFieldVal('src', true);
  4497. const dst = getNATFieldVal('dst', true);
  4498. const srclist = getNATFieldVal('srclist', true);
  4499. const dstlist = getNATFieldVal('dstlist', true);
  4500. const srcgeo = getNATFieldVal('srcgeo', true);
  4501. const dstgeo = getNATFieldVal('dstgeo', true);
  4502. const proto = getNATFieldVal('proto', true);
  4503. const sport = getNATFieldVal('sport', true);
  4504. const dport = getNATFieldVal('dport', true);
  4505. const anyport = getNATFieldVal('anyport', true);
  4506. const iniface = getNATFieldVal('iniface', true);
  4507. const outiface = getNATFieldVal('outiface', true);
  4508. const inifacelist = getNATFieldVal('inifacelist', true);
  4509. const outifacelist = getNATFieldVal('outifacelist', true);
  4510. const pktmark = getNATFieldVal('pktmark', true);
  4511. const connmark = getNATFieldVal('connmark', true);
  4512. const routingmark = getNATFieldVal('routingmark', true);
  4513. const conntype = getNATFieldVal('conntype', false);
  4514. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4515. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4516. const payload = {
  4517. id,
  4518. chain,
  4519. action,
  4520. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4521. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4522. protocol: proto || 'all',
  4523. src_address: src,
  4524. dst_address: dst,
  4525. src_port: sport,
  4526. dst_port: dport,
  4527. any_port: anyport,
  4528. in_interface: iniface,
  4529. out_interface: outiface,
  4530. in_interface_list: inifacelist,
  4531. out_interface_list: outifacelist,
  4532. packet_mark: pktmark,
  4533. connection_mark: connmark,
  4534. routing_mark: routingmark,
  4535. connection_type: conntype,
  4536. src_address_list: srclist,
  4537. dst_address_list: dstlist,
  4538. src_geoip: srcgeo,
  4539. dst_geoip: dstgeo,
  4540. comment,
  4541. disabled: !enabled,
  4542. // Advanced tab
  4543. layer7_protocol: getNATFieldVal('layer7', false),
  4544. content: getNATFieldVal('content', false),
  4545. connection_bytes: getNATFieldVal('connbytes', false),
  4546. connection_rate: getNATFieldVal('connrate', false),
  4547. pcc: getNATFieldVal('pcc', false),
  4548. src_mac_address: getNATFieldVal('srcmac', true),
  4549. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4550. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4551. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4552. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4553. ipsec_policy: getNATFieldVal('ipsec', false),
  4554. ingress_priority: getNATFieldVal('ingresspriority', false),
  4555. priority: getNATFieldVal('priority', false),
  4556. dscp: getNATFieldVal('dscp', false),
  4557. tcp_mss: getNATFieldVal('tcpmss', false),
  4558. tos: document.getElementById('nat-val-tos')?.value || '',
  4559. packet_size: getNATFieldVal('pktsize', false),
  4560. random: getNATFieldVal('random', false),
  4561. icmp_options: getNATFieldVal('icmpoptions', false),
  4562. ipv4_options: getNATFieldVal('ipv4options', false),
  4563. ttl: getNATFieldVal('ttl', false),
  4564. // Extra tab
  4565. time: getNATFieldVal('time', false),
  4566. limit: getNATFieldVal('limit', false),
  4567. dst_limit: getNATFieldVal('dstlimit', false),
  4568. psd: getNATFieldVal('psd', false),
  4569. // Action tab
  4570. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4571. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4572. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4573. log: document.getElementById('nat-modal-log')?.checked || false,
  4574. log_prefix: getNATFieldVal('logprefix', false)
  4575. };
  4576. try {
  4577. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4578. method: 'POST',
  4579. headers: { 'Content-Type': 'application/json' },
  4580. body: JSON.stringify(payload)
  4581. });
  4582. if (res.ok) {
  4583. const data = await res.json();
  4584. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4585. loadFirewall(false);
  4586. if (closeAfter) {
  4587. closeNATModal();
  4588. } else {
  4589. if (data.id) {
  4590. document.getElementById('nat-modal-id').value = data.id;
  4591. const badge = document.getElementById('nat-modal-badge');
  4592. if (badge) badge.innerText = `#${data.id}`;
  4593. }
  4594. }
  4595. } else {
  4596. const err = await res.json();
  4597. showToast('Error', err.message || 'Failed to save rule', 'error');
  4598. }
  4599. } catch (err) {
  4600. showToast('Error', err.message, 'error');
  4601. }
  4602. }
  4603. function submitSaveNATRule(e) {
  4604. if (e && e.preventDefault) e.preventDefault();
  4605. return applyNATRule(true);
  4606. }
  4607. function startNATStatPolling() {
  4608. stopNATStatPolling();
  4609. pollNATRuleStats();
  4610. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4611. }
  4612. function stopNATStatPolling() {
  4613. if (state.natStatInterval) {
  4614. clearInterval(state.natStatInterval);
  4615. state.natStatInterval = null;
  4616. }
  4617. }
  4618. async function pollNATRuleStats() {
  4619. const id = document.getElementById('nat-modal-id')?.value;
  4620. if (!id) {
  4621. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4622. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4623. return;
  4624. }
  4625. try {
  4626. const res = await fetch(`${API_BASE}/firewall/nat`);
  4627. if (!res.ok) return;
  4628. const rules = await res.json();
  4629. const r = rules.find(x => x.id === id);
  4630. if (!r) return;
  4631. const now = Date.now();
  4632. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4633. state.natLastTimestamp = now;
  4634. const curBytes = r.bytes || 0;
  4635. const curPackets = r.packets || 0;
  4636. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4637. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4638. state.natLastBytes = curBytes;
  4639. state.natLastPackets = curPackets;
  4640. const rateBps = Math.round((deltaBytes * 8) / dt);
  4641. const ratePkt = Math.round(deltaPkts / dt);
  4642. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4643. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4644. state.natStatRateHistory.push(rateBps);
  4645. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4646. state.natStatPktHistory.push(ratePkt);
  4647. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4648. const bEl = document.getElementById('nat-stat-bytes');
  4649. const pEl = document.getElementById('nat-stat-packets');
  4650. const rEl = document.getElementById('nat-stat-rate');
  4651. const prEl = document.getElementById('nat-stat-pktrate');
  4652. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4653. if (pEl) pEl.value = curPackets.toLocaleString();
  4654. if (rEl) rEl.value = formatBps(rateBps);
  4655. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4656. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4657. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4658. } catch (e) {
  4659. console.error('Error polling NAT rule stats', e);
  4660. }
  4661. }
  4662. async function moveNATRule(id, dir) {
  4663. try {
  4664. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4665. method: 'POST',
  4666. headers: { 'Content-Type': 'application/json' },
  4667. body: JSON.stringify({ direction: dir })
  4668. });
  4669. if (res.ok) loadFirewall(false);
  4670. } catch (err) {
  4671. showToast('Error', err.message, 'error');
  4672. }
  4673. }
  4674. async function toggleNATRuleState(id, disabled) {
  4675. try {
  4676. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4677. method: 'POST',
  4678. headers: { 'Content-Type': 'application/json' },
  4679. body: JSON.stringify({ disabled })
  4680. });
  4681. if (res.ok) loadFirewall(false);
  4682. } catch (err) {
  4683. showToast('Error', err.message, 'error');
  4684. }
  4685. }
  4686. async function deleteNATRule(id) {
  4687. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4690. if (res.ok) {
  4691. showToast('Deleted', 'NAT rule removed', 'success');
  4692. loadFirewall(false);
  4693. }
  4694. } catch (err) {
  4695. showToast('Error', err.message, 'error');
  4696. }
  4697. }
  4698. // ----------------- Mangle Rules -----------------
  4699. function renderMangleRules() {
  4700. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4701. const tbody = document.getElementById('mangle-table-body');
  4702. const empty = document.getElementById('mangle-empty');
  4703. if (!tbody) return;
  4704. tbody.innerHTML = '';
  4705. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4706. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4707. if (rules.length === 0) {
  4708. empty?.classList.remove('hidden');
  4709. return;
  4710. }
  4711. empty?.classList.add('hidden');
  4712. rules.forEach((r, idx) => {
  4713. const tr = document.createElement('tr');
  4714. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4715. let markVal = '<span class="text-slate-500">-</span>';
  4716. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4717. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4718. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4719. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4720. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4721. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4722. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4723. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4724. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4725. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4726. 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>`;
  4727. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4728. tr.innerHTML = `
  4729. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4730. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4731. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4732. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4733. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4734. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4735. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4736. <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>
  4737. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4738. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4739. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4740. </td>
  4741. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4742. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4743. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4744. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4745. <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>
  4746. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4747. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4748. </td>
  4749. `;
  4750. tbody.appendChild(tr);
  4751. });
  4752. }
  4753. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4754. function switchMangleRuleTab(tab) {
  4755. state.activeMangleRuleTab = tab;
  4756. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4757. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4758. btn.classList.add('text-slate-400', 'border-transparent');
  4759. });
  4760. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4761. if (activeBtn) {
  4762. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4763. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4764. }
  4765. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4766. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4767. if (activePane) activePane.classList.remove('hidden');
  4768. if (tab === 'statistics') {
  4769. startMangleStatPolling();
  4770. } else {
  4771. stopMangleStatPolling();
  4772. }
  4773. }
  4774. function toggleMangleField(fieldKey, expand) {
  4775. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4776. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4777. if (!plusBtn || !fieldBox) return;
  4778. if (expand) {
  4779. plusBtn.classList.add('hidden');
  4780. fieldBox.classList.remove('hidden');
  4781. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4782. if (valInput) valInput.focus();
  4783. } else {
  4784. fieldBox.classList.add('hidden');
  4785. plusBtn.classList.remove('hidden');
  4786. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4787. if (valInput) {
  4788. if (valInput.tagName === 'SELECT') {
  4789. valInput.selectedIndex = 0;
  4790. } else {
  4791. valInput.value = '';
  4792. }
  4793. }
  4794. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4795. if (invInput) invInput.checked = false;
  4796. if (fieldKey === 'cs') {
  4797. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4798. const el = document.getElementById(id);
  4799. if (el) el.checked = false;
  4800. });
  4801. }
  4802. if (fieldKey === 'natstate') {
  4803. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4804. const el = document.getElementById(id);
  4805. if (el) el.checked = false;
  4806. });
  4807. }
  4808. }
  4809. }
  4810. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4811. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4812. toggleMangleField(fieldKey, true);
  4813. let strVal = String(value);
  4814. if (hasInvert) {
  4815. const inv = strVal.startsWith('!');
  4816. if (inv) strVal = strVal.slice(1);
  4817. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4818. if (invEl) invEl.checked = inv;
  4819. }
  4820. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4821. if (valEl) valEl.value = strVal;
  4822. } else {
  4823. toggleMangleField(fieldKey, false);
  4824. }
  4825. }
  4826. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4827. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4828. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4829. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4830. let v = valEl ? valEl.value.trim() : '';
  4831. if (!v) return '';
  4832. if (hasInvert) {
  4833. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4834. if (invEl && invEl.checked) {
  4835. v = '!' + v.replace(/^!/, '');
  4836. }
  4837. }
  4838. return v;
  4839. }
  4840. function toggleMaximizeMangleModal() {
  4841. const win = document.getElementById('mangle-modal-window');
  4842. if (!win) return;
  4843. if (win.classList.contains('max-w-[720px]')) {
  4844. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4845. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4846. } else {
  4847. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4848. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4849. }
  4850. }
  4851. function toggleMangleActionFields() {
  4852. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4853. // Hide all dynamic rows first
  4854. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4855. const el = document.getElementById(`mangle-row-${id}`);
  4856. if (el) el.classList.add('hidden');
  4857. });
  4858. const jumpBox = document.getElementById('mangle-action-jump-box');
  4859. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4860. if (jumpBox) jumpBox.classList.add('hidden');
  4861. if (addrBox) addrBox.classList.add('hidden');
  4862. // Activate matching rows
  4863. if (act === 'mark-connection') {
  4864. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4865. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4866. } else if (act === 'mark-routing') {
  4867. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4868. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4869. } else if (act === 'mark-packet') {
  4870. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4871. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4872. } else if (act === 'change-mss') {
  4873. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4874. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4875. } else if (act === 'change-dscp') {
  4876. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4877. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4878. } else if (act === 'change-ttl') {
  4879. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4880. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4881. } else if (act === 'set-priority') {
  4882. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4883. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4884. } else if (act === 'route') {
  4885. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4886. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4887. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4888. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4889. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4890. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4891. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4892. } else if (act === 'jump') {
  4893. if (jumpBox) jumpBox.classList.remove('hidden');
  4894. } else if (act.includes('address-list') || act.includes('address list')) {
  4895. if (addrBox) addrBox.classList.remove('hidden');
  4896. }
  4897. if (act === 'log') {
  4898. const logEl = document.getElementById('mangle-modal-log');
  4899. if (logEl) logEl.checked = true;
  4900. toggleMangleField('logprefix', true);
  4901. }
  4902. }
  4903. function toggleMangleLogPrefix() {
  4904. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4905. toggleMangleField('logprefix', !!isLog);
  4906. }
  4907. const allMangleFieldKeys = [
  4908. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4909. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4910. 'routingmark', 'conntype', 'cs', 'natstate',
  4911. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4912. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4913. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4914. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4915. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4916. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4917. ];
  4918. function openAddMangleModal() {
  4919. switchMangleRuleTab('general');
  4920. const badge = document.getElementById('mangle-modal-badge');
  4921. if (badge) badge.innerText = 'New...';
  4922. document.getElementById('mangle-modal-id').value = '';
  4923. document.getElementById('mangle-modal-enabled').checked = true;
  4924. document.getElementById('mangle-modal-comment').value = '';
  4925. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4926. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4927. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4928. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4929. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4930. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4931. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4932. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4933. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4934. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4935. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4936. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4937. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4938. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4939. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4940. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4941. populateInterfaceSelect('mangle-val-iniface');
  4942. populateInterfaceSelect('mangle-val-outiface');
  4943. populateAddressListSelect('mangle-val-srclist');
  4944. populateAddressListSelect('mangle-val-dstlist');
  4945. populateGeoIPSelect('mangle-val-srcgeo');
  4946. populateGeoIPSelect('mangle-val-dstgeo');
  4947. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4948. resetCurrentMangleRuleCounters();
  4949. toggleMangleActionFields();
  4950. document.getElementById('mangle-modal').classList.remove('hidden');
  4951. }
  4952. function openEditMangleModal(id) {
  4953. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4954. if (!r) return;
  4955. switchMangleRuleTab('general');
  4956. const badge = document.getElementById('mangle-modal-badge');
  4957. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4958. document.getElementById('mangle-modal-id').value = r.id;
  4959. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4960. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4961. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4962. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4963. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4964. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4965. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4966. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4967. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4968. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4969. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4970. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4971. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4972. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4973. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4974. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4975. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4976. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4977. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4978. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4979. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4980. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4981. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4982. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4983. setMangleFieldVal('src', r.src_address, true);
  4984. setMangleFieldVal('dst', r.dst_address, true);
  4985. setMangleFieldVal('srclist', r.src_address_list, true);
  4986. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4987. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4988. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4989. if (r.protocol && r.protocol !== 'all') {
  4990. setMangleFieldVal('proto', r.protocol, true);
  4991. } else {
  4992. toggleMangleField('proto', false);
  4993. }
  4994. setMangleFieldVal('sport', r.src_port, true);
  4995. setMangleFieldVal('dport', r.dst_port, true);
  4996. setMangleFieldVal('anyport', r.any_port, true);
  4997. setMangleFieldVal('iniface', r.in_interface, true);
  4998. setMangleFieldVal('outiface', r.out_interface, true);
  4999. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5000. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5001. setMangleFieldVal('pktmark', r.packet_mark, true);
  5002. setMangleFieldVal('connmark', r.connection_mark, true);
  5003. setMangleFieldVal('routingmark', r.routing_mark, true);
  5004. setMangleFieldVal('conntype', r.connection_type, false);
  5005. // Connection State
  5006. const states = r.connection_state || [];
  5007. if (states.length > 0) {
  5008. toggleMangleField('cs', true);
  5009. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5010. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5011. if (el) el.checked = states.includes(s);
  5012. });
  5013. } else {
  5014. toggleMangleField('cs', false);
  5015. }
  5016. // Connection NAT State
  5017. const natStates = r.connection_nat_state || [];
  5018. if (natStates.length > 0) {
  5019. toggleMangleField('natstate', true);
  5020. ['srcnat', 'dstnat'].forEach(s => {
  5021. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5022. if (el) el.checked = natStates.includes(s);
  5023. });
  5024. } else {
  5025. toggleMangleField('natstate', false);
  5026. }
  5027. // Advanced tab fields
  5028. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5029. setMangleFieldVal('content', r.content, false);
  5030. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5031. setMangleFieldVal('connrate', r.connection_rate, false);
  5032. setMangleFieldVal('pcc', r.pcc, false);
  5033. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5034. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5035. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5036. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5037. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5038. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5039. setMangleFieldVal('tlshost', r.tls_host, false);
  5040. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5041. setMangleFieldVal('priority', r.priority, false);
  5042. setMangleFieldVal('dscp', r.dscp, false);
  5043. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5044. if (r.tos) {
  5045. const tosEl = document.getElementById('mangle-val-tos');
  5046. if (tosEl) tosEl.value = r.tos;
  5047. }
  5048. setMangleFieldVal('pktsize', r.packet_size, false);
  5049. setMangleFieldVal('random', r.random, false);
  5050. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5051. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5052. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5053. setMangleFieldVal('ttl', r.ttl, false);
  5054. // Extra tab fields
  5055. setMangleFieldVal('nth', r.nth, false);
  5056. setMangleFieldVal('connlimit', r.connection_limit, false);
  5057. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5058. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5059. setMangleFieldVal('hotspot', r.hotspot, false);
  5060. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5061. setMangleFieldVal('limit', r.limit, false);
  5062. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5063. setMangleFieldVal('time', r.time, false);
  5064. setMangleFieldVal('psd', r.psd, false);
  5065. // Action fields
  5066. if (r.jump_target) {
  5067. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5068. if (jtEl) jtEl.value = r.jump_target;
  5069. }
  5070. if (r.address_list) {
  5071. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5072. if (alEl) alEl.value = r.address_list;
  5073. }
  5074. if (r.address_list_timeout) {
  5075. const toEl = document.getElementById('mangle-modal-action-timeout');
  5076. if (toEl) toEl.value = r.address_list_timeout;
  5077. }
  5078. setMangleFieldVal('logprefix', r.log_prefix, false);
  5079. // Statistics
  5080. const bEl = document.getElementById('mangle-stat-bytes');
  5081. const pEl = document.getElementById('mangle-stat-packets');
  5082. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5083. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5084. state.mangleLastBytes = r.bytes || 0;
  5085. state.mangleLastPackets = r.packets || 0;
  5086. state.mangleLastTimestamp = Date.now();
  5087. state.mangleStatRateHistory = new Array(30).fill(0);
  5088. state.mangleStatPktHistory = new Array(30).fill(0);
  5089. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5090. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5091. toggleMangleActionFields();
  5092. document.getElementById('mangle-modal').classList.remove('hidden');
  5093. }
  5094. function closeMangleModal() {
  5095. stopMangleStatPolling();
  5096. document.getElementById('mangle-modal').classList.add('hidden');
  5097. }
  5098. function copyMangleRule() {
  5099. document.getElementById('mangle-modal-id').value = '';
  5100. const badge = document.getElementById('mangle-modal-badge');
  5101. if (badge) badge.innerText = 'New...';
  5102. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5103. }
  5104. function resetCurrentMangleRuleCounters() {
  5105. state.mangleStatRateHistory = new Array(30).fill(0);
  5106. state.mangleStatPktHistory = new Array(30).fill(0);
  5107. state.mangleLastBytes = 0;
  5108. state.mangleLastPackets = 0;
  5109. state.mangleLastTimestamp = Date.now();
  5110. const bEl = document.getElementById('mangle-stat-bytes');
  5111. const pEl = document.getElementById('mangle-stat-packets');
  5112. const rEl = document.getElementById('mangle-stat-rate');
  5113. const prEl = document.getElementById('mangle-stat-pktrate');
  5114. if (bEl) bEl.value = '0 B';
  5115. if (pEl) pEl.value = '0';
  5116. if (rEl) rEl.value = '0 bps';
  5117. if (prEl) prEl.value = '0 p/s';
  5118. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5119. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5120. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5121. }
  5122. async function applyMangleRule(closeAfter = false) {
  5123. const id = document.getElementById('mangle-modal-id').value;
  5124. const chain = document.getElementById('mangle-modal-chain').value;
  5125. const action = document.getElementById('mangle-modal-action').value;
  5126. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5127. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5128. const src = getMangleFieldVal('src', true);
  5129. const dst = getMangleFieldVal('dst', true);
  5130. const srclist = getMangleFieldVal('srclist', true);
  5131. const dstlist = getMangleFieldVal('dstlist', true);
  5132. const srcgeo = getMangleFieldVal('srcgeo', true);
  5133. const dstgeo = getMangleFieldVal('dstgeo', true);
  5134. const proto = getMangleFieldVal('proto', true);
  5135. const sport = getMangleFieldVal('sport', true);
  5136. const dport = getMangleFieldVal('dport', true);
  5137. const anyport = getMangleFieldVal('anyport', true);
  5138. const iniface = getMangleFieldVal('iniface', true);
  5139. const outiface = getMangleFieldVal('outiface', true);
  5140. const inifacelist = getMangleFieldVal('inifacelist', true);
  5141. const outifacelist = getMangleFieldVal('outifacelist', true);
  5142. const pktmark = getMangleFieldVal('pktmark', true);
  5143. const connmark = getMangleFieldVal('connmark', true);
  5144. const routingmark = getMangleFieldVal('routingmark', true);
  5145. const conntype = getMangleFieldVal('conntype', false);
  5146. const states = [];
  5147. const csBox = document.getElementById('mangle-field-cs');
  5148. if (csBox && !csBox.classList.contains('hidden')) {
  5149. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5150. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5151. });
  5152. }
  5153. const natStates = [];
  5154. const natBox = document.getElementById('mangle-field-natstate');
  5155. if (natBox && !natBox.classList.contains('hidden')) {
  5156. ['srcnat', 'dstnat'].forEach(s => {
  5157. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5158. });
  5159. }
  5160. const payload = {
  5161. id,
  5162. chain,
  5163. action,
  5164. protocol: proto || 'all',
  5165. src_address: src,
  5166. dst_address: dst,
  5167. src_port: sport,
  5168. dst_port: dport,
  5169. any_port: anyport,
  5170. in_interface: iniface,
  5171. out_interface: outiface,
  5172. in_interface_list: inifacelist,
  5173. out_interface_list: outifacelist,
  5174. packet_mark: pktmark,
  5175. connection_mark: connmark,
  5176. routing_mark: routingmark,
  5177. connection_type: conntype,
  5178. connection_state: states,
  5179. connection_nat_state: natStates,
  5180. src_address_list: srclist,
  5181. dst_address_list: dstlist,
  5182. src_geoip: srcgeo,
  5183. dst_geoip: dstgeo,
  5184. comment,
  5185. disabled: !enabled,
  5186. // Advanced tab
  5187. layer7_protocol: getMangleFieldVal('layer7', false),
  5188. content: getMangleFieldVal('content', false),
  5189. connection_bytes: getMangleFieldVal('connbytes', false),
  5190. connection_rate: getMangleFieldVal('connrate', false),
  5191. pcc: getMangleFieldVal('pcc', false),
  5192. src_mac_address: getMangleFieldVal('srcmac', true),
  5193. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5194. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5195. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5196. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5197. ipsec_policy: getMangleFieldVal('ipsec', false),
  5198. tls_host: getMangleFieldVal('tlshost', false),
  5199. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5200. priority: getMangleFieldVal('priority', false),
  5201. dscp: getMangleFieldVal('dscp', false),
  5202. tcp_mss: getMangleFieldVal('tcpmss', false),
  5203. tos: document.getElementById('mangle-val-tos')?.value || '',
  5204. packet_size: getMangleFieldVal('pktsize', false),
  5205. random: getMangleFieldVal('random', false),
  5206. tcp_flags: getMangleFieldVal('tcpflags', false),
  5207. icmp_options: getMangleFieldVal('icmpoptions', false),
  5208. ipv4_options: getMangleFieldVal('ipv4options', false),
  5209. ttl: getMangleFieldVal('ttl', false),
  5210. // Extra tab
  5211. nth: getMangleFieldVal('nth', false),
  5212. connection_limit: getMangleFieldVal('connlimit', false),
  5213. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5214. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5215. hotspot: getMangleFieldVal('hotspot', false),
  5216. ip_fragment: getMangleFieldVal('ipfragment', false),
  5217. limit: getMangleFieldVal('limit', false),
  5218. dst_limit: getMangleFieldVal('dstlimit', false),
  5219. time: getMangleFieldVal('time', false),
  5220. psd: getMangleFieldVal('psd', false),
  5221. // Action tab
  5222. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5223. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5224. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5225. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5226. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5227. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5228. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5229. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5230. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5231. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5232. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5233. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5234. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5235. log: document.getElementById('mangle-modal-log')?.checked || false,
  5236. log_prefix: getMangleFieldVal('logprefix', false)
  5237. };
  5238. try {
  5239. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5240. method: 'POST',
  5241. headers: { 'Content-Type': 'application/json' },
  5242. body: JSON.stringify(payload)
  5243. });
  5244. if (res.ok) {
  5245. const data = await res.json();
  5246. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5247. loadFirewall(false);
  5248. if (closeAfter) {
  5249. closeMangleModal();
  5250. } else {
  5251. if (data.id) {
  5252. document.getElementById('mangle-modal-id').value = data.id;
  5253. const badge = document.getElementById('mangle-modal-badge');
  5254. if (badge) badge.innerText = `#${data.id}`;
  5255. }
  5256. }
  5257. } else {
  5258. const err = await res.json();
  5259. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5260. }
  5261. } catch (err) {
  5262. showToast('Error', err.message, 'error');
  5263. }
  5264. }
  5265. function submitSaveMangleRule(e) {
  5266. if (e && e.preventDefault) e.preventDefault();
  5267. return applyMangleRule(true);
  5268. }
  5269. function startMangleStatPolling() {
  5270. stopMangleStatPolling();
  5271. pollMangleRuleStats();
  5272. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5273. }
  5274. function stopMangleStatPolling() {
  5275. if (state.mangleStatInterval) {
  5276. clearInterval(state.mangleStatInterval);
  5277. state.mangleStatInterval = null;
  5278. }
  5279. }
  5280. async function pollMangleRuleStats() {
  5281. const id = document.getElementById('mangle-modal-id')?.value;
  5282. if (!id) {
  5283. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5284. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5285. return;
  5286. }
  5287. try {
  5288. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5289. if (!res.ok) return;
  5290. const rules = await res.json();
  5291. const r = rules.find(x => x.id === id);
  5292. if (!r) return;
  5293. const now = Date.now();
  5294. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5295. state.mangleLastTimestamp = now;
  5296. const curBytes = r.bytes || 0;
  5297. const curPackets = r.packets || 0;
  5298. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5299. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5300. state.mangleLastBytes = curBytes;
  5301. state.mangleLastPackets = curPackets;
  5302. const rateBps = Math.round((deltaBytes * 8) / dt);
  5303. const ratePkt = Math.round(deltaPkts / dt);
  5304. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5305. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5306. state.mangleStatRateHistory.push(rateBps);
  5307. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5308. state.mangleStatPktHistory.push(ratePkt);
  5309. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5310. const bEl = document.getElementById('mangle-stat-bytes');
  5311. const pEl = document.getElementById('mangle-stat-packets');
  5312. const rEl = document.getElementById('mangle-stat-rate');
  5313. const prEl = document.getElementById('mangle-stat-pktrate');
  5314. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5315. if (pEl) pEl.value = curPackets.toLocaleString();
  5316. if (rEl) rEl.value = formatBps(rateBps);
  5317. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5318. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5319. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5320. } catch (e) {
  5321. console.error('Error polling Mangle rule stats', e);
  5322. }
  5323. }
  5324. async function moveMangleRule(id, dir) {
  5325. try {
  5326. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5327. method: 'POST',
  5328. headers: { 'Content-Type': 'application/json' },
  5329. body: JSON.stringify({ direction: dir })
  5330. });
  5331. if (res.ok) loadFirewall(false);
  5332. } catch (err) {
  5333. showToast('Error', err.message, 'error');
  5334. }
  5335. }
  5336. async function toggleMangleRuleState(id, disabled) {
  5337. try {
  5338. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5339. method: 'POST',
  5340. headers: { 'Content-Type': 'application/json' },
  5341. body: JSON.stringify({ disabled })
  5342. });
  5343. if (res.ok) loadFirewall(false);
  5344. } catch (err) {
  5345. showToast('Error', err.message, 'error');
  5346. }
  5347. }
  5348. async function deleteMangleRule(id) {
  5349. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5350. try {
  5351. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5352. if (res.ok) {
  5353. showToast('Deleted', 'Mangle rule removed', 'success');
  5354. loadFirewall(false);
  5355. }
  5356. } catch (err) {
  5357. showToast('Error', err.message, 'error');
  5358. }
  5359. }
  5360. // ----------------- Address Lists -----------------
  5361. function renderAddressLists() {
  5362. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5363. const tbody = document.getElementById('addrlist-table-body');
  5364. const empty = document.getElementById('addrlist-empty');
  5365. if (!tbody) return;
  5366. tbody.innerHTML = '';
  5367. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5368. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5369. // Update filter select
  5370. const sel = document.getElementById('addrlist-filter-name');
  5371. if (sel) {
  5372. const cur = sel.value;
  5373. sel.innerHTML = '<option value="">All Lists</option>';
  5374. const set = new Set((state.addressLists || []).map(a => a.name));
  5375. set.forEach(n => {
  5376. const opt = document.createElement('option');
  5377. opt.value = n;
  5378. opt.innerText = n;
  5379. if (n === cur) opt.selected = true;
  5380. sel.appendChild(opt);
  5381. });
  5382. }
  5383. if (entries.length === 0) {
  5384. empty?.classList.remove('hidden');
  5385. return;
  5386. }
  5387. empty?.classList.add('hidden');
  5388. entries.forEach((e, idx) => {
  5389. const tr = document.createElement('tr');
  5390. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5391. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5392. tr.innerHTML = `
  5393. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5394. <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>
  5395. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5396. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5397. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5398. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5399. <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>
  5400. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5401. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5402. </td>
  5403. `;
  5404. tbody.appendChild(tr);
  5405. });
  5406. populateCommonAddrListDatalist();
  5407. }
  5408. function openAddAddrListModal() {
  5409. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5410. document.getElementById('addrlist-modal-id').value = '';
  5411. document.getElementById('addrlist-modal-name').value = '';
  5412. document.getElementById('addrlist-modal-addr').value = '';
  5413. document.getElementById('addrlist-modal-comment').value = '';
  5414. document.getElementById('addrlist-modal-disabled').checked = false;
  5415. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5416. if (submitBtn) submitBtn.innerText = 'Add to List';
  5417. document.getElementById('addrlist-modal').classList.remove('hidden');
  5418. }
  5419. function openEditAddrListModal(id) {
  5420. const e = (state.addressLists || []).find(item => item.id === id);
  5421. if (!e) return;
  5422. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5423. document.getElementById('addrlist-modal-id').value = e.id;
  5424. document.getElementById('addrlist-modal-name').value = e.name;
  5425. document.getElementById('addrlist-modal-addr').value = e.address;
  5426. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5427. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5428. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5429. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5430. document.getElementById('addrlist-modal').classList.remove('hidden');
  5431. }
  5432. function closeAddrListModal() {
  5433. document.getElementById('addrlist-modal').classList.add('hidden');
  5434. }
  5435. async function submitSaveAddrList(e) {
  5436. e.preventDefault();
  5437. const id = document.getElementById('addrlist-modal-id').value;
  5438. const name = document.getElementById('addrlist-modal-name').value.trim();
  5439. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5440. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5441. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5442. try {
  5443. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5444. method: 'POST',
  5445. headers: { 'Content-Type': 'application/json' },
  5446. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5447. });
  5448. if (res.ok) {
  5449. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5450. closeAddrListModal();
  5451. loadFirewall(false);
  5452. } else {
  5453. const err = await res.json();
  5454. showToast('Error', err.message || 'Failed to save address list', 'error');
  5455. }
  5456. } catch (err) {
  5457. showToast('Error', err.message, 'error');
  5458. }
  5459. }
  5460. async function toggleAddrListState(id, disabled) {
  5461. try {
  5462. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5463. method: 'POST',
  5464. headers: { 'Content-Type': 'application/json' },
  5465. body: JSON.stringify({ disabled })
  5466. });
  5467. if (res.ok) {
  5468. loadFirewall(false);
  5469. }
  5470. } catch (err) {
  5471. showToast('Error', err.message, 'error');
  5472. }
  5473. }
  5474. async function deleteAddrList(id) {
  5475. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5476. try {
  5477. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5478. if (res.ok) {
  5479. showToast('Deleted', 'Address list item removed', 'info');
  5480. loadFirewall(false);
  5481. }
  5482. } catch (err) {
  5483. showToast('Error', err.message, 'error');
  5484. }
  5485. }
  5486. // ----------------- Geo-Location IP Management -----------------
  5487. async function loadGeoIP() {
  5488. try {
  5489. const [statusRes, countriesRes] = await Promise.all([
  5490. fetch(`${API_BASE}/firewall/geoip/status`),
  5491. fetch(`${API_BASE}/firewall/geoip/countries`)
  5492. ]);
  5493. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5494. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5495. updateGeoHeader();
  5496. renderGeoCountries();
  5497. } catch (err) {
  5498. console.error('Failed to load GeoIP:', err);
  5499. }
  5500. }
  5501. function getGeoUsageMap() {
  5502. const usage = {};
  5503. const checkRule = (r, type) => {
  5504. ['src_geoip', 'dst_geoip'].forEach(field => {
  5505. let val = (r && r[field]) || '';
  5506. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5507. if (code) {
  5508. if (!usage[code]) usage[code] = [];
  5509. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5510. if (!usage[code].includes(label)) usage[code].push(label);
  5511. }
  5512. });
  5513. };
  5514. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5515. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5516. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5517. return usage;
  5518. }
  5519. function updateGeoHeader() {
  5520. const s = state.geoStatus || {};
  5521. const statusBadge = document.getElementById('geo-status-badge');
  5522. if (statusBadge) {
  5523. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5524. statusBadge.className = s.auto_update
  5525. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5526. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5527. }
  5528. const intervalLabel = document.getElementById('geo-interval-label');
  5529. if (intervalLabel) {
  5530. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5531. }
  5532. const usageMap = getGeoUsageMap();
  5533. const inUseCount = Object.keys(usageMap).length;
  5534. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5535. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5536. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5537. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5538. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5539. if (lastSyncEl) {
  5540. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5541. const d = new Date(s.last_updated);
  5542. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5543. } else {
  5544. lastSyncEl.innerText = 'Never (Sync Pending)';
  5545. }
  5546. }
  5547. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5548. if (nextSyncEl) {
  5549. if (s.next_update && !s.next_update.startsWith('0001')) {
  5550. const d = new Date(s.next_update);
  5551. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5552. } else {
  5553. nextSyncEl.innerText = '-';
  5554. }
  5555. }
  5556. const badge = document.getElementById('fw-badge-geo');
  5557. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5558. }
  5559. function renderGeoCountries() {
  5560. const tbody = document.getElementById('geo-table-body');
  5561. const empty = document.getElementById('geo-empty');
  5562. if (!tbody) return;
  5563. tbody.innerHTML = '';
  5564. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5565. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5566. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5567. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5568. const usageMap = getGeoUsageMap();
  5569. const countries = (state.geoCountries || []).filter(c => {
  5570. const isUsed = !!usageMap[c.code];
  5571. if (inUseOnly && !isUsed) return false;
  5572. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5573. if (continent && c.continent !== continent) return false;
  5574. if (q) {
  5575. const matchCode = c.code.toLowerCase().includes(q);
  5576. const matchName = c.name.toLowerCase().includes(q);
  5577. if (!matchCode && !matchName) return false;
  5578. }
  5579. return true;
  5580. });
  5581. if (countries.length === 0) {
  5582. empty?.classList.remove('hidden');
  5583. return;
  5584. }
  5585. empty?.classList.add('hidden');
  5586. countries.forEach(c => {
  5587. const tr = document.createElement('tr');
  5588. const isUsed = !!usageMap[c.code];
  5589. const rulesUsing = usageMap[c.code] || [];
  5590. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5591. let statusHtml = '';
  5592. if (isUsed) {
  5593. 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>`;
  5594. } else if (c.subnet_count > 0) {
  5595. 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>';
  5596. } else {
  5597. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5598. }
  5599. tr.innerHTML = `
  5600. <td class="py-2.5 px-3 text-center">
  5601. <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'}">
  5602. ${c.code}
  5603. </span>
  5604. </td>
  5605. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5606. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5607. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5608. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5609. </td>
  5610. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5611. <td class="py-2.5 px-3">
  5612. ${statusHtml}
  5613. </td>
  5614. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5615. <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>
  5616. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5617. </td>
  5618. `;
  5619. tbody.appendChild(tr);
  5620. });
  5621. }
  5622. function quickFilterGeo(preset) {
  5623. const searchInput = document.getElementById('geo-search-input');
  5624. const continentSel = document.getElementById('geo-continent-filter');
  5625. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5626. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5627. if (searchInput) searchInput.value = '';
  5628. if (continentSel) continentSel.value = '';
  5629. if (inUseCheck) inUseCheck.checked = false;
  5630. if (cachedCheck) cachedCheck.checked = false;
  5631. if (preset === 'GR') {
  5632. if (searchInput) searchInput.value = 'Greece';
  5633. } else if (preset === 'Europe') {
  5634. if (continentSel) continentSel.value = 'Europe';
  5635. } else if (preset === 'HIGHRISK') {
  5636. if (searchInput) searchInput.value = 'China';
  5637. }
  5638. renderGeoCountries();
  5639. }
  5640. async function toggleGeoCountry(code, enabled) {
  5641. try {
  5642. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5643. method: 'POST',
  5644. headers: { 'Content-Type': 'application/json' },
  5645. body: JSON.stringify({ enabled })
  5646. });
  5647. if (res.ok) {
  5648. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5649. loadGeoIP();
  5650. } else {
  5651. const err = await res.json();
  5652. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5653. }
  5654. } catch (err) {
  5655. showToast('Error', err.message, 'error');
  5656. }
  5657. }
  5658. async function updateGeoCountry(code) {
  5659. try {
  5660. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5661. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5662. if (res.ok) {
  5663. const data = await res.json();
  5664. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5665. loadGeoIP();
  5666. } else {
  5667. const err = await res.json();
  5668. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5669. }
  5670. } catch (err) {
  5671. showToast('Error', err.message, 'error');
  5672. }
  5673. }
  5674. async function triggerGeoUpdateNow() {
  5675. const spinner = document.getElementById('geo-update-spinner');
  5676. if (spinner) spinner.classList.remove('hidden');
  5677. try {
  5678. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5679. if (res.ok) {
  5680. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5681. setTimeout(() => {
  5682. loadGeoIP();
  5683. if (spinner) spinner.classList.add('hidden');
  5684. }, 2500);
  5685. } else {
  5686. const err = await res.json();
  5687. showToast('Notice', err.message || 'Update in progress', 'info');
  5688. if (spinner) spinner.classList.add('hidden');
  5689. }
  5690. } catch (err) {
  5691. showToast('Error', err.message, 'error');
  5692. if (spinner) spinner.classList.add('hidden');
  5693. }
  5694. }
  5695. async function applyGeoPreset(preset) {
  5696. try {
  5697. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5698. method: 'POST',
  5699. headers: { 'Content-Type': 'application/json' },
  5700. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5701. });
  5702. if (res.ok) {
  5703. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5704. loadGeoIP();
  5705. }
  5706. } catch (err) {
  5707. showToast('Error', err.message, 'error');
  5708. }
  5709. }
  5710. function openGeoIntervalModal() {
  5711. const s = state.geoStatus || {};
  5712. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5713. const sel = document.getElementById('geo-cfg-interval');
  5714. const customBox = document.getElementById('geo-cfg-custom-box');
  5715. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5716. const curHours = s.interval_hours || 24;
  5717. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5718. if (matchOption) {
  5719. sel.value = String(curHours);
  5720. customBox.classList.add('hidden');
  5721. } else {
  5722. sel.value = 'custom';
  5723. customHoursInput.value = curHours;
  5724. customBox.classList.remove('hidden');
  5725. }
  5726. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5727. }
  5728. function closeGeoIntervalModal() {
  5729. document.getElementById('geo-interval-modal').classList.add('hidden');
  5730. }
  5731. function toggleCustomGeoInterval() {
  5732. const val = document.getElementById('geo-cfg-interval').value;
  5733. const customBox = document.getElementById('geo-cfg-custom-box');
  5734. if (val === 'custom') {
  5735. customBox.classList.remove('hidden');
  5736. } else {
  5737. customBox.classList.add('hidden');
  5738. }
  5739. }
  5740. async function submitGeoIntervalSettings(e) {
  5741. e.preventDefault();
  5742. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5743. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5744. let hours = 24;
  5745. if (intervalVal === 'custom') {
  5746. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5747. } else {
  5748. hours = parseInt(intervalVal, 10) || 24;
  5749. }
  5750. try {
  5751. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5752. method: 'POST',
  5753. headers: { 'Content-Type': 'application/json' },
  5754. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5755. });
  5756. if (res.ok) {
  5757. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5758. closeGeoIntervalModal();
  5759. loadGeoIP();
  5760. } else {
  5761. const err = await res.json();
  5762. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5763. }
  5764. } catch (err) {
  5765. showToast('Error', err.message, 'error');
  5766. }
  5767. }
  5768. async function viewGeoSubnets(code, name) {
  5769. if (!name) {
  5770. const found = (state.geoCountries || []).find(x => x.code === code);
  5771. name = found ? found.name : code;
  5772. }
  5773. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5774. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5775. const listEl = document.getElementById('geo-subnets-list');
  5776. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5777. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5778. try {
  5779. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5780. if (res.ok) {
  5781. const data = await res.json();
  5782. const subnets = data.subnets || [];
  5783. if (subnets.length === 0) {
  5784. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5785. } else {
  5786. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5787. }
  5788. } else {
  5789. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5790. }
  5791. } catch (err) {
  5792. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5793. }
  5794. }
  5795. function closeGeoSubnetsModal() {
  5796. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5797. }
  5798. // ----------------- Active Connections Tracking -----------------
  5799. async function loadConnections() {
  5800. try {
  5801. const res = await fetch(`${API_BASE}/firewall/connections`);
  5802. const data = await res.json();
  5803. state.connections = Array.isArray(data) ? data : [];
  5804. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5805. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5806. renderConnections();
  5807. } catch (err) {
  5808. console.error('Failed to load connections:', err);
  5809. }
  5810. }
  5811. function renderConnections() {
  5812. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5813. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5814. const tbody = document.getElementById('conns-table-body');
  5815. const empty = document.getElementById('conns-empty');
  5816. if (!tbody) return;
  5817. tbody.innerHTML = '';
  5818. const conns = (state.connections || []).filter(c => {
  5819. if (protoFilter && c.protocol !== protoFilter) return false;
  5820. if (search) {
  5821. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5822. if (!line.includes(search)) return false;
  5823. }
  5824. return true;
  5825. });
  5826. if (conns.length === 0) {
  5827. empty?.classList.remove('hidden');
  5828. return;
  5829. }
  5830. empty?.classList.add('hidden');
  5831. conns.slice(0, 150).forEach(c => {
  5832. const tr = document.createElement('tr');
  5833. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5834. let stateColor = 'text-slate-400';
  5835. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5836. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5837. tr.innerHTML = `
  5838. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5839. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5840. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5841. <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>
  5842. <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>
  5843. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5844. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5845. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function killConnection(protocol, src, sport, dst, dport) {
  5854. try {
  5855. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5856. method: 'POST',
  5857. headers: { 'Content-Type': 'application/json' },
  5858. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5859. });
  5860. if (res.ok) {
  5861. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5862. loadConnections();
  5863. }
  5864. } catch (err) {
  5865. showToast('Error', err.message, 'error');
  5866. }
  5867. }
  5868. async function resetFirewallCounters() {
  5869. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5870. try {
  5871. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5872. if (res.ok) {
  5873. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5874. loadFirewall(false);
  5875. }
  5876. } catch (err) {
  5877. showToast('Error', err.message, 'error');
  5878. }
  5879. }
  5880. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5881. function switchRoutesSubTab(tab) {
  5882. state.routesSubTab = tab;
  5883. const tabs = ['routes', 'rules', 'tables'];
  5884. tabs.forEach(t => {
  5885. const panel = document.getElementById(`routes-subtab-${t}`);
  5886. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5887. if (panel) {
  5888. if (t === tab) panel.classList.remove('hidden');
  5889. else panel.classList.add('hidden');
  5890. }
  5891. if (btn) {
  5892. if (t === tab) {
  5893. 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';
  5894. } else {
  5895. 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';
  5896. }
  5897. }
  5898. });
  5899. setTimeout(initTableSorting, 50);
  5900. }
  5901. async function loadRoutes() {
  5902. try {
  5903. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5904. fetch(`${API_BASE}/routes`),
  5905. fetch(`${API_BASE}/routing/rules`),
  5906. fetch(`${API_BASE}/routing/tables`)
  5907. ]);
  5908. if (routesRes.ok) state.routes = await routesRes.json();
  5909. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5910. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5911. const bRoutes = document.getElementById('routes-badge-routes');
  5912. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5913. const showSystem = document.getElementById('prule-show-system')?.checked;
  5914. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5915. const bRules = document.getElementById('routes-badge-rules');
  5916. if (bRules) bRules.innerText = userRules.length;
  5917. const bTables = document.getElementById('routes-badge-tables');
  5918. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5919. const bRoutesCount = document.getElementById('badge-routes-count');
  5920. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5921. renderRoutesList();
  5922. renderPolicyRules();
  5923. renderRoutingTables();
  5924. } catch (err) {
  5925. console.error('Failed to load routing:', err);
  5926. }
  5927. }
  5928. function getRouteProtocolBadge(proto) {
  5929. const p = (proto || 'static').toLowerCase();
  5930. switch (p) {
  5931. case 'bgp':
  5932. 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>`;
  5933. case 'ibgp':
  5934. 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>`;
  5935. case 'ospf':
  5936. 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>`;
  5937. case 'rip':
  5938. 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>`;
  5939. case 'static':
  5940. 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>`;
  5941. case 'connected':
  5942. 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>`;
  5943. case 'dhcp':
  5944. 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>`;
  5945. case 'multicast':
  5946. 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>`;
  5947. default:
  5948. 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>`;
  5949. }
  5950. }
  5951. function renderRoutesList() {
  5952. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5953. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5954. const tbody = document.getElementById('routes-table-body');
  5955. const empty = document.getElementById('routes-empty');
  5956. if (!tbody) return;
  5957. // Update table filter select
  5958. const sel = document.getElementById('routes-filter-table');
  5959. if (sel) {
  5960. const cur = sel.value;
  5961. sel.innerHTML = '<option value="">All Tables</option>';
  5962. (state.routingTables || []).forEach(t => {
  5963. const opt = document.createElement('option');
  5964. opt.value = t.name;
  5965. opt.innerText = t.name;
  5966. if (t.name === cur) opt.selected = true;
  5967. sel.appendChild(opt);
  5968. });
  5969. }
  5970. const routes = (state.routes || []).filter(r => {
  5971. if (tableFilter && r.routing_table !== tableFilter) return false;
  5972. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5973. if (typeFilter === 'multicast' && !r.multicast) return false;
  5974. if (typeFilter === 'static' && !r.static) return false;
  5975. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5976. if (typeFilter === 'connected' && !r.connect) return false;
  5977. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5978. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5979. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5980. return true;
  5981. });
  5982. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5983. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5984. let summaryText = `${routes.length} Routes`;
  5985. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5986. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5987. const badgeEl = document.getElementById('routes-count-badge');
  5988. if (badgeEl) badgeEl.innerText = summaryText;
  5989. if (routes.length === 0) {
  5990. empty?.classList.remove('hidden');
  5991. tbody.innerHTML = '';
  5992. return;
  5993. }
  5994. empty?.classList.add('hidden');
  5995. 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(';');
  5996. if (tbody.dataset.sig === sig) {
  5997. return; // Routes table unchanged! Do not wipe DOM or flicker!
  5998. }
  5999. tbody.dataset.sig = sig;
  6000. tbody.innerHTML = '';
  6001. routes.forEach(r => {
  6002. const tr = document.createElement('tr');
  6003. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6004. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6005. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6006. let flags = '';
  6007. if (r.dynamic) flags += 'D';
  6008. if (r.active) flags += 'A';
  6009. if (r.connect) flags += 'C';
  6010. if (r.static) flags += 'S';
  6011. if (r.ecmp) flags += 'E';
  6012. if (r.multicast) flags += 'M';
  6013. if (r.disabled) flags += 'X';
  6014. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6015. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6016. if (r.check_gateway === 'internet') {
  6017. if (r.health_status === 'online') {
  6018. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6019. healthCell = `
  6020. <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)">
  6021. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6022. <span>Internet OK (${ms}ms)</span>
  6023. </span>
  6024. `;
  6025. } else if (r.health_status === 'offline') {
  6026. healthCell = `
  6027. <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.">
  6028. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6029. <span>Internet Down</span>
  6030. </span>
  6031. `;
  6032. } else {
  6033. healthCell = `
  6034. <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">
  6035. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6036. <span>Checking...</span>
  6037. </span>
  6038. `;
  6039. }
  6040. } else if (r.check_gateway === 'ping') {
  6041. if (r.health_status === 'online') {
  6042. healthCell = `
  6043. <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">
  6044. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6045. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6046. </span>
  6047. `;
  6048. } else if (r.health_status === 'offline') {
  6049. healthCell = `
  6050. <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">
  6051. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6052. <span>Gateway Dead</span>
  6053. </span>
  6054. `;
  6055. }
  6056. }
  6057. const flagDescriptions = [];
  6058. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6059. if (r.active) flagDescriptions.push('Active (A)');
  6060. if (r.connect) flagDescriptions.push('Connected (C)');
  6061. if (r.static) flagDescriptions.push('Static (S)');
  6062. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6063. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6064. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6065. tr.innerHTML = `
  6066. <td class="py-2.5 px-3 text-center">
  6067. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6068. 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')
  6069. }" title="Flags: ${flagDescriptions.join(', ')}">
  6070. ${flags || '-'}
  6071. </span>
  6072. </td>
  6073. <td class="py-2.5 px-3">
  6074. <div class="flex items-center gap-1.5 flex-wrap">
  6075. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6076. ${r.ecmp ? `
  6077. <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)">
  6078. <span>⚡ ECMP</span>
  6079. </span>
  6080. ` : ''}
  6081. ${r.multicast ? `
  6082. <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">
  6083. <span>IGMP</span>
  6084. </span>
  6085. ` : ''}
  6086. </div>
  6087. </td>
  6088. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6089. <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>
  6090. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6091. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6092. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6093. <td class="py-2.5 px-3">${healthCell}</td>
  6094. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6095. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6096. ${r.static ? `
  6097. <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>
  6098. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6099. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6100. ` : `
  6101. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6102. `}
  6103. </td>
  6104. `;
  6105. tbody.appendChild(tr);
  6106. });
  6107. }
  6108. function openAddRouteModal() {
  6109. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6110. document.getElementById('route-modal-id').value = '';
  6111. document.getElementById('route-modal-old-dst').value = '';
  6112. document.getElementById('route-modal-old-gw').value = '';
  6113. document.getElementById('route-modal-old-distance').value = '';
  6114. document.getElementById('route-modal-old-table').value = '';
  6115. document.getElementById('route-modal-old-iface').value = '';
  6116. const dstInput = document.getElementById('route-modal-dst');
  6117. const gwInput = document.getElementById('route-modal-gw');
  6118. const distInput = document.getElementById('route-modal-distance');
  6119. const ifaceSelect = document.getElementById('route-modal-iface');
  6120. const tableSelect = document.getElementById('route-modal-table');
  6121. const commentInput = document.getElementById('route-modal-comment');
  6122. const disCheck = document.getElementById('route-modal-disabled');
  6123. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6124. dstInput.disabled = false;
  6125. dstInput.value = '0.0.0.0/0';
  6126. gwInput.disabled = false;
  6127. gwInput.value = '';
  6128. distInput.disabled = false;
  6129. distInput.value = '1';
  6130. ifaceSelect.disabled = false;
  6131. tableSelect.disabled = false;
  6132. commentInput.disabled = false;
  6133. commentInput.value = '';
  6134. disCheck.disabled = false;
  6135. disCheck.checked = false;
  6136. if (saveBtn) saveBtn.classList.remove('hidden');
  6137. const checkGw = document.getElementById('route-modal-check-gw');
  6138. if (checkGw) checkGw.value = 'internet';
  6139. const checkTarget = document.getElementById('route-modal-check-target');
  6140. if (checkTarget) checkTarget.value = '1.1.1.1';
  6141. const checkInterval = document.getElementById('route-modal-check-interval');
  6142. if (checkInterval) checkInterval.value = '5';
  6143. const checkThresh = document.getElementById('route-modal-check-threshold');
  6144. if (checkThresh) checkThresh.value = '3';
  6145. toggleRouteCheckModeUI();
  6146. populateInterfaceSelect('route-modal-iface');
  6147. // Populate tables
  6148. tableSelect.innerHTML = '';
  6149. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6150. const opt = document.createElement('option');
  6151. opt.value = t.name;
  6152. opt.innerText = t.name;
  6153. if (t.name === 'main') opt.selected = true;
  6154. tableSelect.appendChild(opt);
  6155. });
  6156. document.getElementById('route-modal').classList.remove('hidden');
  6157. }
  6158. function openEditRouteModal(id) {
  6159. const r = (state.routes || []).find(route => route.id === id);
  6160. if (!r) return;
  6161. const isStatic = !!r.static;
  6162. document.getElementById('route-modal-title').innerText = isStatic
  6163. ? `Edit Route: ${r.dst_address}`
  6164. : `Route Properties (Read Only): ${r.dst_address}`;
  6165. document.getElementById('route-modal-id').value = r.id;
  6166. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6167. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6168. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6169. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6170. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6171. const dstInput = document.getElementById('route-modal-dst');
  6172. const gwInput = document.getElementById('route-modal-gw');
  6173. const distInput = document.getElementById('route-modal-distance');
  6174. const ifaceSelect = document.getElementById('route-modal-iface');
  6175. const tableSelect = document.getElementById('route-modal-table');
  6176. const commentInput = document.getElementById('route-modal-comment');
  6177. const disCheck = document.getElementById('route-modal-disabled');
  6178. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6179. dstInput.value = r.dst_address;
  6180. gwInput.value = r.gateway || '';
  6181. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6182. commentInput.value = r.comment || '';
  6183. disCheck.checked = !!r.disabled;
  6184. const checkGw = document.getElementById('route-modal-check-gw');
  6185. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6186. const checkTarget = document.getElementById('route-modal-check-target');
  6187. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6188. const checkInterval = document.getElementById('route-modal-check-interval');
  6189. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6190. const checkThresh = document.getElementById('route-modal-check-threshold');
  6191. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6192. toggleRouteCheckModeUI();
  6193. dstInput.disabled = !isStatic;
  6194. gwInput.disabled = !isStatic;
  6195. distInput.disabled = !isStatic;
  6196. ifaceSelect.disabled = !isStatic;
  6197. tableSelect.disabled = !isStatic;
  6198. commentInput.disabled = !isStatic;
  6199. disCheck.disabled = !isStatic;
  6200. if (checkGw) checkGw.disabled = !isStatic;
  6201. if (checkTarget) checkTarget.disabled = !isStatic;
  6202. if (checkInterval) checkInterval.disabled = !isStatic;
  6203. if (checkThresh) checkThresh.disabled = !isStatic;
  6204. if (saveBtn) {
  6205. if (isStatic) {
  6206. saveBtn.classList.remove('hidden');
  6207. } else {
  6208. saveBtn.classList.add('hidden');
  6209. }
  6210. }
  6211. populateInterfaceSelect('route-modal-iface', r.interface);
  6212. tableSelect.innerHTML = '';
  6213. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6214. const opt = document.createElement('option');
  6215. opt.value = t.name;
  6216. opt.innerText = t.name;
  6217. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6218. tableSelect.appendChild(opt);
  6219. });
  6220. document.getElementById('route-modal').classList.remove('hidden');
  6221. }
  6222. function closeRouteModal() {
  6223. document.getElementById('route-modal').classList.add('hidden');
  6224. }
  6225. function setRouteCheckTarget(ip) {
  6226. const inp = document.getElementById('route-modal-check-target');
  6227. if (inp) inp.value = ip;
  6228. }
  6229. function toggleRouteCheckModeUI() {
  6230. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6231. const targetRow = document.getElementById('route-row-check-target');
  6232. const paramsRow = document.getElementById('route-row-check-params');
  6233. if (mode === 'none') {
  6234. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6235. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6236. } else if (mode === 'ping') {
  6237. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6238. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6239. } else { // internet
  6240. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6241. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6242. }
  6243. }
  6244. async function submitSaveRoute(e) {
  6245. e.preventDefault();
  6246. const id = document.getElementById('route-modal-id').value;
  6247. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6248. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6249. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6250. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6251. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6252. const dst = document.getElementById('route-modal-dst').value.trim();
  6253. const gw = document.getElementById('route-modal-gw').value.trim();
  6254. const table = document.getElementById('route-modal-table').value;
  6255. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6256. const iface = document.getElementById('route-modal-iface').value;
  6257. const comment = document.getElementById('route-modal-comment').value.trim();
  6258. const disabled = document.getElementById('route-modal-disabled').checked;
  6259. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6260. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6261. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6262. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6263. if (!dst) {
  6264. showToast('Error', 'Destination address is required', 'error');
  6265. return;
  6266. }
  6267. if (!gw && !iface) {
  6268. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6269. return;
  6270. }
  6271. const payload = {
  6272. id,
  6273. old_dst_address: oldDst,
  6274. old_gateway: oldGw,
  6275. old_routing_table: oldTable,
  6276. old_interface: oldIface,
  6277. dst_address: dst,
  6278. gateway: gw || iface,
  6279. routing_table: table,
  6280. distance,
  6281. interface: iface,
  6282. comment,
  6283. disabled,
  6284. check_gateway,
  6285. check_target,
  6286. check_interval,
  6287. check_threshold
  6288. };
  6289. if (oldDistStr !== undefined && oldDistStr !== '') {
  6290. payload.old_distance = parseInt(oldDistStr, 10);
  6291. }
  6292. try {
  6293. const res = await fetch(`${API_BASE}/routes`, {
  6294. method: 'POST',
  6295. headers: { 'Content-Type': 'application/json' },
  6296. body: JSON.stringify(payload)
  6297. });
  6298. if (res.ok) {
  6299. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6300. closeRouteModal();
  6301. loadRoutes();
  6302. } else {
  6303. const err = await res.json();
  6304. showToast('Error', err.message || 'Failed to save route', 'error');
  6305. }
  6306. } catch (err) {
  6307. showToast('Error', err.message, 'error');
  6308. }
  6309. }
  6310. async function toggleRouteState(id, disabled) {
  6311. try {
  6312. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6313. method: 'POST',
  6314. headers: { 'Content-Type': 'application/json' },
  6315. body: JSON.stringify({ disabled })
  6316. });
  6317. if (res.ok) loadRoutes();
  6318. } catch (err) {
  6319. showToast('Error', err.message, 'error');
  6320. }
  6321. }
  6322. async function deleteRoute(id) {
  6323. if (!confirm('Are you sure you want to delete this route?')) return;
  6324. try {
  6325. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6326. if (res.ok) {
  6327. showToast('Deleted', 'Route removed', 'success');
  6328. loadRoutes();
  6329. }
  6330. } catch (err) {
  6331. showToast('Error', err.message, 'error');
  6332. }
  6333. }
  6334. // ----------------- Policy Rules (/ip route rule) -----------------
  6335. function renderPolicyRules() {
  6336. const tbody = document.getElementById('rules-table-body');
  6337. const empty = document.getElementById('rules-empty');
  6338. if (!tbody) return;
  6339. const showSystem = document.getElementById('prule-show-system')?.checked;
  6340. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6341. const countBadge = document.getElementById('rules-count-badge');
  6342. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6343. const bRules = document.getElementById('routes-badge-rules');
  6344. if (bRules) bRules.innerText = filtered.length;
  6345. if (filtered.length === 0) {
  6346. empty?.classList.remove('hidden');
  6347. tbody.innerHTML = '';
  6348. return;
  6349. }
  6350. empty?.classList.add('hidden');
  6351. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6352. if (tbody.dataset.sig === sig) return;
  6353. tbody.dataset.sig = sig;
  6354. tbody.innerHTML = '';
  6355. filtered.forEach(pr => {
  6356. const isSys = pr.is_default || pr.is_system;
  6357. const tr = document.createElement('tr');
  6358. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6359. tr.innerHTML = `
  6360. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6361. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6362. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6363. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6364. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6365. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6366. <td class="py-2.5 px-3 text-right font-sans">
  6367. ${!pr.is_default ? `
  6368. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6369. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6370. </td>
  6371. `;
  6372. tbody.appendChild(tr);
  6373. });
  6374. }
  6375. function openAddPolicyRuleModal() {
  6376. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6377. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6378. document.getElementById('prule-modal-mark').value = '';
  6379. document.getElementById('prule-modal-src').value = '';
  6380. document.getElementById('prule-modal-dst').value = '';
  6381. const sel = document.getElementById('prule-modal-table');
  6382. sel.innerHTML = '';
  6383. (state.routingTables || []).forEach(t => {
  6384. const opt = document.createElement('option');
  6385. opt.value = t.name;
  6386. opt.innerText = t.name;
  6387. sel.appendChild(opt);
  6388. });
  6389. document.getElementById('prule-modal').classList.remove('hidden');
  6390. }
  6391. function closePolicyRuleModal() {
  6392. document.getElementById('prule-modal').classList.add('hidden');
  6393. }
  6394. async function submitSavePolicyRule(e) {
  6395. e.preventDefault();
  6396. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6397. const mark = document.getElementById('prule-modal-mark').value.trim();
  6398. const src = document.getElementById('prule-modal-src').value.trim();
  6399. const dst = document.getElementById('prule-modal-dst').value.trim();
  6400. const table = document.getElementById('prule-modal-table').value;
  6401. const action = document.getElementById('prule-modal-action').value;
  6402. try {
  6403. const res = await fetch(`${API_BASE}/routing/rules`, {
  6404. method: 'POST',
  6405. headers: { 'Content-Type': 'application/json' },
  6406. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6407. });
  6408. if (res.ok) {
  6409. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6410. closePolicyRuleModal();
  6411. loadRoutes();
  6412. } else {
  6413. const err = await res.json();
  6414. showToast('Error', err.message, 'error');
  6415. }
  6416. } catch (err) {
  6417. showToast('Error', err.message, 'error');
  6418. }
  6419. }
  6420. async function deletePolicyRule(id) {
  6421. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6422. try {
  6423. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6424. if (res.ok) {
  6425. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6426. loadRoutes();
  6427. }
  6428. } catch (err) {
  6429. showToast('Error', err.message, 'error');
  6430. }
  6431. }
  6432. // ----------------- Routing Tables -----------------
  6433. function renderRoutingTables() {
  6434. const tbody = document.getElementById('tables-table-body');
  6435. if (!tbody) return;
  6436. const tables = state.routingTables || [];
  6437. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6438. if (tbody.dataset.sig === sig) return;
  6439. tbody.dataset.sig = sig;
  6440. tbody.innerHTML = '';
  6441. (state.routingTables || []).forEach(t => {
  6442. const tr = document.createElement('tr');
  6443. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6444. tr.innerHTML = `
  6445. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6446. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6447. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6448. `;
  6449. tbody.appendChild(tr);
  6450. });
  6451. }
  6452. function openAddTableModal() {
  6453. document.getElementById('table-modal-name').value = '';
  6454. document.getElementById('table-modal-id').value = '';
  6455. document.getElementById('table-modal-comment').value = '';
  6456. document.getElementById('table-modal').classList.remove('hidden');
  6457. }
  6458. function closeTableModal() {
  6459. document.getElementById('table-modal').classList.add('hidden');
  6460. }
  6461. async function submitSaveTable(e) {
  6462. e.preventDefault();
  6463. const name = document.getElementById('table-modal-name').value.trim();
  6464. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6465. const comment = document.getElementById('table-modal-comment').value.trim();
  6466. try {
  6467. const res = await fetch(`${API_BASE}/routing/tables`, {
  6468. method: 'POST',
  6469. headers: { 'Content-Type': 'application/json' },
  6470. body: JSON.stringify({ name, table_id: id, comment })
  6471. });
  6472. if (res.ok) {
  6473. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6474. closeTableModal();
  6475. loadRoutes();
  6476. } else {
  6477. const err = await res.json();
  6478. showToast('Error', err.message, 'error');
  6479. }
  6480. } catch (err) {
  6481. showToast('Error', err.message, 'error');
  6482. }
  6483. }
  6484. async function loadDebianConfig() {
  6485. const view = document.getElementById('debian-config-view');
  6486. view.innerText = 'Generating live configuration...';
  6487. try {
  6488. const res = await fetch(`${API_BASE}/debian/config`);
  6489. const data = await res.json();
  6490. view.innerText = data.content || '# Empty config';
  6491. } catch (err) {
  6492. view.innerText = 'Failed to generate Debian network config.';
  6493. }
  6494. }
  6495. async function saveDebianConfig() {
  6496. try {
  6497. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6498. const data = await res.json();
  6499. if (res.ok) {
  6500. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6501. loadDebianConfig();
  6502. }
  6503. } catch (err) {
  6504. showToast('Error', err.message, 'error');
  6505. }
  6506. }
  6507. function showToast(title, message, type = 'info') {
  6508. const container = document.getElementById('toast-container');
  6509. const toast = document.createElement('div');
  6510. const borderColors = {
  6511. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6512. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6513. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6514. };
  6515. 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}`;
  6516. toast.innerHTML = `
  6517. <div class="flex-1">
  6518. <div class="font-bold text-xs text-white">${title}</div>
  6519. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6520. </div>
  6521. `;
  6522. container.appendChild(toast);
  6523. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6524. setTimeout(() => {
  6525. toast.classList.add('opacity-0', 'translate-y-2');
  6526. setTimeout(() => toast.remove(), 300);
  6527. }, 4000);
  6528. }
  6529. function formatTraffic(bytesPerSec) {
  6530. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6531. const kb = bytesPerSec / 1024;
  6532. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6533. const mb = kb / 1024;
  6534. return `${mb.toFixed(2)} MB/s`;
  6535. }
  6536. function toggleSidebar() {
  6537. const sb = document.getElementById('sidebar');
  6538. sb.classList.toggle('-translate-x-full');
  6539. }
  6540. // ======================== EoIP (Ethernet over IP) ========================
  6541. async function loadEoIP(populate = true) {
  6542. try {
  6543. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6544. const data = await res.json();
  6545. state.eoipTunnels = Array.isArray(data) ? data : [];
  6546. const badge = document.getElementById('eoip-count-badge');
  6547. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6548. const sideBadge = document.getElementById('badge-eoip-count');
  6549. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6550. renderEoIPTunnels();
  6551. } catch (err) {
  6552. console.error('Failed to load EoIP:', err);
  6553. }
  6554. }
  6555. function renderEoIPTunnels() {
  6556. const tbody = document.getElementById('eoip-table-body');
  6557. const empty = document.getElementById('eoip-empty');
  6558. if (!tbody) return;
  6559. tbody.innerHTML = '';
  6560. const tunnels = state.eoipTunnels || [];
  6561. if (tunnels.length === 0) {
  6562. empty?.classList.remove('hidden');
  6563. return;
  6564. }
  6565. empty?.classList.add('hidden');
  6566. tunnels.forEach(t => {
  6567. const tr = document.createElement('tr');
  6568. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6569. tr.innerHTML = `
  6570. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6571. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6572. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6573. <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>
  6574. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6575. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6576. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6577. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6578. <td class="py-2.5 px-3 font-mono text-[11px]">
  6579. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6580. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6581. </td>
  6582. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6583. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6584. <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>
  6585. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6586. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6587. </td>
  6588. `;
  6589. tbody.appendChild(tr);
  6590. });
  6591. }
  6592. function openAddEoIPModal() {
  6593. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6594. document.getElementById('eoip-modal-id').value = '';
  6595. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6596. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6597. document.getElementById('eoip-modal-remote').value = '';
  6598. document.getElementById('eoip-modal-ip').value = '';
  6599. document.getElementById('eoip-modal-local').value = '';
  6600. document.getElementById('eoip-modal-mac').value = '';
  6601. document.getElementById('eoip-modal-mtu').value = '1500';
  6602. document.getElementById('eoip-modal-comment').value = '';
  6603. document.getElementById('eoip-modal-clampmss').checked = true;
  6604. document.getElementById('eoip-modal-disabled').checked = false;
  6605. document.getElementById('eoip-modal').classList.remove('hidden');
  6606. }
  6607. function openEditEoIPModal(id) {
  6608. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6609. if (!t) return;
  6610. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6611. document.getElementById('eoip-modal-id').value = t.id;
  6612. document.getElementById('eoip-modal-name').value = t.name;
  6613. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6614. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6615. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6616. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6617. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6618. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6619. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6620. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6621. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6622. document.getElementById('eoip-modal').classList.remove('hidden');
  6623. }
  6624. function closeEoIPModal() {
  6625. document.getElementById('eoip-modal').classList.add('hidden');
  6626. }
  6627. async function submitSaveEoIP(e) {
  6628. e.preventDefault();
  6629. const id = document.getElementById('eoip-modal-id').value;
  6630. const name = document.getElementById('eoip-modal-name').value.trim();
  6631. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6632. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6633. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6634. const local = document.getElementById('eoip-modal-local').value.trim();
  6635. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6636. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6637. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6638. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6639. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6640. try {
  6641. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6642. method: 'POST',
  6643. headers: { 'Content-Type': 'application/json' },
  6644. body: JSON.stringify({
  6645. id,
  6646. name,
  6647. tunnel_id: tunnelId,
  6648. remote_address: remote,
  6649. ip_address: ipAddress,
  6650. local_address: local,
  6651. mac_address: mac,
  6652. mtu,
  6653. clamp_mss: clampMss,
  6654. comment,
  6655. disabled
  6656. })
  6657. });
  6658. if (res.ok) {
  6659. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6660. closeEoIPModal();
  6661. loadEoIP(false);
  6662. fetchData(false);
  6663. } else {
  6664. const err = await res.json();
  6665. showToast('Error', err.message, 'error');
  6666. }
  6667. } catch (err) {
  6668. showToast('Error', err.message, 'error');
  6669. }
  6670. }
  6671. async function toggleEoIPState(id, disabled) {
  6672. try {
  6673. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6674. method: 'POST',
  6675. headers: { 'Content-Type': 'application/json' },
  6676. body: JSON.stringify({ disabled })
  6677. });
  6678. if (res.ok) {
  6679. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6680. loadEoIP(false);
  6681. fetchData(false);
  6682. }
  6683. } catch (err) {
  6684. showToast('Error', err.message, 'error');
  6685. }
  6686. }
  6687. async function deleteEoIP(id) {
  6688. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6689. try {
  6690. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6691. if (res.ok) {
  6692. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6693. loadEoIP(false);
  6694. fetchData(false);
  6695. }
  6696. } catch (err) {
  6697. showToast('Error', err.message, 'error');
  6698. }
  6699. }
  6700. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6701. async function loadAeroTUN(populate = true) {
  6702. try {
  6703. const [tunnelsRes, statsRes] = await Promise.all([
  6704. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6705. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6706. ]);
  6707. if (tunnelsRes.ok) {
  6708. const data = await tunnelsRes.json();
  6709. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6710. }
  6711. if (statsRes.ok) {
  6712. state.aerotunStats = await statsRes.json();
  6713. }
  6714. const countBadge = document.getElementById('aerotun-count-badge');
  6715. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6716. const sideBadge = document.getElementById('badge-aerotun-count');
  6717. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6718. renderAeroTUN();
  6719. } catch (err) {
  6720. console.error('Failed to load AeroTUN:', err);
  6721. }
  6722. }
  6723. function renderAeroTUN() {
  6724. const tbody = document.getElementById('aerotun-table-body');
  6725. const empty = document.getElementById('aerotun-empty');
  6726. // Update summary cards
  6727. const stats = state.aerotunStats || {};
  6728. const tunnels = state.aerotunTunnels || [];
  6729. const statActive = document.getElementById('aerotun-stat-active');
  6730. if (statActive) {
  6731. const activeCount = tunnels.filter(t => t.running).length;
  6732. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6733. }
  6734. const statSaved = document.getElementById('aerotun-stat-saved');
  6735. if (statSaved) {
  6736. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6737. }
  6738. const statRatio = document.getElementById('aerotun-stat-ratio');
  6739. if (statRatio) {
  6740. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6741. }
  6742. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6743. if (statTraffic) {
  6744. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6745. }
  6746. if (!tbody) return;
  6747. tbody.innerHTML = '';
  6748. if (tunnels.length === 0) {
  6749. empty?.classList.remove('hidden');
  6750. return;
  6751. }
  6752. empty?.classList.add('hidden');
  6753. tunnels.forEach(t => {
  6754. const tr = document.createElement('tr');
  6755. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6756. const modeBadge = t.mode === 'server'
  6757. ? `<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>`
  6758. : `<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>`;
  6759. const endpointInfo = t.mode === 'server'
  6760. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6761. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6762. const compBadge = t.compression
  6763. ? `<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>`
  6764. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6765. const activePeer = t.active_peer_endpoint
  6766. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6767. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6768. const rawRx = formatBytes(t.rx_bytes || 0);
  6769. const rawTx = formatBytes(t.tx_bytes || 0);
  6770. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6771. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6772. tr.innerHTML = `
  6773. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6774. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6775. <span>${escapeHtml(t.name)}</span>
  6776. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6777. </td>
  6778. <td class="py-2.5 px-3">${modeBadge}</td>
  6779. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6780. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6781. <td class="py-2.5 px-3">${compBadge}</td>
  6782. <td class="py-2.5 px-3">${activePeer}</td>
  6783. <td class="py-2.5 px-3 font-mono text-[11px]">
  6784. <span class="text-emerald-400">↓ ${rawRx}</span>
  6785. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6786. </td>
  6787. <td class="py-2.5 px-3 font-mono text-[11px]">
  6788. <span class="text-slate-400">↓ ${wireRx}</span>
  6789. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6790. </td>
  6791. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6792. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6793. ${t.running
  6794. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6795. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6796. }
  6797. <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>
  6798. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6799. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6800. </td>
  6801. `;
  6802. tbody.appendChild(tr);
  6803. });
  6804. }
  6805. function onAeroTUNModeChange() {
  6806. const mode = document.getElementById('aerotun-modal-mode').value;
  6807. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6808. const portInput = document.getElementById('aerotun-modal-port');
  6809. if (mode === 'server') {
  6810. if (!portInput.value) portInput.value = '51830';
  6811. endpointInput.placeholder = 'Optional / learned roaming peer';
  6812. } else {
  6813. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6814. if (!portInput.value) portInput.value = '';
  6815. }
  6816. }
  6817. async function generateAeroTUNKey() {
  6818. try {
  6819. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6820. if (res.ok) {
  6821. const data = await res.json();
  6822. document.getElementById('aerotun-modal-psk').value = data.key;
  6823. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6824. }
  6825. } catch (err) {
  6826. const arr = new Uint8Array(32);
  6827. crypto.getRandomValues(arr);
  6828. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6829. document.getElementById('aerotun-modal-psk').value = hex;
  6830. }
  6831. }
  6832. function openAddAeroTUNModal() {
  6833. const tunnels = state.aerotunTunnels || [];
  6834. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6835. document.getElementById('aerotun-modal-id').value = '';
  6836. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6837. document.getElementById('aerotun-modal-mode').value = 'server';
  6838. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6839. document.getElementById('aerotun-modal-endpoint').value = '';
  6840. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6841. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6842. document.getElementById('aerotun-modal-psk').value = '';
  6843. document.getElementById('aerotun-modal-mtu').value = '1420';
  6844. document.getElementById('aerotun-modal-comment').value = '';
  6845. document.getElementById('aerotun-modal-compression').checked = true;
  6846. document.getElementById('aerotun-modal-defroute').checked = false;
  6847. document.getElementById('aerotun-modal-disabled').checked = false;
  6848. generateAeroTUNKey();
  6849. onAeroTUNModeChange();
  6850. document.getElementById('aerotun-modal').classList.remove('hidden');
  6851. }
  6852. function openEditAeroTUNModal(id) {
  6853. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6854. if (!t) return;
  6855. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6856. document.getElementById('aerotun-modal-id').value = t.id;
  6857. document.getElementById('aerotun-modal-name').value = t.name;
  6858. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6859. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6860. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6861. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6862. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6863. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6864. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6865. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6866. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6867. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6868. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6869. onAeroTUNModeChange();
  6870. document.getElementById('aerotun-modal').classList.remove('hidden');
  6871. }
  6872. function closeAeroTUNModal() {
  6873. document.getElementById('aerotun-modal').classList.add('hidden');
  6874. }
  6875. async function submitSaveAeroTUN(e) {
  6876. e.preventDefault();
  6877. const id = document.getElementById('aerotun-modal-id').value;
  6878. const name = document.getElementById('aerotun-modal-name').value.trim();
  6879. const mode = document.getElementById('aerotun-modal-mode').value;
  6880. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6881. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6882. const local = document.getElementById('aerotun-modal-local').value.trim();
  6883. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6884. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6885. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6886. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6887. const compression = document.getElementById('aerotun-modal-compression').checked;
  6888. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6889. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6890. if (mode === 'client' && !endpoint) {
  6891. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6892. return;
  6893. }
  6894. if (!psk) {
  6895. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6896. return;
  6897. }
  6898. try {
  6899. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6900. method: 'POST',
  6901. headers: { 'Content-Type': 'application/json' },
  6902. body: JSON.stringify({
  6903. id,
  6904. name,
  6905. mode,
  6906. listen_port: port,
  6907. remote_endpoint: endpoint,
  6908. local_address: local,
  6909. peer_address: peer,
  6910. psk,
  6911. mtu,
  6912. compression,
  6913. default_route: defaultRoute,
  6914. comment,
  6915. disabled
  6916. })
  6917. });
  6918. if (res.ok) {
  6919. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6920. closeAeroTUNModal();
  6921. loadAeroTUN(false);
  6922. fetchData(false);
  6923. } else {
  6924. const err = await res.text();
  6925. showToast('Error Saving Tunnel', err, 'error');
  6926. }
  6927. } catch (err) {
  6928. showToast('Network Error', err.message, 'error');
  6929. }
  6930. }
  6931. async function startAeroTUNTunnel(id) {
  6932. try {
  6933. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6934. if (res.ok) {
  6935. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6936. loadAeroTUN(false);
  6937. fetchData(false);
  6938. } else {
  6939. const err = await res.text();
  6940. showToast('Failed to Start', err, 'error');
  6941. }
  6942. } catch (err) {
  6943. showToast('Error', err.message, 'error');
  6944. }
  6945. }
  6946. async function stopAeroTUNTunnel(id) {
  6947. try {
  6948. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6949. if (res.ok) {
  6950. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6951. loadAeroTUN(false);
  6952. fetchData(false);
  6953. } else {
  6954. const err = await res.text();
  6955. showToast('Failed to Stop', err, 'error');
  6956. }
  6957. } catch (err) {
  6958. showToast('Error', err.message, 'error');
  6959. }
  6960. }
  6961. async function toggleAeroTUNState(id, disabled) {
  6962. try {
  6963. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6964. method: 'POST',
  6965. headers: { 'Content-Type': 'application/json' },
  6966. body: JSON.stringify({ disabled })
  6967. });
  6968. if (res.ok) {
  6969. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6970. loadAeroTUN(false);
  6971. fetchData(false);
  6972. }
  6973. } catch (err) {
  6974. showToast('Error', err.message, 'error');
  6975. }
  6976. }
  6977. async function deleteAeroTUN(id) {
  6978. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6979. try {
  6980. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6981. if (res.ok) {
  6982. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6983. loadAeroTUN(false);
  6984. fetchData(false);
  6985. }
  6986. } catch (err) {
  6987. showToast('Error', err.message, 'error');
  6988. }
  6989. }
  6990. // ======================== PPP Central Hub & Servers ========================
  6991. function switchPPPSubTab(tab) {
  6992. state.pppSubTab = tab;
  6993. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6994. tabs.forEach(t => {
  6995. const panel = document.getElementById(`ppp-subtab-${t}`);
  6996. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6997. if (panel) {
  6998. if (t === tab) panel.classList.remove('hidden');
  6999. else panel.classList.add('hidden');
  7000. }
  7001. if (btn) {
  7002. if (t === tab) {
  7003. 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';
  7004. } else {
  7005. 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';
  7006. }
  7007. }
  7008. });
  7009. const addBtn = document.getElementById('ppp-primary-add-btn');
  7010. if (addBtn) {
  7011. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7012. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7013. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7014. else addBtn.innerHTML = '<span>Save Config</span>';
  7015. }
  7016. if (tab === 'active') loadPPPSessions();
  7017. }
  7018. function openCurrentPPPModal() {
  7019. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7020. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7021. else if (state.pppSubTab === 'active') loadPPPSessions();
  7022. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7023. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7024. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7025. }
  7026. async function loadPPP(populateDropdowns = true) {
  7027. await Promise.all([
  7028. loadPPPSecrets(),
  7029. loadPPPProfiles(),
  7030. loadPPPServers(),
  7031. loadPPPSessions()
  7032. ]);
  7033. }
  7034. async function loadPPPSecrets() {
  7035. try {
  7036. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7037. const data = await res.json();
  7038. state.pppSecrets = Array.isArray(data) ? data : [];
  7039. const b = document.getElementById('ppp-badge-secrets');
  7040. if (b) b.innerText = state.pppSecrets.length;
  7041. const b2 = document.getElementById('secrets-count-badge');
  7042. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7043. renderPPPSecrets();
  7044. } catch (err) {
  7045. console.error('Failed to load PPP secrets:', err);
  7046. }
  7047. }
  7048. function renderPPPSecrets() {
  7049. const tbody = document.getElementById('secrets-table-body');
  7050. const empty = document.getElementById('secrets-empty');
  7051. if (!tbody) return;
  7052. tbody.innerHTML = '';
  7053. const secrets = state.pppSecrets || [];
  7054. if (secrets.length === 0) {
  7055. empty?.classList.remove('hidden');
  7056. return;
  7057. }
  7058. empty?.classList.add('hidden');
  7059. secrets.forEach(s => {
  7060. const tr = document.createElement('tr');
  7061. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7062. tr.innerHTML = `
  7063. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7064. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7065. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7066. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7067. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7068. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7069. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7070. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7071. <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>
  7072. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7073. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7074. </td>
  7075. `;
  7076. tbody.appendChild(tr);
  7077. });
  7078. }
  7079. async function loadPPPProfiles() {
  7080. try {
  7081. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7082. const data = await res.json();
  7083. state.pppProfiles = Array.isArray(data) ? data : [];
  7084. const b = document.getElementById('ppp-badge-profiles');
  7085. if (b) b.innerText = state.pppProfiles.length;
  7086. const b2 = document.getElementById('profiles-count-badge');
  7087. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7088. // Populate profile selects across modals
  7089. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7090. selects.forEach(sid => {
  7091. const el = document.getElementById(sid);
  7092. if (!el) return;
  7093. const cur = el.value;
  7094. el.innerHTML = '';
  7095. state.pppProfiles.forEach(p => {
  7096. const opt = document.createElement('option');
  7097. opt.value = p.name;
  7098. opt.innerText = `${p.name} (${p.remote_address})`;
  7099. if (p.name === cur) opt.selected = true;
  7100. el.appendChild(opt);
  7101. });
  7102. });
  7103. renderPPPProfiles();
  7104. } catch (err) {
  7105. console.error('Failed to load PPP profiles:', err);
  7106. }
  7107. }
  7108. function renderPPPProfiles() {
  7109. const tbody = document.getElementById('profiles-table-body');
  7110. if (!tbody) return;
  7111. tbody.innerHTML = '';
  7112. (state.pppProfiles || []).forEach(p => {
  7113. const isDefault = p.name.startsWith('default');
  7114. const tr = document.createElement('tr');
  7115. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7116. tr.innerHTML = `
  7117. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7118. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7119. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7120. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7121. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7122. <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>
  7123. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7124. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7125. ${!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>`}
  7126. </td>
  7127. `;
  7128. tbody.appendChild(tr);
  7129. });
  7130. }
  7131. async function loadPPPServers() {
  7132. try {
  7133. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7134. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7135. fetch(`${API_BASE}/vpn/servers/pptp`),
  7136. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7137. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7138. ]);
  7139. if (pppoeRes.ok) {
  7140. state.pppoeServer = await pppoeRes.json();
  7141. const s = state.pppoeServer;
  7142. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7143. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7144. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7145. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7146. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7147. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7148. const pill = document.getElementById('pppoe-server-status-pill');
  7149. if (pill) {
  7150. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7151. 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';
  7152. }
  7153. setDotBadge('ppp-badge-pppoe-state', s.running);
  7154. }
  7155. if (pptpRes.ok) {
  7156. state.pptpServer = await pptpRes.json();
  7157. const s = state.pptpServer;
  7158. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7159. document.getElementById('pptp-server-port').value = s.port || 1723;
  7160. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7161. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7162. const pill = document.getElementById('pptp-server-status-pill');
  7163. if (pill) {
  7164. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7165. 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';
  7166. }
  7167. setDotBadge('ppp-badge-pptp-state', s.running);
  7168. }
  7169. if (l2tpRes.ok) {
  7170. state.l2tpServer = await l2tpRes.json();
  7171. const s = state.l2tpServer;
  7172. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7173. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7174. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7175. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7176. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7177. const pill = document.getElementById('l2tp-server-status-pill');
  7178. if (pill) {
  7179. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7180. 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';
  7181. }
  7182. setDotBadge('ppp-badge-l2tp-state', s.running);
  7183. }
  7184. if (ipsecRes.ok) {
  7185. state.ipsecServer = await ipsecRes.json();
  7186. const s = state.ipsecServer;
  7187. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7188. if (modalEn) modalEn.checked = !!s.enabled;
  7189. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7190. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7191. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7192. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7193. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7194. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7195. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7196. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7197. const pill = document.getElementById('modal-ipsec-server-status');
  7198. if (pill) {
  7199. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7200. 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';
  7201. }
  7202. }
  7203. } catch (err) {
  7204. console.error('Failed to load VPN servers:', err);
  7205. }
  7206. }
  7207. async function loadPPPSessions() {
  7208. try {
  7209. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7210. const data = await res.json();
  7211. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7212. const b = document.getElementById('ppp-badge-active');
  7213. if (b) b.innerText = state.pppActiveSessions.length;
  7214. const sideB = document.getElementById('badge-ppp-sessions');
  7215. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7216. renderPPPSessions();
  7217. } catch (err) {
  7218. console.error('Failed to load active PPP sessions:', err);
  7219. }
  7220. }
  7221. function renderPPPSessions() {
  7222. const tbody = document.getElementById('active-ppp-table-body');
  7223. const empty = document.getElementById('active-ppp-empty');
  7224. if (!tbody) return;
  7225. tbody.innerHTML = '';
  7226. const list = state.pppActiveSessions || [];
  7227. if (list.length === 0) {
  7228. empty?.classList.remove('hidden');
  7229. return;
  7230. }
  7231. empty?.classList.add('hidden');
  7232. list.forEach(s => {
  7233. const tr = document.createElement('tr');
  7234. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7235. tr.innerHTML = `
  7236. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7237. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7238. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7239. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7240. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7241. <td class="py-2.5 px-3 text-[11px]">
  7242. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7243. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7244. </td>
  7245. <td class="py-2.5 px-3 text-right font-sans">
  7246. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7247. </td>
  7248. `;
  7249. tbody.appendChild(tr);
  7250. });
  7251. }
  7252. async function disconnectPPPSession(iface) {
  7253. if (!confirm(`Disconnect session ${iface}?`)) return;
  7254. try {
  7255. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7256. if (res.ok) {
  7257. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7258. loadPPPSessions();
  7259. }
  7260. } catch (err) {
  7261. showToast('Error', err.message, 'error');
  7262. }
  7263. }
  7264. // PPP Secret Modal handlers
  7265. function openAddPPPSecretModal() {
  7266. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7267. document.getElementById('secret-modal-id').value = '';
  7268. document.getElementById('secret-modal-name').value = '';
  7269. document.getElementById('secret-modal-password').value = '';
  7270. document.getElementById('secret-modal-service').value = 'any';
  7271. document.getElementById('secret-modal-profile').value = 'default';
  7272. document.getElementById('secret-modal-local').value = '';
  7273. document.getElementById('secret-modal-remote').value = '';
  7274. document.getElementById('secret-modal-comment').value = '';
  7275. document.getElementById('secret-modal-disabled').checked = false;
  7276. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7277. }
  7278. function openEditPPPSecretModal(id) {
  7279. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7280. if (!s) return;
  7281. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7282. document.getElementById('secret-modal-id').value = s.id;
  7283. document.getElementById('secret-modal-name').value = s.name;
  7284. document.getElementById('secret-modal-password').value = s.password;
  7285. document.getElementById('secret-modal-service').value = s.service || 'any';
  7286. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7287. document.getElementById('secret-modal-local').value = s.local_address || '';
  7288. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7289. document.getElementById('secret-modal-comment').value = s.comment || '';
  7290. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7291. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7292. }
  7293. function closePPPSecretModal() {
  7294. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7295. }
  7296. async function submitSavePPPSecret(e) {
  7297. e.preventDefault();
  7298. const id = document.getElementById('secret-modal-id').value;
  7299. const name = document.getElementById('secret-modal-name').value.trim();
  7300. const password = document.getElementById('secret-modal-password').value.trim();
  7301. const service = document.getElementById('secret-modal-service').value;
  7302. const profile = document.getElementById('secret-modal-profile').value;
  7303. const local = document.getElementById('secret-modal-local').value.trim();
  7304. const remote = document.getElementById('secret-modal-remote').value.trim();
  7305. const comment = document.getElementById('secret-modal-comment').value.trim();
  7306. const disabled = document.getElementById('secret-modal-disabled').checked;
  7307. try {
  7308. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7309. method: 'POST',
  7310. headers: { 'Content-Type': 'application/json' },
  7311. body: JSON.stringify({
  7312. id,
  7313. name,
  7314. password,
  7315. service,
  7316. profile,
  7317. local_address: local,
  7318. remote_address: remote,
  7319. comment,
  7320. disabled
  7321. })
  7322. });
  7323. if (res.ok) {
  7324. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7325. closePPPSecretModal();
  7326. loadPPPSecrets();
  7327. } else {
  7328. const err = await res.json();
  7329. showToast('Error', err.message, 'error');
  7330. }
  7331. } catch (err) {
  7332. showToast('Error', err.message, 'error');
  7333. }
  7334. }
  7335. async function togglePPPSecretState(id, disabled) {
  7336. try {
  7337. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7338. method: 'POST',
  7339. headers: { 'Content-Type': 'application/json' },
  7340. body: JSON.stringify({ disabled })
  7341. });
  7342. if (res.ok) {
  7343. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7344. loadPPPSecrets();
  7345. }
  7346. } catch (err) {
  7347. showToast('Error', err.message, 'error');
  7348. }
  7349. }
  7350. async function deletePPPSecret(id) {
  7351. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7352. try {
  7353. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7354. if (res.ok) {
  7355. showToast('Deleted', 'Secret account removed', 'success');
  7356. loadPPPSecrets();
  7357. }
  7358. } catch (err) {
  7359. showToast('Error', err.message, 'error');
  7360. }
  7361. }
  7362. // PPP Profile Modal handlers
  7363. function openAddPPPProfileModal() {
  7364. document.getElementById('profile-modal-name').value = '';
  7365. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7366. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7367. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7368. document.getElementById('profile-modal-encryption').value = 'required';
  7369. document.getElementById('profile-modal-onlyone').checked = true;
  7370. document.getElementById('profile-modal-comment').value = '';
  7371. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7372. }
  7373. function closePPPProfileModal() {
  7374. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7375. }
  7376. async function submitSavePPPProfile(e) {
  7377. e.preventDefault();
  7378. const name = document.getElementById('profile-modal-name').value.trim();
  7379. const local = document.getElementById('profile-modal-local').value.trim();
  7380. const remote = document.getElementById('profile-modal-remote').value.trim();
  7381. const dns = document.getElementById('profile-modal-dns').value.trim();
  7382. const enc = document.getElementById('profile-modal-encryption').value;
  7383. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7384. const comment = document.getElementById('profile-modal-comment').value.trim();
  7385. try {
  7386. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7387. method: 'POST',
  7388. headers: { 'Content-Type': 'application/json' },
  7389. body: JSON.stringify({
  7390. id: name,
  7391. name,
  7392. local_address: local,
  7393. remote_address: remote,
  7394. dns_servers: dns,
  7395. use_encryption: enc,
  7396. only_one: onlyone,
  7397. comment
  7398. })
  7399. });
  7400. if (res.ok) {
  7401. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7402. closePPPProfileModal();
  7403. loadPPPProfiles();
  7404. } else {
  7405. const err = await res.json();
  7406. showToast('Error', err.message, 'error');
  7407. }
  7408. } catch (err) {
  7409. showToast('Error', err.message, 'error');
  7410. }
  7411. }
  7412. async function deletePPPProfile(name) {
  7413. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7414. try {
  7415. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7416. if (res.ok) {
  7417. showToast('Deleted', 'Profile removed', 'success');
  7418. loadPPPProfiles();
  7419. } else {
  7420. const err = await res.json();
  7421. showToast('Error', err.message, 'error');
  7422. }
  7423. } catch (err) {
  7424. showToast('Error', err.message, 'error');
  7425. }
  7426. }
  7427. // Server Config submissions
  7428. async function savePPPoEServerConfig(e) {
  7429. e.preventDefault();
  7430. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7431. const name = document.getElementById('pppoe-server-name').value.trim();
  7432. const iface = document.getElementById('pppoe-server-iface').value;
  7433. const profile = document.getElementById('pppoe-server-profile').value;
  7434. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7435. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7436. try {
  7437. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7438. method: 'POST',
  7439. headers: { 'Content-Type': 'application/json' },
  7440. body: JSON.stringify({
  7441. enabled,
  7442. service_name: name,
  7443. interface: iface,
  7444. default_profile: profile,
  7445. max_mtu: mtu,
  7446. max_mru: mtu,
  7447. one_session_per_host: onesession
  7448. })
  7449. });
  7450. if (res.ok) {
  7451. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7452. loadPPPServers();
  7453. fetchData(false);
  7454. } else {
  7455. const err = await res.json();
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. } catch (err) {
  7459. showToast('Error', err.message, 'error');
  7460. }
  7461. }
  7462. async function savePPTPServerConfig(e) {
  7463. e.preventDefault();
  7464. const enabled = document.getElementById('pptp-server-enabled').checked;
  7465. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7466. const profile = document.getElementById('pptp-server-profile').value;
  7467. const mppe = document.getElementById('pptp-server-mppe').checked;
  7468. try {
  7469. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7470. method: 'POST',
  7471. headers: { 'Content-Type': 'application/json' },
  7472. body: JSON.stringify({
  7473. enabled,
  7474. port,
  7475. default_profile: profile,
  7476. require_mppe: mppe
  7477. })
  7478. });
  7479. if (res.ok) {
  7480. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7481. loadPPPServers();
  7482. fetchData(false);
  7483. } else {
  7484. const err = await res.json();
  7485. showToast('Error', err.message, 'error');
  7486. }
  7487. } catch (err) {
  7488. showToast('Error', err.message, 'error');
  7489. }
  7490. }
  7491. async function saveL2TPServerConfig(e) {
  7492. e.preventDefault();
  7493. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7494. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7495. const profile = document.getElementById('l2tp-server-profile').value;
  7496. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7497. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7498. try {
  7499. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7500. method: 'POST',
  7501. headers: { 'Content-Type': 'application/json' },
  7502. body: JSON.stringify({
  7503. enabled,
  7504. port,
  7505. default_profile: profile,
  7506. use_ipsec: useipsec,
  7507. ipsec_secret: psk
  7508. })
  7509. });
  7510. if (res.ok) {
  7511. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7512. loadPPPServers();
  7513. fetchData(false);
  7514. } else {
  7515. const err = await res.json();
  7516. showToast('Error', err.message, 'error');
  7517. }
  7518. } catch (err) {
  7519. showToast('Error', err.message, 'error');
  7520. }
  7521. }
  7522. // IPSec Server Modal
  7523. function openIPSecServerModal() {
  7524. loadPPPServers();
  7525. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7526. }
  7527. function closeIPSecServerModal() {
  7528. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7529. }
  7530. async function submitSaveIPSecServer(e) {
  7531. e.preventDefault();
  7532. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7533. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7534. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7535. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7536. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7537. try {
  7538. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7539. method: 'POST',
  7540. headers: { 'Content-Type': 'application/json' },
  7541. body: JSON.stringify({
  7542. enabled,
  7543. preshared_key: psk,
  7544. pool_address: pool,
  7545. dns_servers: dns,
  7546. local_subnet: subnet
  7547. })
  7548. });
  7549. if (res.ok) {
  7550. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7551. closeIPSecServerModal();
  7552. loadPPPServers();
  7553. fetchData(false);
  7554. } else {
  7555. const err = await res.json();
  7556. showToast('Error', err.message, 'error');
  7557. }
  7558. } catch (err) {
  7559. showToast('Error', err.message, 'error');
  7560. }
  7561. }
  7562. // WireGuard Client Config Viewer
  7563. let currentWGClientConf = '';
  7564. async function openWGClientConfModal(iface, clientIP) {
  7565. try {
  7566. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7567. method: 'POST',
  7568. headers: { 'Content-Type': 'application/json' },
  7569. body: JSON.stringify({
  7570. interface: iface,
  7571. address: clientIP || '10.10.0.2/32',
  7572. dns: '1.1.1.1, 8.8.8.8'
  7573. })
  7574. });
  7575. if (res.ok) {
  7576. const data = await res.json();
  7577. currentWGClientConf = data.config;
  7578. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7579. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7580. } else {
  7581. const err = await res.json();
  7582. showToast('Error', err.message, 'error');
  7583. }
  7584. } catch (err) {
  7585. showToast('Error', err.message, 'error');
  7586. }
  7587. }
  7588. function closeWGClientConfModal() {
  7589. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7590. }
  7591. function copyWGClientConf() {
  7592. if (!currentWGClientConf) return;
  7593. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7594. }
  7595. function downloadWGClientConf() {
  7596. if (!currentWGClientConf) return;
  7597. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7598. const a = document.createElement('a');
  7599. a.href = URL.createObjectURL(blob);
  7600. a.download = 'wireguard-client.conf';
  7601. document.body.appendChild(a);
  7602. a.click();
  7603. document.body.removeChild(a);
  7604. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7605. }
  7606. // =========================================================================
  7607. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7608. // =========================================================================
  7609. state.activeDynSubTab = 'bgp-peers';
  7610. state.activeBgpSubTab = 'bgp-peers';
  7611. state.activeOspfTab = 'instances';
  7612. state.bgpInstance = null;
  7613. state.bgpPeers = [];
  7614. state.bgpNets = [];
  7615. state.bgpRoutes = [];
  7616. state.ospfInstance = null;
  7617. state.ospfInstances = [];
  7618. state.ospfAreas = [];
  7619. state.ospfAreaRanges = [];
  7620. state.ospfTemplates = [];
  7621. state.ospfLiveInterfaces = [];
  7622. state.ospfStaticNbrs = [];
  7623. state.ospfNeighbors = [];
  7624. state.ospfLSA = [];
  7625. state.ospfRoutes = [];
  7626. state.selectedOspfRow = {
  7627. instances: null,
  7628. areas: null,
  7629. 'area-ranges': null,
  7630. templates: null,
  7631. interfaces: null,
  7632. 'static-nbrs': null,
  7633. neighbors: null,
  7634. lsa: null,
  7635. };
  7636. state.ospfSort = {
  7637. instances: { col: 'name', asc: true },
  7638. areas: { col: 'name', asc: true },
  7639. ranges: { col: 'area', asc: true },
  7640. templates: { col: 'interfaces', asc: true },
  7641. live_ifaces: { col: 'interface', asc: true },
  7642. snbrs: { col: 'address', asc: true },
  7643. neighbors: { col: 'address', asc: true },
  7644. lsa: { col: 'instance', asc: true },
  7645. };
  7646. function switchBgpSubTab(subTab) {
  7647. state.activeBgpSubTab = subTab;
  7648. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7649. tabs.forEach(t => {
  7650. const el = document.getElementById(`dyn-subtab-${t}`);
  7651. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7652. if (el) el.classList.toggle('hidden', t !== subTab);
  7653. if (btn) {
  7654. if (t === subTab) {
  7655. 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';
  7656. } else {
  7657. 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';
  7658. }
  7659. }
  7660. });
  7661. }
  7662. function switchOspfTab(tabName) {
  7663. state.activeOspfTab = tabName;
  7664. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7665. tabs.forEach(t => {
  7666. const pane = document.getElementById(`ospf-pane-${t}`);
  7667. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7668. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7669. if (btn) {
  7670. if (t === tabName) {
  7671. 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';
  7672. } else {
  7673. 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';
  7674. }
  7675. }
  7676. });
  7677. }
  7678. function switchOspfSubTab(tab) {
  7679. // Legacy alias
  7680. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7681. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7682. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7683. else switchOspfTab('instances');
  7684. }
  7685. function switchDynSubTab(subTab) {
  7686. if (subTab.startsWith('bgp')) {
  7687. if (state.activeTab !== 'bgp') navigate('bgp');
  7688. switchBgpSubTab(subTab);
  7689. } else if (subTab.startsWith('ospf')) {
  7690. if (state.activeTab !== 'ospf') navigate('ospf');
  7691. switchOspfTab('instances');
  7692. }
  7693. }
  7694. async function loadDynamicRouting(showToastMsg = false) {
  7695. try {
  7696. const fetchSafeJson = async (url) => {
  7697. try {
  7698. const r = await fetch(url);
  7699. return r.ok ? await r.json() : null;
  7700. } catch (e) {
  7701. return null;
  7702. }
  7703. };
  7704. const [
  7705. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7706. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7707. selectRules, commLists, asLists
  7708. ] = await Promise.all([
  7709. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7710. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7711. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7712. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7713. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7714. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7715. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7716. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7717. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7718. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7719. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7720. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7721. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7722. fetchSafeJson(`${API_BASE}/routing/filters`),
  7723. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7724. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7725. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7726. ]);
  7727. if (sum) state.dynSummary = sum;
  7728. if (bgpInst) state.bgpInstance = bgpInst;
  7729. if (bgpPeers) state.bgpPeers = bgpPeers;
  7730. if (bgpNets) state.bgpNets = bgpNets;
  7731. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7732. if (ospfInsts) state.ospfInstances = ospfInsts;
  7733. if (ospfAreas) state.ospfAreas = ospfAreas;
  7734. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7735. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7736. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7737. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7738. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7739. if (ospfLsa) state.ospfLSA = ospfLsa;
  7740. if (filters) state.routingFilters = filters;
  7741. if (selectRules) state.routingSelectRules = selectRules;
  7742. if (commLists) state.routingCommunityLists = commLists;
  7743. if (asLists) state.routingASLists = asLists;
  7744. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7745. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7746. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7747. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7748. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7749. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7750. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7751. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7752. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7753. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7754. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7755. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7756. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7757. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7758. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7759. } catch (err) {
  7760. console.error('Failed to load dynamic routing:', err);
  7761. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7762. }
  7763. }
  7764. async function loadOspfAll() {
  7765. await loadDynamicRouting(true);
  7766. }
  7767. function renderBgpStatusPill() {
  7768. const pill = document.getElementById('bgp-live-status-pill');
  7769. if (!pill) return;
  7770. const inst = state.bgpInstance;
  7771. if (!inst || !inst.enabled) {
  7772. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7773. pill.innerText = 'BGP DISABLED';
  7774. } else if (inst.running) {
  7775. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7776. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7777. } else {
  7778. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  7779. pill.innerText = 'BGP STARTING...';
  7780. }
  7781. }
  7782. function renderBgpPeers() {
  7783. const tbody = document.getElementById('bgp-peers-table-body');
  7784. if (!tbody) return;
  7785. const empty = document.getElementById('bgp-peers-empty');
  7786. const countBadge = document.getElementById('bgp-peers-count-badge');
  7787. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7788. const peers = state.bgpPeers || [];
  7789. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7790. if (navBadge) navBadge.innerText = peers.length;
  7791. if (peers.length === 0) {
  7792. tbody.innerHTML = '';
  7793. if (empty) empty.classList.remove('hidden');
  7794. return;
  7795. }
  7796. if (empty) empty.classList.add('hidden');
  7797. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7798. if (tbody.dataset.sig === sig) return;
  7799. tbody.dataset.sig = sig;
  7800. tbody.innerHTML = peers.map(p => {
  7801. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7802. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7803. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7804. let stateBadge = '';
  7805. if (p.disabled) {
  7806. 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>';
  7807. } else if (p.state === 'Established') {
  7808. 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>';
  7809. } else if (p.state === 'Connect' || p.state === 'Active') {
  7810. 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>`;
  7811. } else {
  7812. 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>`;
  7813. }
  7814. return `
  7815. <tr class="hover:bg-slate-800/40 transition">
  7816. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7817. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7818. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7819. <td class="py-2.5 px-3">
  7820. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7821. ${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>`}
  7822. </td>
  7823. <td class="py-2.5 px-3">${stateBadge}</td>
  7824. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7825. <td class="py-2.5 px-3 text-slate-300">
  7826. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7827. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7828. </td>
  7829. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7830. ${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> ` : ''}
  7831. ${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>` : ''}
  7832. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7833. </td>
  7834. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7835. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7836. <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'}">
  7837. ${p.disabled ? 'Enable' : 'Disable'}
  7838. </button>
  7839. <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">
  7840. Edit
  7841. </button>
  7842. <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">
  7843. Delete
  7844. </button>
  7845. </td>
  7846. </tr>
  7847. `;
  7848. }).join('');
  7849. }
  7850. function renderBgpNetworks() {
  7851. const tbody = document.getElementById('bgp-nets-table-body');
  7852. if (!tbody) return;
  7853. const empty = document.getElementById('bgp-nets-empty');
  7854. const countBadge = document.getElementById('bgp-nets-count-badge');
  7855. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7856. const nets = state.bgpNets || [];
  7857. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7858. if (navBadge) navBadge.innerText = nets.length;
  7859. if (nets.length === 0) {
  7860. tbody.innerHTML = '';
  7861. if (empty) empty.classList.remove('hidden');
  7862. return;
  7863. }
  7864. if (empty) empty.classList.add('hidden');
  7865. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7866. if (tbody.dataset.sig === sig) return;
  7867. tbody.dataset.sig = sig;
  7868. tbody.innerHTML = nets.map(n => `
  7869. <tr class="hover:bg-slate-800/40 transition">
  7870. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7871. <td class="py-2.5 px-3">
  7872. ${n.disabled
  7873. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7874. : '<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>'}
  7875. </td>
  7876. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7877. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7878. <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">
  7879. Delete
  7880. </button>
  7881. </td>
  7882. </tr>
  7883. `).join('');
  7884. }
  7885. function renderBgpRoutes() {
  7886. const tbody = document.getElementById('bgp-routes-table-body');
  7887. if (!tbody) return;
  7888. const empty = document.getElementById('bgp-routes-empty');
  7889. const countBadge = document.getElementById('bgp-routes-count-badge');
  7890. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7891. const routes = state.bgpRoutes || [];
  7892. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7893. if (navBadge) navBadge.innerText = routes.length;
  7894. if (routes.length === 0) {
  7895. tbody.innerHTML = '';
  7896. if (empty) empty.classList.remove('hidden');
  7897. return;
  7898. }
  7899. if (empty) empty.classList.add('hidden');
  7900. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7901. if (tbody.dataset.sig === sig) return;
  7902. tbody.dataset.sig = sig;
  7903. tbody.innerHTML = routes.map(r => `
  7904. <tr class="hover:bg-slate-800/40 transition">
  7905. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7906. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7907. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7908. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7909. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7910. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7911. </tr>
  7912. `).join('');
  7913. }
  7914. // =========================================================================
  7915. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7916. // =========================================================================
  7917. function sortOspfTable(tab, col) {
  7918. if (!state.ospfSort) state.ospfSort = {};
  7919. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7920. if (state.ospfSort[tab].col === col) {
  7921. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7922. } else {
  7923. state.ospfSort[tab].col = col;
  7924. state.ospfSort[tab].asc = true;
  7925. }
  7926. const asc = state.ospfSort[tab].asc;
  7927. let list = [];
  7928. if (tab === 'instances') list = state.ospfInstances || [];
  7929. else if (tab === 'areas') list = state.ospfAreas || [];
  7930. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7931. else if (tab === 'templates') list = state.ospfTemplates || [];
  7932. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7933. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7934. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7935. else if (tab === 'lsa') list = state.ospfLSA || [];
  7936. list.sort((a, b) => {
  7937. let valA = a[col] ?? '';
  7938. let valB = b[col] ?? '';
  7939. if (typeof valA === 'number' && typeof valB === 'number') {
  7940. return asc ? valA - valB : valB - valA;
  7941. }
  7942. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7943. });
  7944. if (tab === 'instances') renderOspfInstances();
  7945. else if (tab === 'areas') renderOspfAreas();
  7946. else if (tab === 'ranges') renderOspfAreaRanges();
  7947. else if (tab === 'templates') renderOspfTemplates();
  7948. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7949. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7950. else if (tab === 'neighbors') renderOspfNeighbors();
  7951. else if (tab === 'lsa') renderOspfLSA();
  7952. }
  7953. function selectOspfRow(tab, id) {
  7954. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7955. state.selectedOspfRow[tab] = id;
  7956. if (tab === 'instances') {
  7957. renderOspfInstances();
  7958. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7959. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7960. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7961. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7962. if (btnEn) btnEn.disabled = false;
  7963. if (btnDis) btnDis.disabled = false;
  7964. if (btnRem) btnRem.disabled = false;
  7965. if (btnCom) btnCom.disabled = false;
  7966. } else if (tab === 'areas') {
  7967. renderOspfAreas();
  7968. const btnEn = document.getElementById('btn-ospf-area-enable');
  7969. const btnDis = document.getElementById('btn-ospf-area-disable');
  7970. const btnRem = document.getElementById('btn-ospf-area-remove');
  7971. const btnCom = document.getElementById('btn-ospf-area-comment');
  7972. if (btnEn) btnEn.disabled = false;
  7973. if (btnDis) btnDis.disabled = false;
  7974. if (btnRem) btnRem.disabled = false;
  7975. if (btnCom) btnCom.disabled = false;
  7976. } else if (tab === 'ranges') {
  7977. renderOspfAreaRanges();
  7978. const btnEn = document.getElementById('btn-ospf-range-enable');
  7979. const btnDis = document.getElementById('btn-ospf-range-disable');
  7980. const btnRem = document.getElementById('btn-ospf-range-remove');
  7981. const btnCom = document.getElementById('btn-ospf-range-comment');
  7982. if (btnEn) btnEn.disabled = false;
  7983. if (btnDis) btnDis.disabled = false;
  7984. if (btnRem) btnRem.disabled = false;
  7985. if (btnCom) btnCom.disabled = false;
  7986. } else if (tab === 'templates') {
  7987. renderOspfTemplates();
  7988. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7989. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7990. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7991. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7992. if (btnEn) btnEn.disabled = false;
  7993. if (btnDis) btnDis.disabled = false;
  7994. if (btnRem) btnRem.disabled = false;
  7995. if (btnCom) btnCom.disabled = false;
  7996. } else if (tab === 'snbrs') {
  7997. renderOspfStaticNbrs();
  7998. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7999. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8000. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8001. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8002. if (btnEn) btnEn.disabled = false;
  8003. if (btnDis) btnDis.disabled = false;
  8004. if (btnRem) btnRem.disabled = false;
  8005. if (btnCom) btnCom.disabled = false;
  8006. }
  8007. }
  8008. // TAB 1: INSTANCES
  8009. function renderOspfInstances() {
  8010. const tbody = document.getElementById('ospf-instances-table-body');
  8011. if (!tbody) return;
  8012. const countEl = document.getElementById('ospf-instances-footer-count');
  8013. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8014. let list = state.ospfInstances || [];
  8015. if (filter) {
  8016. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8017. }
  8018. if (countEl) countEl.innerText = list.length;
  8019. const selId = state.selectedOspfRow?.instances;
  8020. tbody.innerHTML = list.map((inst, idx) => {
  8021. const isSel = inst.id === selId;
  8022. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8023. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8024. return `
  8025. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8026. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8027. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8028. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8029. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8030. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8031. </td>
  8032. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8033. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8034. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8035. </tr>
  8036. `;
  8037. }).join('');
  8038. }
  8039. // TAB 2: AREAS
  8040. function renderOspfAreas() {
  8041. const tbody = document.getElementById('ospf-areas-table-body');
  8042. if (!tbody) return;
  8043. const countEl = document.getElementById('ospf-areas-footer-count');
  8044. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8045. let list = state.ospfAreas || [];
  8046. if (filter) {
  8047. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8048. }
  8049. if (countEl) countEl.innerText = list.length;
  8050. const selId = state.selectedOspfRow?.areas;
  8051. tbody.innerHTML = list.map((a, idx) => {
  8052. const isSel = a.id === selId;
  8053. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8054. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8055. return `
  8056. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8057. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8058. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8059. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8060. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8061. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8062. </td>
  8063. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8064. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8065. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8066. </tr>
  8067. `;
  8068. }).join('');
  8069. }
  8070. // TAB 3: AREA RANGES
  8071. function renderOspfAreaRanges() {
  8072. const tbody = document.getElementById('ospf-ranges-table-body');
  8073. if (!tbody) return;
  8074. const countEl = document.getElementById('ospf-ranges-footer-count');
  8075. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8076. let list = state.ospfAreaRanges || [];
  8077. if (filter) {
  8078. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8079. }
  8080. if (countEl) countEl.innerText = list.length;
  8081. const selId = state.selectedOspfRow?.['area-ranges'];
  8082. tbody.innerHTML = list.map((r, idx) => {
  8083. const isSel = r.id === selId;
  8084. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8085. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8086. return `
  8087. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8088. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8089. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8090. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8091. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8092. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8093. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8094. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8095. </tr>
  8096. `;
  8097. }).join('');
  8098. }
  8099. // TAB 4: INTERFACE TEMPLATES
  8100. function renderOspfTemplates() {
  8101. const tbody = document.getElementById('ospf-templates-table-body');
  8102. if (!tbody) return;
  8103. const countEl = document.getElementById('ospf-templates-footer-count');
  8104. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8105. let list = state.ospfTemplates || [];
  8106. if (filter) {
  8107. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8108. }
  8109. if (countEl) countEl.innerText = list.length;
  8110. const selId = state.selectedOspfRow?.templates;
  8111. tbody.innerHTML = list.map((t, idx) => {
  8112. const isSel = t.id === selId;
  8113. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8114. const ifaces = t.interfaces || t.interface || 'all';
  8115. const nets = t.networks || t.network || '';
  8116. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8117. return `
  8118. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8119. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8120. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8121. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8122. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8123. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8124. </td>
  8125. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8126. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8127. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8128. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8129. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8130. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8131. </tr>
  8132. `;
  8133. }).join('');
  8134. }
  8135. // TAB 5: LIVE INTERFACES
  8136. function renderOspfLiveInterfaces() {
  8137. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8138. if (!tbody) return;
  8139. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8140. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8141. let list = state.ospfLiveInterfaces || [];
  8142. if (filter) {
  8143. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8144. }
  8145. if (countEl) countEl.innerText = list.length;
  8146. tbody.innerHTML = list.map(i => `
  8147. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8148. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8149. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8150. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8151. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8152. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8153. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8154. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8155. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8156. </tr>
  8157. `).join('');
  8158. }
  8159. // TAB 6: STATIC NEIGHBORS
  8160. function renderOspfStaticNbrs() {
  8161. const tbody = document.getElementById('ospf-snbrs-table-body');
  8162. if (!tbody) return;
  8163. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8164. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8165. let list = state.ospfStaticNbrs || [];
  8166. if (filter) {
  8167. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8168. }
  8169. if (countEl) countEl.innerText = list.length;
  8170. const selId = state.selectedOspfRow?.['static-nbrs'];
  8171. tbody.innerHTML = list.map((n, idx) => {
  8172. const isSel = n.id === selId;
  8173. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8174. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8175. return `
  8176. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8177. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8178. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8179. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8180. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8181. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8182. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8183. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8184. </tr>
  8185. `;
  8186. }).join('');
  8187. }
  8188. // TAB 7: LIVE NEIGHBORS
  8189. function renderOspfNeighbors() {
  8190. const tbody = document.getElementById('ospf-neighbors-table-body');
  8191. if (!tbody) return;
  8192. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8193. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8194. let list = state.ospfNeighbors || [];
  8195. if (filter) {
  8196. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8197. }
  8198. if (countEl) countEl.innerText = list.length;
  8199. tbody.innerHTML = list.map(n => `
  8200. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8201. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8202. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8203. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8204. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8205. </td>
  8206. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8207. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8208. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8209. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8210. </tr>
  8211. `).join('');
  8212. }
  8213. // TAB 8: LINK-STATE DATABASE (LSA)
  8214. function renderOspfLSA() {
  8215. const tbody = document.getElementById('ospf-lsa-table-body');
  8216. if (!tbody) return;
  8217. const countEl = document.getElementById('ospf-lsa-footer-count');
  8218. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8219. let list = state.ospfLSA || [];
  8220. if (filter) {
  8221. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8222. }
  8223. if (countEl) countEl.innerText = list.length;
  8224. tbody.innerHTML = list.map(l => `
  8225. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8226. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8227. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8228. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8229. </td>
  8230. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8231. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8232. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8233. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8234. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8235. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8236. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8237. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8238. </tr>
  8239. `).join('');
  8240. }
  8241. function renderOspfStatusPill() {
  8242. // Maintained for backward compatibility
  8243. const pill = document.getElementById('ospf-live-status-pill');
  8244. if (!pill) return;
  8245. 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';
  8246. pill.innerText = 'OSPF ACTIVE';
  8247. }
  8248. function renderOspfInterfaces() {
  8249. renderOspfTemplates();
  8250. }
  8251. function renderOspfRoutes() {
  8252. // Routes retained in background
  8253. }
  8254. // BGP Modals & Actions
  8255. function openBgpInstanceModal() {
  8256. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8257. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8258. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8259. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8260. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8261. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8262. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8263. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8264. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8265. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8266. }
  8267. function closeBgpInstanceModal() {
  8268. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8269. }
  8270. async function submitBgpInstance(e) {
  8271. e.preventDefault();
  8272. const payload = {
  8273. enabled: document.getElementById('modal-bgp-enabled').checked,
  8274. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8275. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8276. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8277. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8278. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8279. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8280. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8281. };
  8282. try {
  8283. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8284. method: 'POST',
  8285. headers: { 'Content-Type': 'application/json' },
  8286. body: JSON.stringify(payload)
  8287. });
  8288. if (res.ok) {
  8289. closeBgpInstanceModal();
  8290. showToast('Success', 'BGP instance configuration updated', 'success');
  8291. loadDynamicRouting();
  8292. } else {
  8293. const err = await res.json();
  8294. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8295. }
  8296. } catch (err) {
  8297. showToast('Error', err.message, 'error');
  8298. }
  8299. }
  8300. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8301. function switchBgpPeerModalTab(tab) {
  8302. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8303. tabs.forEach(t => {
  8304. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8305. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8306. if (t === tab) {
  8307. if (pane) pane.classList.remove('hidden');
  8308. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8309. } else {
  8310. if (pane) pane.classList.add('hidden');
  8311. 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';
  8312. }
  8313. });
  8314. }
  8315. function addOutputNetworkRow(val = '') {
  8316. const container = document.getElementById('modal-bgp-output-networks-container');
  8317. if (!container) return;
  8318. const row = document.createElement('div');
  8319. row.className = 'flex items-center gap-2 output-net-row';
  8320. row.innerHTML = `
  8321. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  8322. <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>
  8323. `;
  8324. container.appendChild(row);
  8325. }
  8326. function parseBgpTime(val) {
  8327. if (!val) return 0;
  8328. val = String(val).trim();
  8329. if (val.includes(':')) {
  8330. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8331. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8332. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8333. }
  8334. return parseInt(val, 10) || 0;
  8335. }
  8336. function formatBgpTime(secs) {
  8337. if (!secs || secs <= 0) return '00:00:00';
  8338. const h = Math.floor(secs / 3600);
  8339. const m = Math.floor((secs % 3600) / 60);
  8340. const s = secs % 60;
  8341. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8342. }
  8343. function populateBgpRoutingTables() {
  8344. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8345. if (!sel) return;
  8346. const cur = sel.value || 'main';
  8347. sel.innerHTML = '<option value="main">main</option>';
  8348. (state.routingTables || []).forEach(t => {
  8349. if (t.name !== 'main') {
  8350. const opt = document.createElement('option');
  8351. opt.value = t.name;
  8352. opt.innerText = t.name;
  8353. sel.appendChild(opt);
  8354. }
  8355. });
  8356. sel.value = cur;
  8357. }
  8358. function openAddBgpPeerModal() {
  8359. document.getElementById('bgp-peer-form').reset();
  8360. document.getElementById('modal-bgp-peer-id').value = '';
  8361. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8362. // General Tab
  8363. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8364. document.getElementById('modal-bgp-peer-comment').value = '';
  8365. document.getElementById('modal-bgp-peer-name').value = '';
  8366. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8367. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8368. document.getElementById('modal-bgp-peer-local-as').value = '';
  8369. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8370. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8371. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8372. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8373. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8374. document.getElementById('modal-bgp-peer-router-id').value = '';
  8375. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8376. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8377. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8378. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8379. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8380. document.getElementById('modal-bgp-peer-local-port').value = '';
  8381. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8382. document.getElementById('modal-bgp-peer-password').value = '';
  8383. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8384. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8385. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8386. document.getElementById('modal-bgp-peer-connect').checked = true;
  8387. document.getElementById('modal-bgp-peer-listen').checked = true;
  8388. // Extra Tab
  8389. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8390. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8391. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8392. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8393. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8394. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8395. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8396. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8397. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8398. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8399. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8400. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8401. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8402. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8403. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8404. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8405. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8406. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8407. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8408. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8409. // Attributes Tab
  8410. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8411. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8412. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8413. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8414. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8415. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8416. // Filter Tab
  8417. populateFilterChainsDatalist();
  8418. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8419. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8420. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8421. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8422. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8423. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8424. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8425. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8426. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8427. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8428. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8429. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8430. populateBgpRoutingTables();
  8431. const container = document.getElementById('modal-bgp-output-networks-container');
  8432. if (container) {
  8433. container.innerHTML = '';
  8434. addOutputNetworkRow('');
  8435. }
  8436. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8437. if (removeBtn) removeBtn.classList.add('hidden');
  8438. switchBgpPeerModalTab('general');
  8439. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8440. }
  8441. function populateFilterChainsDatalist() {
  8442. const dl = document.getElementById('filter-chains-list');
  8443. if (!dl) return;
  8444. const chains = new Set();
  8445. (state.routingFilters || []).forEach(f => {
  8446. if (f.chain) chains.add(f.chain);
  8447. });
  8448. if (chains.size === 0) {
  8449. chains.add('awmn');
  8450. chains.add('bgp-in');
  8451. chains.add('bgp-out');
  8452. }
  8453. dl.innerHTML = '';
  8454. chains.forEach(c => {
  8455. const opt = document.createElement('option');
  8456. opt.value = c;
  8457. dl.appendChild(opt);
  8458. });
  8459. }
  8460. function openEditBgpPeerModal(id) {
  8461. const p = (state.bgpPeers || []).find(item => item.id === id);
  8462. if (!p) return;
  8463. populateBgpRoutingTables();
  8464. populateFilterChainsDatalist();
  8465. document.getElementById('modal-bgp-peer-id').value = p.id;
  8466. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8467. // General Tab
  8468. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8469. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8470. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8471. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8472. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8473. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8474. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8475. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8476. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8477. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8478. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8479. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8480. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8481. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8482. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8483. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8484. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8485. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8486. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8487. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8488. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8489. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8490. // Extra Tab
  8491. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8492. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8493. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8494. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8495. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8496. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8497. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8498. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8499. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8500. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8501. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8502. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8503. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8504. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8505. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8506. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8507. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8508. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8509. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8510. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8511. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8512. // Attributes Tab
  8513. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8514. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8515. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8516. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8517. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8518. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8519. // Filter Tab
  8520. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8521. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8522. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8523. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8524. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8525. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8526. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8527. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8528. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8529. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8530. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8531. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8532. // Output Networks
  8533. const container = document.getElementById('modal-bgp-output-networks-container');
  8534. if (container) {
  8535. container.innerHTML = '';
  8536. if (p.output_networks && p.output_networks.length > 0) {
  8537. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8538. } else {
  8539. addOutputNetworkRow('');
  8540. }
  8541. }
  8542. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8543. if (removeBtn) removeBtn.classList.remove('hidden');
  8544. switchBgpPeerModalTab('general');
  8545. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8546. }
  8547. function copyCurrentBgpPeer() {
  8548. document.getElementById('modal-bgp-peer-id').value = '';
  8549. const nameEl = document.getElementById('modal-bgp-peer-name');
  8550. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8551. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8552. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8553. if (removeBtn) removeBtn.classList.add('hidden');
  8554. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8555. }
  8556. function removeCurrentBgpPeer() {
  8557. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8558. if (!id) return;
  8559. deleteBgpPeer(id);
  8560. closeBgpPeerModal();
  8561. }
  8562. function closeBgpPeerModal() {
  8563. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8564. }
  8565. function getBgpPeerFormData() {
  8566. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8567. const outputNetworks = [];
  8568. netInputs.forEach(inp => {
  8569. const v = inp.value.trim();
  8570. if (v) outputNetworks.push(v);
  8571. });
  8572. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8573. return {
  8574. id: document.getElementById('modal-bgp-peer-id').value,
  8575. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8576. enabled: enabled,
  8577. disabled: !enabled,
  8578. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8579. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8580. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8581. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8582. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8583. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8584. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8585. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8586. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8587. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8588. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8589. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8590. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8591. password: document.getElementById('modal-bgp-peer-password').value,
  8592. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8593. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8594. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8595. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8596. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8597. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8598. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8599. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8600. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8601. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8602. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8603. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8604. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8605. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8606. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8607. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8608. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8609. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8610. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8611. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8612. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8613. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8614. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8615. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8616. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8617. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8618. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8619. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8620. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8621. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8622. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8623. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8624. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8625. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8626. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8627. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8628. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8629. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8630. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8631. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8632. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8633. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8634. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8635. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8636. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8637. output_networks: outputNetworks
  8638. };
  8639. }
  8640. async function submitBgpPeer(e) {
  8641. if (e) e.preventDefault();
  8642. const payload = getBgpPeerFormData();
  8643. try {
  8644. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8645. method: 'POST',
  8646. headers: { 'Content-Type': 'application/json' },
  8647. body: JSON.stringify(payload)
  8648. });
  8649. if (res.ok) {
  8650. closeBgpPeerModal();
  8651. showToast('Success', 'BGP Connection saved', 'success');
  8652. loadDynamicRouting();
  8653. } else {
  8654. const err = await res.json();
  8655. showToast('Error', err.error || 'Failed to save peer', 'error');
  8656. }
  8657. } catch (err) {
  8658. showToast('Error', err.message, 'error');
  8659. }
  8660. }
  8661. async function applyBgpPeerModal(e) {
  8662. if (e) e.preventDefault();
  8663. const payload = getBgpPeerFormData();
  8664. try {
  8665. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8666. method: 'POST',
  8667. headers: { 'Content-Type': 'application/json' },
  8668. body: JSON.stringify(payload)
  8669. });
  8670. if (res.ok) {
  8671. const data = await res.json();
  8672. if (data.peer && data.peer.id) {
  8673. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8674. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8675. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8676. }
  8677. showToast('Applied', 'BGP Connection applied', 'success');
  8678. loadDynamicRouting();
  8679. } else {
  8680. const err = await res.json();
  8681. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8682. }
  8683. } catch (err) {
  8684. showToast('Error', err.message, 'error');
  8685. }
  8686. }
  8687. async function deleteBgpPeer(id) {
  8688. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8689. try {
  8690. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8691. if (res.ok) {
  8692. showToast('Deleted', 'BGP peer removed', 'success');
  8693. loadDynamicRouting();
  8694. }
  8695. } catch (err) {
  8696. showToast('Error', err.message, 'error');
  8697. }
  8698. }
  8699. async function toggleBgpPeerState(id, disabled) {
  8700. try {
  8701. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8702. method: 'POST',
  8703. headers: { 'Content-Type': 'application/json' },
  8704. body: JSON.stringify({ disabled })
  8705. });
  8706. if (res.ok) {
  8707. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8708. loadDynamicRouting();
  8709. }
  8710. } catch (err) {
  8711. showToast('Error', err.message, 'error');
  8712. }
  8713. }
  8714. function openAddBgpNetworkModal() {
  8715. document.getElementById('bgp-network-form').reset();
  8716. document.getElementById('modal-bgp-net-id').value = '';
  8717. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8718. }
  8719. function closeBgpNetworkModal() {
  8720. document.getElementById('bgp-network-modal').classList.add('hidden');
  8721. }
  8722. async function submitBgpNetwork(e) {
  8723. e.preventDefault();
  8724. const payload = {
  8725. id: document.getElementById('modal-bgp-net-id').value,
  8726. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8727. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8728. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8729. };
  8730. try {
  8731. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8732. method: 'POST',
  8733. headers: { 'Content-Type': 'application/json' },
  8734. body: JSON.stringify(payload)
  8735. });
  8736. if (res.ok) {
  8737. closeBgpNetworkModal();
  8738. showToast('Success', 'BGP network advertisement saved', 'success');
  8739. loadDynamicRouting();
  8740. } else {
  8741. const err = await res.json();
  8742. showToast('Error', err.error || 'Failed to save network', 'error');
  8743. }
  8744. } catch (err) {
  8745. showToast('Error', err.message, 'error');
  8746. }
  8747. }
  8748. async function deleteBgpNetwork(id) {
  8749. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8750. try {
  8751. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8752. if (res.ok) {
  8753. showToast('Deleted', 'Network advertisement removed', 'success');
  8754. loadDynamicRouting();
  8755. }
  8756. } catch (err) {
  8757. showToast('Error', err.message, 'error');
  8758. }
  8759. }
  8760. // =========================================================================
  8761. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8762. // =========================================================================
  8763. // --- 1. OSPF INSTANCE ---
  8764. function openOspfInstanceModal(id = null) {
  8765. const isEdit = !!id;
  8766. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8767. id: '',
  8768. name: 'Default',
  8769. version: 2,
  8770. vrf: 'main',
  8771. router_id: '192.168.131.56',
  8772. routing_table: 'main',
  8773. enabled: true,
  8774. redistribute_connected: false,
  8775. redistribute_static: true,
  8776. redistribute_bgp: false,
  8777. comment: ''
  8778. };
  8779. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8780. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8781. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8782. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8783. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8784. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8785. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8786. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8787. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8788. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8789. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8790. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8791. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8792. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8793. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8794. }
  8795. function openEditOspfInstanceModal(id) {
  8796. openOspfInstanceModal(id);
  8797. }
  8798. function closeOspfInstanceModal() {
  8799. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8800. }
  8801. async function submitOspfInstance(e) {
  8802. if (e) e.preventDefault();
  8803. const payload = {
  8804. id: document.getElementById('modal-ospf-inst-id').value,
  8805. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8806. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8807. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8808. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8809. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8810. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8811. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8812. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8813. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8814. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8815. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8816. };
  8817. try {
  8818. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8819. method: 'POST',
  8820. headers: { 'Content-Type': 'application/json' },
  8821. body: JSON.stringify(payload)
  8822. });
  8823. if (res.ok) {
  8824. closeOspfInstanceModal();
  8825. showToast('Saved', 'OSPF instance updated', 'success');
  8826. loadDynamicRouting();
  8827. } else {
  8828. const err = await res.json();
  8829. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8830. }
  8831. } catch (err) {
  8832. showToast('Error', err.message, 'error');
  8833. }
  8834. }
  8835. function applyOspfInstanceForm() {
  8836. submitOspfInstance(null);
  8837. }
  8838. function copyOspfInstance() {
  8839. document.getElementById('modal-ospf-inst-id').value = '';
  8840. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8841. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8842. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8843. }
  8844. async function deleteCurrentOspfInstance() {
  8845. const id = document.getElementById('modal-ospf-inst-id').value;
  8846. if (!id) return;
  8847. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8848. try {
  8849. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8850. if (res.ok) {
  8851. closeOspfInstanceModal();
  8852. showToast('Removed', 'OSPF instance deleted', 'success');
  8853. loadDynamicRouting();
  8854. }
  8855. } catch (err) {
  8856. showToast('Error', err.message, 'error');
  8857. }
  8858. }
  8859. async function enableSelectedOspfInstance() {
  8860. const id = state.selectedOspfRow?.instances;
  8861. if (!id) return;
  8862. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8863. method: 'POST',
  8864. headers: { 'Content-Type': 'application/json' },
  8865. body: JSON.stringify({ disabled: false })
  8866. });
  8867. loadDynamicRouting();
  8868. }
  8869. async function disableSelectedOspfInstance() {
  8870. const id = state.selectedOspfRow?.instances;
  8871. if (!id) return;
  8872. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8873. method: 'POST',
  8874. headers: { 'Content-Type': 'application/json' },
  8875. body: JSON.stringify({ disabled: true })
  8876. });
  8877. loadDynamicRouting();
  8878. }
  8879. async function removeSelectedOspfInstance() {
  8880. const id = state.selectedOspfRow?.instances;
  8881. if (!id) return;
  8882. if (!confirm('Delete selected OSPF instance?')) return;
  8883. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8884. loadDynamicRouting();
  8885. }
  8886. async function promptCommentOspfInstance() {
  8887. const id = state.selectedOspfRow?.instances;
  8888. if (!id) return;
  8889. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8890. if (!inst) return;
  8891. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8892. if (comment === null) return;
  8893. inst.comment = comment;
  8894. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8895. method: 'POST',
  8896. headers: { 'Content-Type': 'application/json' },
  8897. body: JSON.stringify(inst)
  8898. });
  8899. loadDynamicRouting();
  8900. }
  8901. // --- 2. OSPF AREA ---
  8902. function populateOspfAreaDropdowns() {
  8903. const instSelect = document.getElementById('modal-ospf-area-instance');
  8904. if (instSelect) {
  8905. const cur = instSelect.value;
  8906. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8907. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8908. if (cur) instSelect.value = cur;
  8909. }
  8910. }
  8911. function openOspfAreaModal(id = null) {
  8912. const isEdit = !!id;
  8913. populateOspfAreaDropdowns();
  8914. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8915. id: '',
  8916. name: 'Default',
  8917. instance: 'Default',
  8918. area_id: '0.0.0.0',
  8919. area_type: 'default',
  8920. default_cost: 1,
  8921. no_summaries: false,
  8922. disabled: false,
  8923. comment: ''
  8924. };
  8925. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8926. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8927. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8928. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8929. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8930. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8931. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8932. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8933. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8934. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8935. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8936. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8937. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8938. }
  8939. function openEditOspfAreaModal(id) {
  8940. openOspfAreaModal(id);
  8941. }
  8942. function closeOspfAreaModal() {
  8943. document.getElementById('ospf-area-modal').classList.add('hidden');
  8944. }
  8945. async function submitOspfArea(e) {
  8946. if (e) e.preventDefault();
  8947. const payload = {
  8948. id: document.getElementById('modal-ospf-area-id').value,
  8949. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8950. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8951. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8952. area_type: document.getElementById('modal-ospf-area-type').value,
  8953. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8954. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8955. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8956. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8957. };
  8958. try {
  8959. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8960. method: 'POST',
  8961. headers: { 'Content-Type': 'application/json' },
  8962. body: JSON.stringify(payload)
  8963. });
  8964. if (res.ok) {
  8965. closeOspfAreaModal();
  8966. showToast('Saved', 'OSPF area saved', 'success');
  8967. loadDynamicRouting();
  8968. } else {
  8969. const err = await res.json();
  8970. showToast('Error', err.error || 'Failed to save area', 'error');
  8971. }
  8972. } catch (err) {
  8973. showToast('Error', err.message, 'error');
  8974. }
  8975. }
  8976. function applyOspfAreaForm() {
  8977. submitOspfArea(null);
  8978. }
  8979. function copyOspfArea() {
  8980. document.getElementById('modal-ospf-area-id').value = '';
  8981. document.getElementById('modal-ospf-area-name').value += '-copy';
  8982. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8983. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8984. }
  8985. async function deleteCurrentOspfArea() {
  8986. const id = document.getElementById('modal-ospf-area-id').value;
  8987. if (!id) return;
  8988. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8989. try {
  8990. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8991. if (res.ok) {
  8992. closeOspfAreaModal();
  8993. showToast('Removed', 'OSPF area deleted', 'success');
  8994. loadDynamicRouting();
  8995. }
  8996. } catch (err) {
  8997. showToast('Error', err.message, 'error');
  8998. }
  8999. }
  9000. async function enableSelectedOspfArea() {
  9001. const id = state.selectedOspfRow?.areas;
  9002. if (!id) return;
  9003. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9004. method: 'POST',
  9005. headers: { 'Content-Type': 'application/json' },
  9006. body: JSON.stringify({ disabled: false })
  9007. });
  9008. loadDynamicRouting();
  9009. }
  9010. async function disableSelectedOspfArea() {
  9011. const id = state.selectedOspfRow?.areas;
  9012. if (!id) return;
  9013. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9014. method: 'POST',
  9015. headers: { 'Content-Type': 'application/json' },
  9016. body: JSON.stringify({ disabled: true })
  9017. });
  9018. loadDynamicRouting();
  9019. }
  9020. async function removeSelectedOspfArea() {
  9021. const id = state.selectedOspfRow?.areas;
  9022. if (!id) return;
  9023. if (!confirm('Delete selected OSPF area?')) return;
  9024. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9025. loadDynamicRouting();
  9026. }
  9027. async function promptCommentOspfArea() {
  9028. const id = state.selectedOspfRow?.areas;
  9029. if (!id) return;
  9030. const area = (state.ospfAreas || []).find(a => a.id === id);
  9031. if (!area) return;
  9032. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9033. if (comment === null) return;
  9034. area.comment = comment;
  9035. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9036. method: 'POST',
  9037. headers: { 'Content-Type': 'application/json' },
  9038. body: JSON.stringify(area)
  9039. });
  9040. loadDynamicRouting();
  9041. }
  9042. // --- 3. OSPF AREA RANGE ---
  9043. function populateAreaRangeDropdowns() {
  9044. const select = document.getElementById('modal-ospf-range-area');
  9045. if (select) {
  9046. const cur = select.value;
  9047. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9048. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9049. if (cur) select.value = cur;
  9050. }
  9051. }
  9052. function openOspfAreaRangeModal(id = null) {
  9053. const isEdit = !!id;
  9054. populateAreaRangeDropdowns();
  9055. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9056. id: '',
  9057. area: 'Default',
  9058. prefix: '',
  9059. cost: 1,
  9060. advertise: true,
  9061. disabled: false,
  9062. comment: ''
  9063. };
  9064. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9065. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9066. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9067. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9068. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9069. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9070. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9071. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9072. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9073. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9074. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9075. }
  9076. function openEditOspfAreaRangeModal(id) {
  9077. openOspfAreaRangeModal(id);
  9078. }
  9079. function closeOspfAreaRangeModal() {
  9080. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9081. }
  9082. async function submitOspfAreaRange(e) {
  9083. if (e) e.preventDefault();
  9084. const payload = {
  9085. id: document.getElementById('modal-ospf-range-id').value,
  9086. area: document.getElementById('modal-ospf-range-area').value,
  9087. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9088. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9089. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9090. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9091. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9092. };
  9093. try {
  9094. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9095. method: 'POST',
  9096. headers: { 'Content-Type': 'application/json' },
  9097. body: JSON.stringify(payload)
  9098. });
  9099. if (res.ok) {
  9100. closeOspfAreaRangeModal();
  9101. showToast('Saved', 'Area range saved', 'success');
  9102. loadDynamicRouting();
  9103. } else {
  9104. const err = await res.json();
  9105. showToast('Error', err.error || 'Failed to save area range', 'error');
  9106. }
  9107. } catch (err) {
  9108. showToast('Error', err.message, 'error');
  9109. }
  9110. }
  9111. function applyOspfAreaRangeForm() {
  9112. submitOspfAreaRange(null);
  9113. }
  9114. async function deleteCurrentOspfAreaRange() {
  9115. const id = document.getElementById('modal-ospf-range-id').value;
  9116. if (!id) return;
  9117. if (!confirm('Delete this area range?')) return;
  9118. try {
  9119. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9120. closeOspfAreaRangeModal();
  9121. showToast('Removed', 'Area range removed', 'success');
  9122. loadDynamicRouting();
  9123. } catch (err) {
  9124. showToast('Error', err.message, 'error');
  9125. }
  9126. }
  9127. async function enableSelectedOspfAreaRange() {
  9128. const id = state.selectedOspfRow?.['area-ranges'];
  9129. if (!id) return;
  9130. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9131. if (!r) return;
  9132. r.disabled = false;
  9133. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9134. loadDynamicRouting();
  9135. }
  9136. async function disableSelectedOspfAreaRange() {
  9137. const id = state.selectedOspfRow?.['area-ranges'];
  9138. if (!id) return;
  9139. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9140. if (!r) return;
  9141. r.disabled = true;
  9142. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9143. loadDynamicRouting();
  9144. }
  9145. async function removeSelectedOspfAreaRange() {
  9146. const id = state.selectedOspfRow?.['area-ranges'];
  9147. if (!id) return;
  9148. if (!confirm('Delete selected area range?')) return;
  9149. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9150. loadDynamicRouting();
  9151. }
  9152. async function promptCommentOspfAreaRange() {
  9153. const id = state.selectedOspfRow?.['area-ranges'];
  9154. if (!id) return;
  9155. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9156. if (!r) return;
  9157. const comment = prompt('Enter comment for area range:', r.comment || '');
  9158. if (comment === null) return;
  9159. r.comment = comment;
  9160. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9161. loadDynamicRouting();
  9162. }
  9163. // --- 4. OSPF INTERFACE TEMPLATE ---
  9164. function switchOspfTemplateTab(tab) {
  9165. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9166. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9167. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9168. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9169. if (tab === 'general') {
  9170. if (tabGen) tabGen.classList.remove('hidden');
  9171. if (tabAuth) tabAuth.classList.add('hidden');
  9172. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9173. 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';
  9174. } else {
  9175. if (tabGen) tabGen.classList.add('hidden');
  9176. if (tabAuth) tabAuth.classList.remove('hidden');
  9177. 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';
  9178. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9179. }
  9180. }
  9181. function populateTemplateAreaDropdowns() {
  9182. const select = document.getElementById('modal-ospf-tmpl-area');
  9183. if (select) {
  9184. const cur = select.value;
  9185. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9186. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9187. if (cur) select.value = cur;
  9188. }
  9189. }
  9190. function openOspfTemplateModal(id = null) {
  9191. const isEdit = !!id;
  9192. populateTemplateAreaDropdowns();
  9193. switchOspfTemplateTab('general');
  9194. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9195. id: '',
  9196. interfaces: '',
  9197. area: 'Default',
  9198. networks: '',
  9199. network_type: 'broadcast',
  9200. cost: 1,
  9201. priority: 128,
  9202. passive: false,
  9203. hello_interval: 10,
  9204. dead_interval: 40,
  9205. auth: 'none',
  9206. auth_key: '',
  9207. disabled: false,
  9208. comment: ''
  9209. };
  9210. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9211. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9212. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9213. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9214. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9215. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9216. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9217. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9218. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9219. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9220. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9221. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9222. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9223. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9224. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9225. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9226. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9227. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9228. }
  9229. function openEditOspfTemplateModal(id) {
  9230. openOspfTemplateModal(id);
  9231. }
  9232. function closeOspfTemplateModal() {
  9233. document.getElementById('ospf-template-modal').classList.add('hidden');
  9234. }
  9235. async function submitOspfTemplate(e) {
  9236. if (e) e.preventDefault();
  9237. const payload = {
  9238. id: document.getElementById('modal-ospf-tmpl-id').value,
  9239. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9240. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9241. area: document.getElementById('modal-ospf-tmpl-area').value,
  9242. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9243. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9244. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9245. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9246. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9247. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9248. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9249. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9250. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9251. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9252. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9253. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9254. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9255. };
  9256. try {
  9257. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9258. method: 'POST',
  9259. headers: { 'Content-Type': 'application/json' },
  9260. body: JSON.stringify(payload)
  9261. });
  9262. if (res.ok) {
  9263. closeOspfTemplateModal();
  9264. showToast('Saved', 'Interface template saved', 'success');
  9265. loadDynamicRouting();
  9266. } else {
  9267. const err = await res.json();
  9268. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9269. }
  9270. } catch (err) {
  9271. showToast('Error', err.message, 'error');
  9272. }
  9273. }
  9274. function applyOspfTemplateForm() {
  9275. submitOspfTemplate(null);
  9276. }
  9277. function copyOspfTemplate() {
  9278. document.getElementById('modal-ospf-tmpl-id').value = '';
  9279. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9280. showToast('Copied', 'Duplicated as new template', 'info');
  9281. }
  9282. async function deleteCurrentOspfTemplate() {
  9283. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9284. if (!id) return;
  9285. if (!confirm('Delete this interface template?')) return;
  9286. try {
  9287. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9288. closeOspfTemplateModal();
  9289. showToast('Removed', 'Interface template deleted', 'success');
  9290. loadDynamicRouting();
  9291. } catch (err) {
  9292. showToast('Error', err.message, 'error');
  9293. }
  9294. }
  9295. async function enableSelectedOspfTemplate() {
  9296. const id = state.selectedOspfRow?.templates;
  9297. if (!id) return;
  9298. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9299. method: 'POST',
  9300. headers: { 'Content-Type': 'application/json' },
  9301. body: JSON.stringify({ disabled: false })
  9302. });
  9303. loadDynamicRouting();
  9304. }
  9305. async function disableSelectedOspfTemplate() {
  9306. const id = state.selectedOspfRow?.templates;
  9307. if (!id) return;
  9308. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9309. method: 'POST',
  9310. headers: { 'Content-Type': 'application/json' },
  9311. body: JSON.stringify({ disabled: true })
  9312. });
  9313. loadDynamicRouting();
  9314. }
  9315. async function removeSelectedOspfTemplate() {
  9316. const id = state.selectedOspfRow?.templates;
  9317. if (!id) return;
  9318. if (!confirm('Delete selected interface template?')) return;
  9319. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9320. loadDynamicRouting();
  9321. }
  9322. async function promptCommentOspfTemplate() {
  9323. const id = state.selectedOspfRow?.templates;
  9324. if (!id) return;
  9325. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9326. if (!tmpl) return;
  9327. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9328. if (comment === null) return;
  9329. tmpl.comment = comment;
  9330. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9331. method: 'POST',
  9332. headers: { 'Content-Type': 'application/json' },
  9333. body: JSON.stringify(tmpl)
  9334. });
  9335. loadDynamicRouting();
  9336. }
  9337. // --- 5. OSPF STATIC NEIGHBOR ---
  9338. function populateStaticNbrAreaDropdowns() {
  9339. const select = document.getElementById('modal-ospf-snbr-area');
  9340. if (select) {
  9341. const cur = select.value;
  9342. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9343. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9344. if (cur) select.value = cur;
  9345. }
  9346. }
  9347. function openOspfStaticNbrModal(id = null) {
  9348. const isEdit = !!id;
  9349. populateStaticNbrAreaDropdowns();
  9350. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9351. id: '',
  9352. address: '',
  9353. area: 'Default',
  9354. poll_interval: 120,
  9355. cost: 1,
  9356. disabled: false,
  9357. comment: ''
  9358. };
  9359. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9360. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9361. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9362. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9363. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9364. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9365. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9366. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9367. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9368. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9369. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9370. }
  9371. function openEditOspfStaticNbrModal(id) {
  9372. openOspfStaticNbrModal(id);
  9373. }
  9374. function closeOspfStaticNbrModal() {
  9375. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9376. }
  9377. async function submitOspfStaticNbr(e) {
  9378. if (e) e.preventDefault();
  9379. const payload = {
  9380. id: document.getElementById('modal-ospf-snbr-id').value,
  9381. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9382. area: document.getElementById('modal-ospf-snbr-area').value,
  9383. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9384. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9385. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9386. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9387. };
  9388. try {
  9389. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9390. method: 'POST',
  9391. headers: { 'Content-Type': 'application/json' },
  9392. body: JSON.stringify(payload)
  9393. });
  9394. if (res.ok) {
  9395. closeOspfStaticNbrModal();
  9396. showToast('Saved', 'Static neighbor saved', 'success');
  9397. loadDynamicRouting();
  9398. } else {
  9399. const err = await res.json();
  9400. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9401. }
  9402. } catch (err) {
  9403. showToast('Error', err.message, 'error');
  9404. }
  9405. }
  9406. function applyOspfStaticNbrForm() {
  9407. submitOspfStaticNbr(null);
  9408. }
  9409. async function deleteCurrentOspfStaticNbr() {
  9410. const id = document.getElementById('modal-ospf-snbr-id').value;
  9411. if (!id) return;
  9412. if (!confirm('Delete this static neighbor?')) return;
  9413. try {
  9414. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9415. closeOspfStaticNbrModal();
  9416. showToast('Removed', 'Static neighbor removed', 'success');
  9417. loadDynamicRouting();
  9418. } catch (err) {
  9419. showToast('Error', err.message, 'error');
  9420. }
  9421. }
  9422. async function enableSelectedOspfStaticNbr() {
  9423. const id = state.selectedOspfRow?.['static-nbrs'];
  9424. if (!id) return;
  9425. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9426. if (!n) return;
  9427. n.disabled = false;
  9428. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9429. loadDynamicRouting();
  9430. }
  9431. async function disableSelectedOspfStaticNbr() {
  9432. const id = state.selectedOspfRow?.['static-nbrs'];
  9433. if (!id) return;
  9434. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9435. if (!n) return;
  9436. n.disabled = true;
  9437. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9438. loadDynamicRouting();
  9439. }
  9440. async function removeSelectedOspfStaticNbr() {
  9441. const id = state.selectedOspfRow?.['static-nbrs'];
  9442. if (!id) return;
  9443. if (!confirm('Delete selected static neighbor?')) return;
  9444. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9445. loadDynamicRouting();
  9446. }
  9447. async function promptCommentOspfStaticNbr() {
  9448. const id = state.selectedOspfRow?.['static-nbrs'];
  9449. if (!id) return;
  9450. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9451. if (!n) return;
  9452. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9453. if (comment === null) return;
  9454. n.comment = comment;
  9455. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9456. loadDynamicRouting();
  9457. }
  9458. // Backward-compat aliases
  9459. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9460. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9461. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9462. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9463. function deleteOspfInterface(id) {
  9464. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9465. }
  9466. function toggleOspfInterfaceState(id, disabled) {
  9467. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9468. method: 'POST',
  9469. headers: { 'Content-Type': 'application/json' },
  9470. body: JSON.stringify({ disabled })
  9471. }).then(() => loadDynamicRouting());
  9472. }
  9473. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9474. function deleteOspfArea(id) {
  9475. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9476. }
  9477. // ============================================================================
  9478. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9479. // ============================================================================
  9480. function switchBridgeSubTab(tab) {
  9481. state.bridgeSubTab = tab;
  9482. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9483. tabs.forEach(t => {
  9484. const panel = document.getElementById(`bridge-subtab-${t}`);
  9485. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9486. if (panel) {
  9487. if (t === tab) panel.classList.remove('hidden');
  9488. else panel.classList.add('hidden');
  9489. }
  9490. if (btn) {
  9491. if (t === tab) {
  9492. 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';
  9493. } else {
  9494. 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';
  9495. }
  9496. }
  9497. });
  9498. const addBtn = document.getElementById('bridge-top-action-btn');
  9499. if (addBtn) {
  9500. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9501. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9502. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9503. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9504. }
  9505. if (tab === 'hosts') loadBridgeHosts();
  9506. setTimeout(initTableSorting, 50);
  9507. }
  9508. function openCurrentBridgeModal() {
  9509. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9510. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9511. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9512. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9513. }
  9514. async function loadBridge() {
  9515. try {
  9516. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9517. fetch(`${API_BASE}/bridge/bridges`),
  9518. fetch(`${API_BASE}/bridge/ports`),
  9519. fetch(`${API_BASE}/bridge/vlans`),
  9520. fetch(`${API_BASE}/bridge/summary`),
  9521. fetch(`${API_BASE}/vpn/eoip`),
  9522. fetch(`${API_BASE}/vlans`)
  9523. ]);
  9524. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9525. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9526. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9527. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9528. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9529. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9530. // Badges & Stats
  9531. const bBridges = document.getElementById('bridge-badge-bridges');
  9532. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9533. const bPorts = document.getElementById('bridge-badge-ports');
  9534. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9535. const bVlans = document.getElementById('bridge-badge-vlans');
  9536. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9537. const bHosts = document.getElementById('bridge-badge-hosts');
  9538. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9539. const sBr = document.getElementById('bridge-stat-bridges');
  9540. if (sBr) sBr.innerText = (state.bridges || []).length;
  9541. const sPorts = document.getElementById('bridge-stat-ports');
  9542. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9543. const sHosts = document.getElementById('bridge-stat-hosts');
  9544. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9545. renderBridges();
  9546. renderBridgePorts();
  9547. renderBridgeVLANs();
  9548. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9549. } catch (err) {
  9550. console.error('Failed to load bridge subsystem:', err);
  9551. }
  9552. }
  9553. // ----------------- Bridges -----------------
  9554. function renderBridges() {
  9555. const tbody = document.getElementById('bridge-table-body');
  9556. const empty = document.getElementById('bridge-empty-bridges');
  9557. const countBadge = document.getElementById('bridge-count-badge');
  9558. if (!tbody) return;
  9559. tbody.innerHTML = '';
  9560. const bridges = state.bridges || [];
  9561. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9562. if (bridges.length === 0) {
  9563. empty?.classList.remove('hidden');
  9564. return;
  9565. }
  9566. empty?.classList.add('hidden');
  9567. bridges.forEach((b, idx) => {
  9568. const tr = document.createElement('tr');
  9569. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9570. // Format IP addresses pill list
  9571. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9572. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9573. ipsHtml = b.ip_addresses.map(ip => `
  9574. <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">
  9575. <span>${ip}</span>
  9576. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9577. </span>
  9578. `).join(' ');
  9579. }
  9580. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9581. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9582. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9583. tr.innerHTML = `
  9584. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9585. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9586. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9587. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9588. </td>
  9589. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9590. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9591. <td class="py-2.5 px-3">
  9592. <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>
  9593. </td>
  9594. <td class="py-2.5 px-3 text-center">
  9595. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9596. </td>
  9597. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9598. <td class="py-2.5 px-3">
  9599. <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>
  9600. </td>
  9601. <td class="py-2.5 px-3">
  9602. <div class="flex items-center gap-1.5 flex-wrap">
  9603. ${ipsHtml}
  9604. <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>
  9605. </div>
  9606. </td>
  9607. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9608. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9609. </td>
  9610. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9611. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9612. <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>
  9613. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9614. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9615. </td>
  9616. `;
  9617. tbody.appendChild(tr);
  9618. });
  9619. }
  9620. function openAddBridgeModal() {
  9621. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9622. document.getElementById('bridge-modal-id').value = '';
  9623. document.getElementById('bridge-modal-name').value = 'bridge1';
  9624. document.getElementById('bridge-modal-name').disabled = false;
  9625. document.getElementById('bridge-modal-mtu').value = '1500';
  9626. document.getElementById('bridge-modal-mac').value = '';
  9627. document.getElementById('bridge-modal-stp').value = 'rstp';
  9628. document.getElementById('bridge-modal-priority').value = '32768';
  9629. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9630. document.getElementById('bridge-modal-pvid').value = '1';
  9631. document.getElementById('bridge-modal-fastforward').checked = true;
  9632. document.getElementById('bridge-modal-comment').value = '';
  9633. document.getElementById('bridge-modal-disabled').checked = false;
  9634. toggleBridgeModalVlanFiltering();
  9635. document.getElementById('bridge-modal').classList.remove('hidden');
  9636. }
  9637. function openEditBridgeModal(id) {
  9638. const b = (state.bridges || []).find(x => x.id === id);
  9639. if (!b) return;
  9640. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9641. document.getElementById('bridge-modal-id').value = b.id;
  9642. document.getElementById('bridge-modal-name').value = b.name;
  9643. document.getElementById('bridge-modal-name').disabled = true;
  9644. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9645. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9646. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9647. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9648. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9649. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9650. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9651. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9652. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9653. toggleBridgeModalVlanFiltering();
  9654. document.getElementById('bridge-modal').classList.remove('hidden');
  9655. }
  9656. function closeBridgeModal() {
  9657. document.getElementById('bridge-modal').classList.add('hidden');
  9658. }
  9659. function toggleBridgeModalVlanFiltering() {
  9660. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9661. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9662. if (pvidBox) {
  9663. if (chk) pvidBox.classList.remove('opacity-40');
  9664. else pvidBox.classList.add('opacity-40');
  9665. }
  9666. }
  9667. async function submitSaveBridge(e) {
  9668. e.preventDefault();
  9669. const id = document.getElementById('bridge-modal-id').value;
  9670. const name = document.getElementById('bridge-modal-name').value.trim();
  9671. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9672. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9673. const stp = document.getElementById('bridge-modal-stp').value;
  9674. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9675. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9676. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9677. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9678. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9679. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9680. try {
  9681. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9682. method: 'POST',
  9683. headers: { 'Content-Type': 'application/json' },
  9684. body: JSON.stringify({
  9685. id,
  9686. name,
  9687. mtu,
  9688. mac_address: mac,
  9689. stp,
  9690. priority,
  9691. vlan_filtering: vlanFiltering,
  9692. pvid,
  9693. fast_forward: fastForward,
  9694. comment,
  9695. disabled
  9696. })
  9697. });
  9698. if (res.ok) {
  9699. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9700. closeBridgeModal();
  9701. loadBridge();
  9702. fetchData(false);
  9703. } else {
  9704. const err = await res.json();
  9705. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9706. }
  9707. } catch (err) {
  9708. showToast('Error', err.message, 'error');
  9709. }
  9710. }
  9711. async function toggleBridgeState(id, disabled) {
  9712. try {
  9713. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9714. method: 'POST',
  9715. headers: { 'Content-Type': 'application/json' },
  9716. body: JSON.stringify({ disabled })
  9717. });
  9718. if (res.ok) {
  9719. loadBridge();
  9720. fetchData(false);
  9721. }
  9722. } catch (err) {
  9723. showToast('Error', err.message, 'error');
  9724. }
  9725. }
  9726. async function deleteBridge(id) {
  9727. const b = (state.bridges || []).find(x => x.id === id);
  9728. const name = b ? b.name : id;
  9729. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9730. try {
  9731. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9732. if (res.ok) {
  9733. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9734. loadBridge();
  9735. fetchData(false);
  9736. } else {
  9737. const err = await res.json();
  9738. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9739. }
  9740. } catch (err) {
  9741. showToast('Error', err.message, 'error');
  9742. }
  9743. }
  9744. // ----------------- Bridge IP Assignments -----------------
  9745. function openAddBridgeIPModal(id, name) {
  9746. document.getElementById('bridge-ip-modal-id').value = id;
  9747. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9748. document.getElementById('bridge-ip-modal-cidr').value = '';
  9749. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9750. }
  9751. function closeBridgeIPModal() {
  9752. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9753. }
  9754. async function submitAddBridgeIP(e) {
  9755. e.preventDefault();
  9756. const id = document.getElementById('bridge-ip-modal-id').value;
  9757. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9758. try {
  9759. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9760. method: 'POST',
  9761. headers: { 'Content-Type': 'application/json' },
  9762. body: JSON.stringify({ ip })
  9763. });
  9764. if (res.ok) {
  9765. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9766. closeBridgeIPModal();
  9767. loadBridge();
  9768. fetchData(false);
  9769. } else {
  9770. const err = await res.json();
  9771. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9772. }
  9773. } catch (err) {
  9774. showToast('Error', err.message, 'error');
  9775. }
  9776. }
  9777. async function deleteBridgeIP(id, ip) {
  9778. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9779. try {
  9780. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9781. method: 'DELETE',
  9782. headers: { 'Content-Type': 'application/json' },
  9783. body: JSON.stringify({ ip })
  9784. });
  9785. if (res.ok) {
  9786. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9787. loadBridge();
  9788. fetchData(false);
  9789. }
  9790. } catch (err) {
  9791. showToast('Error', err.message, 'error');
  9792. }
  9793. }
  9794. // ----------------- Bridge Ports -----------------
  9795. function renderBridgePorts() {
  9796. const tbody = document.getElementById('bridge-ports-table-body');
  9797. const empty = document.getElementById('bridge-empty-ports');
  9798. const countBadge = document.getElementById('bridge-ports-count-badge');
  9799. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9800. if (!tbody) return;
  9801. tbody.innerHTML = '';
  9802. // Update filter select
  9803. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9804. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9805. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9806. if (ports.length === 0) {
  9807. empty?.classList.remove('hidden');
  9808. return;
  9809. }
  9810. empty?.classList.add('hidden');
  9811. ports.forEach((p, idx) => {
  9812. const tr = document.createElement('tr');
  9813. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9814. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9815. tr.innerHTML = `
  9816. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9817. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9818. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9819. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9820. </td>
  9821. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9822. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9823. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9824. <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>
  9825. <td class="py-2.5 px-3">
  9826. ${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>'}
  9827. </td>
  9828. <td class="py-2.5 px-3">
  9829. <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>
  9830. </td>
  9831. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9832. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9833. <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>
  9834. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9835. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9836. </td>
  9837. `;
  9838. tbody.appendChild(tr);
  9839. });
  9840. }
  9841. function openAddBridgePortModal() {
  9842. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9843. document.getElementById('bridge-port-modal-id').value = '';
  9844. populateBridgeSelect('bridge-port-modal-bridge');
  9845. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9846. document.getElementById('bridge-port-modal-pvid').value = '1';
  9847. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9848. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9849. document.getElementById('bridge-port-modal-horizon').value = '0';
  9850. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9851. document.getElementById('bridge-port-modal-priority').value = '128';
  9852. document.getElementById('bridge-port-modal-learn').checked = true;
  9853. document.getElementById('bridge-port-modal-comment').value = '';
  9854. document.getElementById('bridge-port-modal-disabled').checked = false;
  9855. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9856. }
  9857. function openEditBridgePortModal(id) {
  9858. const p = (state.bridgePorts || []).find(x => x.id === id);
  9859. if (!p) return;
  9860. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9861. document.getElementById('bridge-port-modal-id').value = p.id;
  9862. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9863. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9864. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9865. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9866. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9867. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9868. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9869. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9870. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9871. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9872. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9873. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9874. }
  9875. function closeBridgePortModal() {
  9876. document.getElementById('bridge-port-modal').classList.add('hidden');
  9877. }
  9878. async function submitSaveBridgePort(e) {
  9879. e.preventDefault();
  9880. const id = document.getElementById('bridge-port-modal-id').value;
  9881. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9882. const iface = document.getElementById('bridge-port-modal-interface').value;
  9883. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9884. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9885. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9886. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9887. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9888. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9889. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9890. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9891. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9892. try {
  9893. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9894. method: 'POST',
  9895. headers: { 'Content-Type': 'application/json' },
  9896. body: JSON.stringify({
  9897. id,
  9898. bridge,
  9899. interface: iface,
  9900. pvid,
  9901. frame_types: frameTypes,
  9902. ingress_filtering: ingressFiltering,
  9903. horizon,
  9904. path_cost: pathCost,
  9905. priority,
  9906. learn,
  9907. comment,
  9908. disabled
  9909. })
  9910. });
  9911. if (res.ok) {
  9912. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9913. closeBridgePortModal();
  9914. loadBridge();
  9915. fetchData(false);
  9916. } else {
  9917. const err = await res.json();
  9918. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9919. }
  9920. } catch (err) {
  9921. showToast('Error', err.message, 'error');
  9922. }
  9923. }
  9924. async function toggleBridgePortState(id, disabled) {
  9925. try {
  9926. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9927. method: 'POST',
  9928. headers: { 'Content-Type': 'application/json' },
  9929. body: JSON.stringify({ disabled })
  9930. });
  9931. if (res.ok) {
  9932. loadBridge();
  9933. fetchData(false);
  9934. }
  9935. } catch (err) {
  9936. showToast('Error', err.message, 'error');
  9937. }
  9938. }
  9939. async function deleteBridgePort(id) {
  9940. const p = (state.bridgePorts || []).find(x => x.id === id);
  9941. const iface = p ? p.interface : id;
  9942. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9943. try {
  9944. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9945. if (res.ok) {
  9946. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9947. loadBridge();
  9948. fetchData(false);
  9949. }
  9950. } catch (err) {
  9951. showToast('Error', err.message, 'error');
  9952. }
  9953. }
  9954. // ----------------- Bridge VLANs -----------------
  9955. function renderBridgeVLANs() {
  9956. const tbody = document.getElementById('bridge-vlans-table-body');
  9957. const empty = document.getElementById('bridge-empty-vlans');
  9958. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9959. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9960. if (!tbody) return;
  9961. tbody.innerHTML = '';
  9962. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9963. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9964. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9965. if (vlans.length === 0) {
  9966. empty?.classList.remove('hidden');
  9967. return;
  9968. }
  9969. empty?.classList.add('hidden');
  9970. vlans.forEach((v, idx) => {
  9971. const tr = document.createElement('tr');
  9972. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9973. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9974. ? 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(' ')
  9975. : '<span class="text-slate-600">none</span>';
  9976. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9977. ? 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(' ')
  9978. : '<span class="text-slate-600">none</span>';
  9979. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9980. tr.innerHTML = `
  9981. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9982. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9983. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9984. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9985. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9986. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9987. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9988. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9989. <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>
  9990. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9991. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9992. </td>
  9993. `;
  9994. tbody.appendChild(tr);
  9995. });
  9996. }
  9997. function openAddBridgeVLANModal() {
  9998. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9999. document.getElementById('bridge-vlan-modal-id').value = '';
  10000. populateBridgeSelect('bridge-vlan-modal-bridge');
  10001. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10002. document.getElementById('bridge-vlan-modal-comment').value = '';
  10003. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10004. updateBridgeVlanPortCheckboxes();
  10005. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10006. }
  10007. function openEditBridgeVLANModal(id) {
  10008. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10009. if (!v) return;
  10010. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10011. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10012. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10013. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10014. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10015. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10016. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10017. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10018. }
  10019. function closeBridgeVlanModal() {
  10020. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10021. }
  10022. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10023. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10024. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10025. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10026. if (!taggedBox || !untaggedBox) return;
  10027. // Ports belonging to the selected bridge
  10028. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10029. if (memberPorts.length === 0) {
  10030. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10031. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10032. return;
  10033. }
  10034. taggedBox.innerHTML = memberPorts.map(p => `
  10035. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10036. <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">
  10037. <span>${p.interface}</span>
  10038. </label>
  10039. `).join('');
  10040. untaggedBox.innerHTML = memberPorts.map(p => `
  10041. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10042. <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">
  10043. <span>${p.interface}</span>
  10044. </label>
  10045. `).join('');
  10046. }
  10047. async function submitSaveBridgeVLAN(e) {
  10048. e.preventDefault();
  10049. const id = document.getElementById('bridge-vlan-modal-id').value;
  10050. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10051. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10052. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10053. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10054. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10055. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10056. try {
  10057. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10058. method: 'POST',
  10059. headers: { 'Content-Type': 'application/json' },
  10060. body: JSON.stringify({
  10061. id,
  10062. bridge,
  10063. vlan_ids: vlanIDs,
  10064. tagged,
  10065. untagged,
  10066. comment,
  10067. disabled
  10068. })
  10069. });
  10070. if (res.ok) {
  10071. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10072. closeBridgeVlanModal();
  10073. loadBridge();
  10074. } else {
  10075. const err = await res.json();
  10076. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10077. }
  10078. } catch (err) {
  10079. showToast('Error', err.message, 'error');
  10080. }
  10081. }
  10082. async function toggleBridgeVLANState(id, disabled) {
  10083. try {
  10084. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10085. method: 'POST',
  10086. headers: { 'Content-Type': 'application/json' },
  10087. body: JSON.stringify({ disabled })
  10088. });
  10089. if (res.ok) loadBridge();
  10090. } catch (err) {
  10091. showToast('Error', err.message, 'error');
  10092. }
  10093. }
  10094. async function deleteBridgeVLAN(id) {
  10095. if (!confirm('Delete this bridge VLAN entry?')) return;
  10096. try {
  10097. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10098. if (res.ok) {
  10099. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10100. loadBridge();
  10101. }
  10102. } catch (err) {
  10103. showToast('Error', err.message, 'error');
  10104. }
  10105. }
  10106. // ----------------- Hosts / MAC Table -----------------
  10107. async function loadBridgeHosts() {
  10108. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10109. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10110. try {
  10111. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10112. const res = await fetch(url);
  10113. if (res.ok) {
  10114. state.bridgeHosts = await res.json();
  10115. renderBridgeHosts();
  10116. }
  10117. } catch (err) {
  10118. console.error('Failed to load bridge hosts:', err);
  10119. }
  10120. }
  10121. function renderBridgeHosts() {
  10122. const tbody = document.getElementById('bridge-hosts-table-body');
  10123. const empty = document.getElementById('bridge-empty-hosts');
  10124. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10125. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10126. if (!tbody) return;
  10127. tbody.innerHTML = '';
  10128. const hosts = (state.bridgeHosts || []).filter(h => {
  10129. if (!search) return true;
  10130. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10131. });
  10132. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10133. if (hosts.length === 0) {
  10134. empty?.classList.remove('hidden');
  10135. return;
  10136. }
  10137. empty?.classList.add('hidden');
  10138. hosts.forEach(h => {
  10139. const tr = document.createElement('tr');
  10140. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10141. let flagBadges = '';
  10142. 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>';
  10143. 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>';
  10144. 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>';
  10145. tr.innerHTML = `
  10146. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10147. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10148. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10149. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10150. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10151. <td class="py-2.5 px-3">${flagBadges}</td>
  10152. `;
  10153. tbody.appendChild(tr);
  10154. });
  10155. }
  10156. async function flushBridgeHosts() {
  10157. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10158. if (!selBridge) {
  10159. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10160. return;
  10161. }
  10162. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10163. try {
  10164. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10165. method: 'POST',
  10166. headers: { 'Content-Type': 'application/json' },
  10167. body: JSON.stringify({ bridge: selBridge })
  10168. });
  10169. if (res.ok) {
  10170. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10171. loadBridgeHosts();
  10172. }
  10173. } catch (err) {
  10174. showToast('Error', err.message, 'error');
  10175. }
  10176. }
  10177. // ----------------- Helpers -----------------
  10178. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10179. const sel = document.getElementById(selectId);
  10180. if (!sel) return;
  10181. const prevVal = currentVal || sel.value;
  10182. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10183. (state.bridges || []).forEach(b => {
  10184. const opt = document.createElement('option');
  10185. opt.value = b.name;
  10186. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10187. if (b.name === prevVal) opt.selected = true;
  10188. sel.appendChild(opt);
  10189. });
  10190. }
  10191. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10192. const sel = document.getElementById(selectId);
  10193. if (!sel) return;
  10194. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10195. // 1. Physical Interfaces
  10196. const grpPhys = document.createElement('optgroup');
  10197. grpPhys.label = 'Physical Interfaces';
  10198. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10199. const opt = document.createElement('option');
  10200. opt.value = i.name;
  10201. opt.innerText = `${i.name} (${i.role || i.type})`;
  10202. if (i.name === currentVal) opt.selected = true;
  10203. grpPhys.appendChild(opt);
  10204. });
  10205. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10206. // 2. VLAN Sub-interfaces
  10207. const grpVlans = document.createElement('optgroup');
  10208. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10209. (state.vlans || []).forEach(v => {
  10210. const opt = document.createElement('option');
  10211. opt.value = v.name;
  10212. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10213. if (v.name === currentVal) opt.selected = true;
  10214. grpVlans.appendChild(opt);
  10215. });
  10216. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10217. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10218. const grpEoip = document.createElement('optgroup');
  10219. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10220. (state.eoipTunnels || []).forEach(t => {
  10221. const opt = document.createElement('option');
  10222. opt.value = t.name;
  10223. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10224. if (t.name === currentVal) opt.selected = true;
  10225. grpEoip.appendChild(opt);
  10226. });
  10227. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10228. }
  10229. // -------------------------------------------------------------
  10230. // RouterOS v7 Routing Filters Management (/routing filter)
  10231. // -------------------------------------------------------------
  10232. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10233. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10234. if (!state.rfSort) state.rfSort = {};
  10235. function switchRoutingFilterTab(tab) {
  10236. state.activeRoutingFilterTab = tab;
  10237. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10238. tabs.forEach(t => {
  10239. const btn = document.getElementById(`tab-rf-${t}`);
  10240. const content = document.getElementById(`tab-content-rf-${t}`);
  10241. if (btn) {
  10242. if (t === tab) {
  10243. 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';
  10244. } else {
  10245. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10246. }
  10247. }
  10248. if (content) {
  10249. if (t === tab) content.classList.remove('hidden');
  10250. else content.classList.add('hidden');
  10251. }
  10252. });
  10253. const chainContainer = document.getElementById('rf-chain-filter-container');
  10254. if (chainContainer) {
  10255. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10256. else chainContainer.classList.add('hidden');
  10257. }
  10258. renderRoutingFilters();
  10259. }
  10260. function selectFilterRow(tab, id) {
  10261. if (state.selectedFilterRow[tab] === id) {
  10262. delete state.selectedFilterRow[tab];
  10263. } else {
  10264. state.selectedFilterRow[tab] = id;
  10265. }
  10266. if (tab === 'rules') renderRoutingFilterRules();
  10267. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10268. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10269. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10270. }
  10271. function openRoutingFilterNewModal() {
  10272. const tab = state.activeRoutingFilterTab || 'rules';
  10273. if (tab === 'rules') openAddRoutingFilterModal();
  10274. else if (tab === 'select-rules') openAddSelectRuleModal();
  10275. else if (tab === 'community-lists') openAddCommunityListModal();
  10276. else if (tab === 'as-lists') openAddASListModal();
  10277. }
  10278. function toggleSelectedRoutingFilter(disabled) {
  10279. const tab = state.activeRoutingFilterTab || 'rules';
  10280. const id = state.selectedFilterRow[tab];
  10281. if (!id) {
  10282. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10283. return;
  10284. }
  10285. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10286. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10287. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10288. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10289. }
  10290. function removeSelectedRoutingFilter() {
  10291. const tab = state.activeRoutingFilterTab || 'rules';
  10292. const id = state.selectedFilterRow[tab];
  10293. if (!id) {
  10294. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10295. return;
  10296. }
  10297. if (tab === 'rules') deleteRoutingFilter(id);
  10298. else if (tab === 'select-rules') deleteSelectRule(id);
  10299. else if (tab === 'community-lists') deleteCommunityList(id);
  10300. else if (tab === 'as-lists') deleteASList(id);
  10301. }
  10302. function searchRoutingFilters(q) {
  10303. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10304. renderRoutingFilters();
  10305. }
  10306. function sortFilterTable(tab, col) {
  10307. if (!state.rfSort) state.rfSort = {};
  10308. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10309. if (state.rfSort[tab].col === col) {
  10310. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10311. } else {
  10312. state.rfSort[tab].col = col;
  10313. state.rfSort[tab].asc = true;
  10314. }
  10315. const asc = state.rfSort[tab].asc;
  10316. let list = [];
  10317. if (tab === 'rules') list = state.routingFilters || [];
  10318. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10319. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10320. else if (tab === 'as-lists') list = state.routingASLists || [];
  10321. list.sort((a, b) => {
  10322. let valA = a[col] ?? '';
  10323. let valB = b[col] ?? '';
  10324. if (col === 'flags') {
  10325. valA = a.disabled ? 'X' : 'A';
  10326. valB = b.disabled ? 'X' : 'A';
  10327. }
  10328. if (typeof valA === 'number' && typeof valB === 'number') {
  10329. return asc ? valA - valB : valB - valA;
  10330. }
  10331. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10332. });
  10333. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10334. allCols.forEach(c => {
  10335. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10336. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10337. });
  10338. if (tab === 'rules') renderRoutingFilterRules();
  10339. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10340. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10341. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10342. }
  10343. function renderRoutingFilters() {
  10344. const navBadge = document.getElementById('badge-filters-count');
  10345. const allRules = state.routingFilters || [];
  10346. if (navBadge) navBadge.innerText = allRules.length;
  10347. // Populate chain filter select options and datalist
  10348. const chainSelect = document.getElementById('routing-filter-chain-select');
  10349. const chainDatalist = document.getElementById('dl-routing-chains');
  10350. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10351. if (chainSelect) {
  10352. const currentVal = state.filterChainSelected || 'all';
  10353. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10354. uniqueChains.map(ch => {
  10355. const count = allRules.filter(r => r.chain === ch).length;
  10356. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10357. }).join('');
  10358. chainSelect.value = currentVal;
  10359. }
  10360. if (chainDatalist) {
  10361. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10362. }
  10363. renderRoutingFilterRules();
  10364. renderRoutingFilterSelectRules();
  10365. renderRoutingFilterCommunityLists();
  10366. renderRoutingFilterASLists();
  10367. }
  10368. function filterRoutingFiltersByChain(chain) {
  10369. state.filterChainSelected = chain;
  10370. renderRoutingFilters();
  10371. }
  10372. // -------------------------------------------------------------
  10373. // TAB 1: RULES (/routing filter rule)
  10374. // -------------------------------------------------------------
  10375. function renderRoutingFilterRules() {
  10376. const tbody = document.getElementById('routing-filter-rules-tbody');
  10377. if (!tbody) return;
  10378. const empty = document.getElementById('rf-rules-empty');
  10379. const statusCount = document.getElementById('rf-status-count');
  10380. let list = (state.routingFilters || []).slice();
  10381. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10382. list = list.filter(r => r.chain === state.filterChainSelected);
  10383. }
  10384. const q = state.rfSearchQuery;
  10385. if (q) {
  10386. list = list.filter(r =>
  10387. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10388. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10389. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10390. (r.comment && r.comment.toLowerCase().includes(q))
  10391. );
  10392. }
  10393. if (!state.rfSort?.['rules']) {
  10394. list.sort((a, b) => {
  10395. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10396. return (a.rule_order || 0) - (b.rule_order || 0);
  10397. });
  10398. }
  10399. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10400. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10401. }
  10402. if (list.length === 0) {
  10403. tbody.innerHTML = '';
  10404. if (empty) empty.classList.remove('hidden');
  10405. return;
  10406. }
  10407. if (empty) empty.classList.add('hidden');
  10408. tbody.innerHTML = list.map(r => {
  10409. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10410. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10411. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10412. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10413. let ruleDisplay = '';
  10414. if (r.rule && r.rule.trim() !== '') {
  10415. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10416. } else {
  10417. let conds = [];
  10418. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10419. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10420. let act = r.action || 'accept';
  10421. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10422. }
  10423. return `
  10424. <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'}">
  10425. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10426. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10427. <td class="py-2 px-3">
  10428. <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>
  10429. </td>
  10430. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10431. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10432. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10433. <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>
  10434. <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>
  10435. <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'}">
  10436. ${r.disabled ? 'Enable' : 'Disable'}
  10437. </button>
  10438. <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">
  10439. Edit
  10440. </button>
  10441. <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">
  10442. ✕
  10443. </button>
  10444. </td>
  10445. </tr>
  10446. `;
  10447. }).join('');
  10448. }
  10449. // -------------------------------------------------------------
  10450. // TAB 2: SELECT RULES (/routing filter select-rule)
  10451. // -------------------------------------------------------------
  10452. function renderRoutingFilterSelectRules() {
  10453. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10454. if (!tbody) return;
  10455. const empty = document.getElementById('rf-select-rules-empty');
  10456. const statusCount = document.getElementById('rf-status-count');
  10457. let list = (state.routingSelectRules || []).slice();
  10458. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10459. list = list.filter(r => r.chain === state.filterChainSelected);
  10460. }
  10461. const q = state.rfSearchQuery;
  10462. if (q) {
  10463. list = list.filter(r =>
  10464. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10465. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10466. (r.comment && r.comment.toLowerCase().includes(q))
  10467. );
  10468. }
  10469. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10470. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10471. }
  10472. if (list.length === 0) {
  10473. tbody.innerHTML = '';
  10474. if (empty) empty.classList.remove('hidden');
  10475. return;
  10476. }
  10477. if (empty) empty.classList.add('hidden');
  10478. tbody.innerHTML = list.map(r => {
  10479. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10480. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10481. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10482. return `
  10483. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10484. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10485. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10486. <td class="py-2 px-3">
  10487. <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>
  10488. </td>
  10489. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10490. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10491. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10492. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10493. ${r.disabled ? 'Enable' : 'Disable'}
  10494. </button>
  10495. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10496. Edit
  10497. </button>
  10498. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10499. ✕
  10500. </button>
  10501. </td>
  10502. </tr>
  10503. `;
  10504. }).join('');
  10505. }
  10506. // -------------------------------------------------------------
  10507. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10508. // -------------------------------------------------------------
  10509. function renderRoutingFilterCommunityLists() {
  10510. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10511. if (!tbody) return;
  10512. const empty = document.getElementById('rf-comm-lists-empty');
  10513. const statusCount = document.getElementById('rf-status-count');
  10514. let list = (state.routingCommunityLists || []).slice();
  10515. const q = state.rfSearchQuery;
  10516. if (q) {
  10517. list = list.filter(cl =>
  10518. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10519. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10520. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10521. );
  10522. }
  10523. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10524. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10525. }
  10526. if (list.length === 0) {
  10527. tbody.innerHTML = '';
  10528. if (empty) empty.classList.remove('hidden');
  10529. return;
  10530. }
  10531. if (empty) empty.classList.add('hidden');
  10532. tbody.innerHTML = list.map(cl => {
  10533. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10534. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10535. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10536. const commBadges = (cl.communities || []).map(c =>
  10537. `<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>`
  10538. ).join(' ');
  10539. return `
  10540. <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'}">
  10541. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10542. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10543. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10544. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10545. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10546. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10547. <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'}">
  10548. ${cl.disabled ? 'Enable' : 'Disable'}
  10549. </button>
  10550. <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">
  10551. Edit
  10552. </button>
  10553. <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">
  10554. ✕
  10555. </button>
  10556. </td>
  10557. </tr>
  10558. `;
  10559. }).join('');
  10560. }
  10561. // -------------------------------------------------------------
  10562. // TAB 4: AS LISTS (/routing filter num-list)
  10563. // -------------------------------------------------------------
  10564. function renderRoutingFilterASLists() {
  10565. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10566. if (!tbody) return;
  10567. const empty = document.getElementById('rf-as-lists-empty');
  10568. const statusCount = document.getElementById('rf-status-count');
  10569. let list = (state.routingASLists || []).slice();
  10570. const q = state.rfSearchQuery;
  10571. if (q) {
  10572. list = list.filter(al =>
  10573. (al.name && al.name.toLowerCase().includes(q)) ||
  10574. (al.range && al.range.toLowerCase().includes(q)) ||
  10575. (al.comment && al.comment.toLowerCase().includes(q))
  10576. );
  10577. }
  10578. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10579. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10580. }
  10581. if (list.length === 0) {
  10582. tbody.innerHTML = '';
  10583. if (empty) empty.classList.remove('hidden');
  10584. return;
  10585. }
  10586. if (empty) empty.classList.add('hidden');
  10587. tbody.innerHTML = list.map(al => {
  10588. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10589. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10590. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10591. return `
  10592. <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'}">
  10593. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10594. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10595. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10596. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10597. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10598. <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'}">
  10599. ${al.disabled ? 'Enable' : 'Disable'}
  10600. </button>
  10601. <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">
  10602. Edit
  10603. </button>
  10604. <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">
  10605. ✕
  10606. </button>
  10607. </td>
  10608. </tr>
  10609. `;
  10610. }).join('');
  10611. }
  10612. // -------------------------------------------------------------
  10613. // SNIPPETS & WIZARD HELPERS
  10614. // -------------------------------------------------------------
  10615. function insertRuleSnippet(type) {
  10616. const textarea = document.getElementById('modal-rf-rule');
  10617. if (!textarea) return;
  10618. let snippet = '';
  10619. switch (type) {
  10620. case 'accept-default':
  10621. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10622. break;
  10623. case 'drop-rfc1918':
  10624. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10625. break;
  10626. case 'len-24':
  10627. snippet = 'if (dst-len > 24) { reject; }';
  10628. break;
  10629. case 'local-pref-150':
  10630. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10631. break;
  10632. case 'as-prepend-2':
  10633. snippet = 'set bgp-path-prepend 2; accept;';
  10634. break;
  10635. case 'set-comm':
  10636. snippet = 'set bgp-communities.add 65000:100; accept;';
  10637. break;
  10638. case 'match-comm':
  10639. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10640. break;
  10641. case 'reject-all':
  10642. snippet = 'reject;';
  10643. break;
  10644. }
  10645. if (!snippet) return;
  10646. if (!textarea.value.trim()) {
  10647. textarea.value = snippet;
  10648. } else {
  10649. textarea.value = textarea.value.trim() + '\n' + snippet;
  10650. }
  10651. }
  10652. function generateScriptFromWizard() {
  10653. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10654. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10655. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10656. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10657. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10658. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10659. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10660. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10661. const conds = [];
  10662. if (pfx) {
  10663. if (pfxLen) {
  10664. if (pfxLen.includes('-')) {
  10665. const parts = pfxLen.split('-');
  10666. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10667. } else {
  10668. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10669. }
  10670. } else {
  10671. conds.push(`dst in ${pfx}`);
  10672. }
  10673. }
  10674. if (proto && proto !== 'any') {
  10675. conds.push(`protocol ${proto}`);
  10676. }
  10677. if (asp) {
  10678. conds.push(`bgp-as-path "${asp}"`);
  10679. }
  10680. if (comm) {
  10681. conds.push(`bgp-communities includes ${comm}`);
  10682. }
  10683. const actions = [];
  10684. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10685. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10686. actions.push(`${act};`);
  10687. let code = '';
  10688. if (conds.length > 0) {
  10689. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10690. } else {
  10691. code = actions.join(' ');
  10692. }
  10693. const textarea = document.getElementById('modal-rf-rule');
  10694. if (textarea) textarea.value = code;
  10695. }
  10696. // -------------------------------------------------------------
  10697. // MODAL CRUD: RULES (/routing filter rule)
  10698. // -------------------------------------------------------------
  10699. function openAddRoutingFilterModal(defaultChain = '') {
  10700. const form = document.getElementById('routing-filter-form');
  10701. if (form) form.reset();
  10702. const idEl = document.getElementById('modal-rf-id');
  10703. if (idEl) idEl.value = '';
  10704. const titleEl = document.getElementById('modal-rf-title');
  10705. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10706. const chainEl = document.getElementById('modal-rf-chain');
  10707. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10708. const orderEl = document.getElementById('modal-rf-order');
  10709. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10710. const ruleEl = document.getElementById('modal-rf-rule');
  10711. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10712. const disEl = document.getElementById('modal-rf-disabled');
  10713. if (disEl) disEl.checked = false;
  10714. const modal = document.getElementById('modal-routing-filter');
  10715. if (modal) modal.classList.remove('hidden');
  10716. }
  10717. function openEditRoutingFilterModal(id) {
  10718. const r = (state.routingFilters || []).find(item => item.id === id);
  10719. if (!r) return;
  10720. const idEl = document.getElementById('modal-rf-id');
  10721. if (idEl) idEl.value = r.id;
  10722. const titleEl = document.getElementById('modal-rf-title');
  10723. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10724. const chainEl = document.getElementById('modal-rf-chain');
  10725. if (chainEl) chainEl.value = r.chain || '';
  10726. const orderEl = document.getElementById('modal-rf-order');
  10727. if (orderEl) orderEl.value = r.rule_order || 10;
  10728. const ruleEl = document.getElementById('modal-rf-rule');
  10729. if (ruleEl) {
  10730. if (r.rule) {
  10731. ruleEl.value = r.rule;
  10732. } else {
  10733. let conds = [];
  10734. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10735. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10736. let act = r.action || 'accept';
  10737. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10738. }
  10739. }
  10740. const comEl = document.getElementById('modal-rf-comment');
  10741. if (comEl) comEl.value = r.comment || '';
  10742. const disEl = document.getElementById('modal-rf-disabled');
  10743. if (disEl) disEl.checked = !!r.disabled;
  10744. const modal = document.getElementById('modal-routing-filter');
  10745. if (modal) modal.classList.remove('hidden');
  10746. }
  10747. function closeRoutingFilterModal() {
  10748. const modal = document.getElementById('modal-routing-filter');
  10749. if (modal) modal.classList.add('hidden');
  10750. }
  10751. async function submitRoutingFilter(e) {
  10752. if (e) e.preventDefault();
  10753. const payload = {
  10754. id: document.getElementById('modal-rf-id').value,
  10755. chain: document.getElementById('modal-rf-chain').value.trim(),
  10756. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10757. rule: document.getElementById('modal-rf-rule').value.trim(),
  10758. comment: document.getElementById('modal-rf-comment').value.trim(),
  10759. disabled: document.getElementById('modal-rf-disabled').checked
  10760. };
  10761. try {
  10762. const res = await fetch(`${API_BASE}/routing/filters`, {
  10763. method: 'POST',
  10764. headers: { 'Content-Type': 'application/json' },
  10765. body: JSON.stringify(payload)
  10766. });
  10767. if (res.ok) {
  10768. closeRoutingFilterModal();
  10769. showToast('Success', 'Routing filter rule saved', 'success');
  10770. loadDynamicRouting();
  10771. } else {
  10772. const err = await res.json();
  10773. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10774. }
  10775. } catch (err) {
  10776. showToast('Error', err.message, 'error');
  10777. }
  10778. }
  10779. async function applyRoutingFilterForm() {
  10780. const payload = {
  10781. id: document.getElementById('modal-rf-id').value,
  10782. chain: document.getElementById('modal-rf-chain').value.trim(),
  10783. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10784. rule: document.getElementById('modal-rf-rule').value.trim(),
  10785. comment: document.getElementById('modal-rf-comment').value.trim(),
  10786. disabled: document.getElementById('modal-rf-disabled').checked
  10787. };
  10788. try {
  10789. const res = await fetch(`${API_BASE}/routing/filters`, {
  10790. method: 'POST',
  10791. headers: { 'Content-Type': 'application/json' },
  10792. body: JSON.stringify(payload)
  10793. });
  10794. if (res.ok) {
  10795. const data = await res.json();
  10796. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10797. showToast('Applied', 'Routing filter configuration applied', 'success');
  10798. loadDynamicRouting();
  10799. } else {
  10800. const err = await res.json();
  10801. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10802. }
  10803. } catch (err) {
  10804. showToast('Error', err.message, 'error');
  10805. }
  10806. }
  10807. async function moveRoutingFilterOrder(id, delta) {
  10808. const list = state.routingFilters || [];
  10809. const idx = list.findIndex(r => r.id === id);
  10810. if (idx < 0) return;
  10811. const targetIdx = idx + delta;
  10812. if (targetIdx < 0 || targetIdx >= list.length) return;
  10813. const currentOrder = list[idx].rule_order || 10;
  10814. const targetOrder = list[targetIdx].rule_order || 20;
  10815. list[idx].rule_order = targetOrder;
  10816. list[targetIdx].rule_order = currentOrder;
  10817. try {
  10818. await fetch(`${API_BASE}/routing/filters`, {
  10819. method: 'POST',
  10820. headers: { 'Content-Type': 'application/json' },
  10821. body: JSON.stringify(list[idx])
  10822. });
  10823. await fetch(`${API_BASE}/routing/filters`, {
  10824. method: 'POST',
  10825. headers: { 'Content-Type': 'application/json' },
  10826. body: JSON.stringify(list[targetIdx])
  10827. });
  10828. loadDynamicRouting();
  10829. } catch (e) {
  10830. console.error('Reorder error:', e);
  10831. }
  10832. }
  10833. async function deleteRoutingFilter(id) {
  10834. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10835. try {
  10836. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10837. if (res.ok) {
  10838. showToast('Deleted', 'Routing filter rule removed', 'info');
  10839. loadDynamicRouting();
  10840. } else {
  10841. const err = await res.json();
  10842. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10843. }
  10844. } catch (err) {
  10845. showToast('Error', err.message, 'error');
  10846. }
  10847. }
  10848. async function toggleRoutingFilterState(id, disabled) {
  10849. try {
  10850. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10851. method: 'POST',
  10852. headers: { 'Content-Type': 'application/json' },
  10853. body: JSON.stringify({ disabled })
  10854. });
  10855. if (res.ok) {
  10856. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10857. loadDynamicRouting();
  10858. } else {
  10859. const err = await res.json();
  10860. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10861. }
  10862. } catch (err) {
  10863. showToast('Error', err.message, 'error');
  10864. }
  10865. }
  10866. // -------------------------------------------------------------
  10867. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10868. // -------------------------------------------------------------
  10869. function openAddSelectRuleModal() {
  10870. document.getElementById('modal-rf-sr-id').value = '';
  10871. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10872. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10873. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10874. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10875. document.getElementById('modal-rf-sr-comment').value = '';
  10876. document.getElementById('modal-rf-sr-disabled').checked = false;
  10877. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10878. }
  10879. function openEditSelectRuleModal(id) {
  10880. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10881. if (!r) return;
  10882. document.getElementById('modal-rf-sr-id').value = r.id;
  10883. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10884. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10885. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10886. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10887. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10888. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10889. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10890. }
  10891. function closeSelectRuleModal() {
  10892. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10893. }
  10894. async function submitSelectRule(e) {
  10895. e.preventDefault();
  10896. const payload = {
  10897. id: document.getElementById('modal-rf-sr-id').value,
  10898. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10899. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10900. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10901. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10902. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10903. };
  10904. try {
  10905. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10906. method: 'POST',
  10907. headers: { 'Content-Type': 'application/json' },
  10908. body: JSON.stringify(payload)
  10909. });
  10910. if (res.ok) {
  10911. closeSelectRuleModal();
  10912. showToast('Success', 'Select rule saved', 'success');
  10913. loadDynamicRouting();
  10914. } else {
  10915. const err = await res.json();
  10916. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10917. }
  10918. } catch (err) {
  10919. showToast('Error', err.message, 'error');
  10920. }
  10921. }
  10922. async function deleteSelectRule(id) {
  10923. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10924. try {
  10925. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10926. if (res.ok) {
  10927. showToast('Deleted', 'Select rule removed', 'info');
  10928. loadDynamicRouting();
  10929. } else {
  10930. const err = await res.json();
  10931. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10932. }
  10933. } catch (err) {
  10934. showToast('Error', err.message, 'error');
  10935. }
  10936. }
  10937. async function toggleSelectRuleState(id, disabled) {
  10938. try {
  10939. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10940. method: 'POST',
  10941. headers: { 'Content-Type': 'application/json' },
  10942. body: JSON.stringify({ disabled })
  10943. });
  10944. if (res.ok) {
  10945. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10946. loadDynamicRouting();
  10947. } else {
  10948. const err = await res.json();
  10949. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10950. }
  10951. } catch (err) {
  10952. showToast('Error', err.message, 'error');
  10953. }
  10954. }
  10955. // -------------------------------------------------------------
  10956. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10957. // -------------------------------------------------------------
  10958. function openAddCommunityListModal() {
  10959. document.getElementById('modal-rf-cl-id').value = '';
  10960. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10961. document.getElementById('modal-rf-cl-name').value = '';
  10962. document.getElementById('modal-rf-cl-communities').value = '';
  10963. document.getElementById('modal-rf-cl-regexp').value = '';
  10964. document.getElementById('modal-rf-cl-comment').value = '';
  10965. document.getElementById('modal-rf-cl-disabled').checked = false;
  10966. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10967. }
  10968. function openEditCommunityListModal(id) {
  10969. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10970. if (!cl) return;
  10971. document.getElementById('modal-rf-cl-id').value = cl.id;
  10972. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10973. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10974. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10975. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10976. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10977. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10978. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10979. }
  10980. function closeCommunityListModal() {
  10981. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10982. }
  10983. async function submitCommunityList(e) {
  10984. e.preventDefault();
  10985. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10986. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10987. const payload = {
  10988. id: document.getElementById('modal-rf-cl-id').value,
  10989. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10990. communities: comms,
  10991. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10992. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10993. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10994. };
  10995. try {
  10996. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10997. method: 'POST',
  10998. headers: { 'Content-Type': 'application/json' },
  10999. body: JSON.stringify(payload)
  11000. });
  11001. if (res.ok) {
  11002. closeCommunityListModal();
  11003. showToast('Success', 'Community list saved', 'success');
  11004. loadDynamicRouting();
  11005. } else {
  11006. const err = await res.json();
  11007. showToast('Error', err.error || 'Failed to save community list', 'error');
  11008. }
  11009. } catch (err) {
  11010. showToast('Error', err.message, 'error');
  11011. }
  11012. }
  11013. async function deleteCommunityList(id) {
  11014. if (!confirm('Are you sure you want to delete this community list?')) return;
  11015. try {
  11016. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11017. if (res.ok) {
  11018. showToast('Deleted', 'Community list removed', 'info');
  11019. loadDynamicRouting();
  11020. } else {
  11021. const err = await res.json();
  11022. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11023. }
  11024. } catch (err) {
  11025. showToast('Error', err.message, 'error');
  11026. }
  11027. }
  11028. async function toggleCommunityListState(id, disabled) {
  11029. try {
  11030. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11031. method: 'POST',
  11032. headers: { 'Content-Type': 'application/json' },
  11033. body: JSON.stringify({ disabled })
  11034. });
  11035. if (res.ok) {
  11036. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11037. loadDynamicRouting();
  11038. } else {
  11039. const err = await res.json();
  11040. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11041. }
  11042. } catch (err) {
  11043. showToast('Error', err.message, 'error');
  11044. }
  11045. }
  11046. // -------------------------------------------------------------
  11047. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11048. // -------------------------------------------------------------
  11049. function openAddASListModal() {
  11050. document.getElementById('modal-rf-al-id').value = '';
  11051. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11052. document.getElementById('modal-rf-al-name').value = '';
  11053. document.getElementById('modal-rf-al-range').value = '';
  11054. document.getElementById('modal-rf-al-comment').value = '';
  11055. document.getElementById('modal-rf-al-disabled').checked = false;
  11056. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11057. }
  11058. function openEditASListModal(id) {
  11059. const al = (state.routingASLists || []).find(item => item.id === id);
  11060. if (!al) return;
  11061. document.getElementById('modal-rf-al-id').value = al.id;
  11062. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11063. document.getElementById('modal-rf-al-name').value = al.name || '';
  11064. document.getElementById('modal-rf-al-range').value = al.range || '';
  11065. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11066. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11067. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11068. }
  11069. function closeASListModal() {
  11070. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11071. }
  11072. async function submitASList(e) {
  11073. e.preventDefault();
  11074. const payload = {
  11075. id: document.getElementById('modal-rf-al-id').value,
  11076. name: document.getElementById('modal-rf-al-name').value.trim(),
  11077. range: document.getElementById('modal-rf-al-range').value.trim(),
  11078. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11079. disabled: document.getElementById('modal-rf-al-disabled').checked
  11080. };
  11081. try {
  11082. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11083. method: 'POST',
  11084. headers: { 'Content-Type': 'application/json' },
  11085. body: JSON.stringify(payload)
  11086. });
  11087. if (res.ok) {
  11088. closeASListModal();
  11089. showToast('Success', 'AS number list saved', 'success');
  11090. loadDynamicRouting();
  11091. } else {
  11092. const err = await res.json();
  11093. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11094. }
  11095. } catch (err) {
  11096. showToast('Error', err.message, 'error');
  11097. }
  11098. }
  11099. async function deleteASList(id) {
  11100. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11101. try {
  11102. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11103. if (res.ok) {
  11104. showToast('Deleted', 'AS list removed', 'info');
  11105. loadDynamicRouting();
  11106. } else {
  11107. const err = await res.json();
  11108. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11109. }
  11110. } catch (err) {
  11111. showToast('Error', err.message, 'error');
  11112. }
  11113. }
  11114. async function toggleASListState(id, disabled) {
  11115. try {
  11116. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11117. method: 'POST',
  11118. headers: { 'Content-Type': 'application/json' },
  11119. body: JSON.stringify({ disabled })
  11120. });
  11121. if (res.ok) {
  11122. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11123. loadDynamicRouting();
  11124. } else {
  11125. const err = await res.json();
  11126. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11127. }
  11128. } catch (err) {
  11129. showToast('Error', err.message, 'error');
  11130. }
  11131. }
  11132. // ==========================================
  11133. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11134. // ==========================================
  11135. function loadToolsView() {
  11136. populateToolsInterfaces();
  11137. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11138. }
  11139. function populateToolsInterfaces() {
  11140. const pingSel = document.getElementById('tools-ping-iface');
  11141. const traceSel = document.getElementById('tools-tr-iface');
  11142. let opts = '<option value="">Auto (Default Route)</option>';
  11143. if (Array.isArray(state.interfaces)) {
  11144. state.interfaces.forEach(iface => {
  11145. if (iface.name) {
  11146. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11147. }
  11148. });
  11149. }
  11150. if (pingSel) {
  11151. const cur = pingSel.value;
  11152. pingSel.innerHTML = opts;
  11153. if (cur) pingSel.value = cur;
  11154. }
  11155. if (traceSel) {
  11156. const cur = traceSel.value;
  11157. traceSel.innerHTML = opts;
  11158. if (cur) traceSel.value = cur;
  11159. }
  11160. }
  11161. function switchToolsSubTab(subTab) {
  11162. state.activeToolsSubTab = subTab;
  11163. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11164. tabs.forEach(t => {
  11165. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11166. const view = document.getElementById(`tools-view-${t}`);
  11167. if (btn) {
  11168. if (t === subTab) {
  11169. 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';
  11170. } else {
  11171. 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';
  11172. }
  11173. }
  11174. if (view) {
  11175. if (t === subTab) {
  11176. view.classList.remove('hidden');
  11177. } else {
  11178. view.classList.add('hidden');
  11179. }
  11180. }
  11181. });
  11182. }
  11183. function setPortPreset(port) {
  11184. const input = document.getElementById('tools-port-num');
  11185. if (input) input.value = port;
  11186. }
  11187. let pingAbortController = null;
  11188. let tracerouteAbortController = null;
  11189. function clearPingTable() {
  11190. const tbody = document.getElementById('tools-ping-tbody');
  11191. if (tbody) tbody.innerHTML = '';
  11192. const rawEl = document.getElementById('tools-ping-raw');
  11193. if (rawEl) rawEl.innerText = '';
  11194. const sentEl = document.getElementById('tools-ping-stat-sent');
  11195. if (sentEl) sentEl.innerText = '0';
  11196. const recvEl = document.getElementById('tools-ping-stat-recv');
  11197. if (recvEl) recvEl.innerText = '0';
  11198. const lossEl = document.getElementById('tools-ping-stat-loss');
  11199. if (lossEl) lossEl.innerText = '0%';
  11200. const avgEl = document.getElementById('tools-ping-stat-avg');
  11201. if (avgEl) avgEl.innerText = '0 ms';
  11202. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11203. if (minMaxEl) minMaxEl.innerText = '-';
  11204. const badge = document.getElementById('tools-ping-status-badge');
  11205. if (badge) {
  11206. badge.className = '';
  11207. badge.innerText = '';
  11208. }
  11209. }
  11210. function clearTracerouteTable() {
  11211. const tbody = document.getElementById('tools-tr-tbody');
  11212. if (tbody) tbody.innerHTML = '';
  11213. const rawEl = document.getElementById('tools-tr-raw');
  11214. if (rawEl) rawEl.innerText = '';
  11215. const statHops = document.getElementById('tools-tr-hops-count');
  11216. if (statHops) statHops.innerText = '0 Hops';
  11217. }
  11218. function resetPingButton() {
  11219. const btn = document.getElementById('tools-ping-btn');
  11220. const btnText = document.getElementById('tools-ping-btn-text');
  11221. const spinner = document.getElementById('tools-ping-spinner');
  11222. if (btn) {
  11223. btn.disabled = false;
  11224. 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';
  11225. }
  11226. if (btnText) btnText.innerText = 'Start Ping';
  11227. if (spinner) spinner.classList.add('hidden');
  11228. }
  11229. function setPingRunningButton() {
  11230. const btn = document.getElementById('tools-ping-btn');
  11231. const btnText = document.getElementById('tools-ping-btn-text');
  11232. const spinner = document.getElementById('tools-ping-spinner');
  11233. if (btn) {
  11234. btn.disabled = false;
  11235. 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';
  11236. }
  11237. if (btnText) btnText.innerText = 'Stop Ping';
  11238. if (spinner) spinner.classList.remove('hidden');
  11239. }
  11240. function resetTracerouteButton() {
  11241. const btn = document.getElementById('tools-tr-btn');
  11242. const btnText = document.getElementById('tools-tr-btn-text');
  11243. const spinner = document.getElementById('tools-tr-spinner');
  11244. if (btn) {
  11245. btn.disabled = false;
  11246. 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';
  11247. }
  11248. if (btnText) btnText.innerText = 'Start Traceroute';
  11249. if (spinner) spinner.classList.add('hidden');
  11250. }
  11251. function setTracerouteRunningButton() {
  11252. const btn = document.getElementById('tools-tr-btn');
  11253. const btnText = document.getElementById('tools-tr-btn-text');
  11254. const spinner = document.getElementById('tools-tr-spinner');
  11255. if (btn) {
  11256. btn.disabled = false;
  11257. 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';
  11258. }
  11259. if (btnText) btnText.innerText = 'Stop Traceroute';
  11260. if (spinner) spinner.classList.remove('hidden');
  11261. }
  11262. async function executePing(e) {
  11263. if (e) e.preventDefault();
  11264. // If already running, clicking the button stops the stream!
  11265. if (pingAbortController) {
  11266. pingAbortController.abort();
  11267. pingAbortController = null;
  11268. resetPingButton();
  11269. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11270. return;
  11271. }
  11272. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11273. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11274. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11275. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11276. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11277. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11278. if (!target) {
  11279. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11280. return;
  11281. }
  11282. clearPingTable();
  11283. const resCard = document.getElementById('tools-ping-results');
  11284. if (resCard) resCard.classList.remove('hidden');
  11285. pingAbortController = new AbortController();
  11286. setPingRunningButton();
  11287. try {
  11288. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11289. method: 'POST',
  11290. headers: { 'Content-Type': 'application/json' },
  11291. body: JSON.stringify({
  11292. target,
  11293. count,
  11294. size,
  11295. timeout,
  11296. interface: iface,
  11297. dont_frag: dontFrag
  11298. }),
  11299. signal: pingAbortController.signal
  11300. });
  11301. if (!res.ok) {
  11302. const errText = await res.text();
  11303. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11304. resetPingButton();
  11305. pingAbortController = null;
  11306. return;
  11307. }
  11308. const reader = res.body.getReader();
  11309. const decoder = new TextDecoder('utf-8');
  11310. let buffer = '';
  11311. while (true) {
  11312. const { done, value } = await reader.read();
  11313. if (done) break;
  11314. buffer += decoder.decode(value, { stream: true });
  11315. const blocks = buffer.split('\n\n');
  11316. buffer = blocks.pop() || '';
  11317. for (const block of blocks) {
  11318. const trimmed = block.trim();
  11319. if (!trimmed) continue;
  11320. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11321. try {
  11322. const evt = JSON.parse(line);
  11323. handleLivePingEvent(evt);
  11324. } catch (parseErr) {
  11325. console.warn('Ping SSE parse error:', parseErr, line);
  11326. }
  11327. }
  11328. }
  11329. } catch (err) {
  11330. if (err.name === 'AbortError') {
  11331. // User aborted normally
  11332. } else {
  11333. showToast('Ping Error', err.message, 'error');
  11334. }
  11335. } finally {
  11336. pingAbortController = null;
  11337. resetPingButton();
  11338. }
  11339. }
  11340. function handleLivePingEvent(evt) {
  11341. const sentEl = document.getElementById('tools-ping-stat-sent');
  11342. const recvEl = document.getElementById('tools-ping-stat-recv');
  11343. const lossEl = document.getElementById('tools-ping-stat-loss');
  11344. const avgEl = document.getElementById('tools-ping-stat-avg');
  11345. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11346. const badge = document.getElementById('tools-ping-status-badge');
  11347. const tbody = document.getElementById('tools-ping-tbody');
  11348. const rawEl = document.getElementById('tools-ping-raw');
  11349. if (evt.raw && rawEl) {
  11350. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11351. rawEl.scrollTop = rawEl.scrollHeight;
  11352. }
  11353. if (evt.type === 'reply') {
  11354. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11355. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11356. if (lossEl && evt.packet_loss_pct !== undefined) {
  11357. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11358. lossEl.className = evt.packet_loss_pct === 0
  11359. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11360. : (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');
  11361. }
  11362. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11363. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11364. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11365. }
  11366. if (badge) {
  11367. if (evt.packet_loss_pct === 0) {
  11368. 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';
  11369. badge.innerText = '100% OK';
  11370. } else {
  11371. 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';
  11372. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11373. }
  11374. }
  11375. if (tbody) {
  11376. const tr = document.createElement('tr');
  11377. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11378. tr.innerHTML = `
  11379. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11380. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11381. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11382. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11383. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11384. <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>
  11385. `;
  11386. tbody.appendChild(tr);
  11387. }
  11388. } else if (evt.type === 'timeout') {
  11389. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11390. if (lossEl && evt.packet_loss_pct !== undefined) {
  11391. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11392. 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';
  11393. }
  11394. if (badge) {
  11395. 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';
  11396. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11397. }
  11398. if (tbody) {
  11399. const tr = document.createElement('tr');
  11400. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11401. tr.innerHTML = `
  11402. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11403. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11404. <td class="py-2 px-3 text-slate-600">--</td>
  11405. <td class="py-2 px-3 text-slate-600">--</td>
  11406. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11407. <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>
  11408. `;
  11409. tbody.appendChild(tr);
  11410. }
  11411. } else if (evt.type === 'unreach') {
  11412. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11413. if (lossEl && evt.packet_loss_pct !== undefined) {
  11414. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11415. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11416. }
  11417. if (badge) {
  11418. 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';
  11419. badge.innerText = 'UNREACHABLE';
  11420. }
  11421. if (tbody) {
  11422. const tr = document.createElement('tr');
  11423. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11424. tr.innerHTML = `
  11425. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11426. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11427. <td class="py-2 px-3 text-slate-600">--</td>
  11428. <td class="py-2 px-3 text-slate-600">--</td>
  11429. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11430. <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>
  11431. `;
  11432. tbody.appendChild(tr);
  11433. }
  11434. } else if (evt.type === 'stats') {
  11435. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11436. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11437. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11438. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11439. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11440. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11441. }
  11442. } else if (evt.type === 'done') {
  11443. 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');
  11444. }
  11445. }
  11446. async function executeTraceroute(e) {
  11447. if (e) e.preventDefault();
  11448. if (tracerouteAbortController) {
  11449. tracerouteAbortController.abort();
  11450. tracerouteAbortController = null;
  11451. resetTracerouteButton();
  11452. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11453. return;
  11454. }
  11455. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11456. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11457. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11458. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11459. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11460. if (!target) {
  11461. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11462. return;
  11463. }
  11464. clearTracerouteTable();
  11465. const resCard = document.getElementById('tools-tr-results');
  11466. if (resCard) resCard.classList.remove('hidden');
  11467. tracerouteAbortController = new AbortController();
  11468. setTracerouteRunningButton();
  11469. try {
  11470. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11471. method: 'POST',
  11472. headers: { 'Content-Type': 'application/json' },
  11473. body: JSON.stringify({
  11474. target,
  11475. max_hops: maxHops,
  11476. protocol,
  11477. interface: iface,
  11478. resolve
  11479. }),
  11480. signal: tracerouteAbortController.signal
  11481. });
  11482. if (!res.ok) {
  11483. const errText = await res.text();
  11484. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11485. resetTracerouteButton();
  11486. tracerouteAbortController = null;
  11487. return;
  11488. }
  11489. const reader = res.body.getReader();
  11490. const decoder = new TextDecoder('utf-8');
  11491. let buffer = '';
  11492. while (true) {
  11493. const { done, value } = await reader.read();
  11494. if (done) break;
  11495. buffer += decoder.decode(value, { stream: true });
  11496. const blocks = buffer.split('\n\n');
  11497. buffer = blocks.pop() || '';
  11498. for (const block of blocks) {
  11499. const trimmed = block.trim();
  11500. if (!trimmed) continue;
  11501. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11502. try {
  11503. const evt = JSON.parse(line);
  11504. handleLiveTracerouteEvent(evt);
  11505. } catch (parseErr) {
  11506. console.warn('Traceroute SSE parse error:', parseErr, line);
  11507. }
  11508. }
  11509. }
  11510. } catch (err) {
  11511. if (err.name === 'AbortError') {
  11512. // User aborted normally
  11513. } else {
  11514. showToast('Traceroute Error', err.message, 'error');
  11515. }
  11516. } finally {
  11517. tracerouteAbortController = null;
  11518. resetTracerouteButton();
  11519. }
  11520. }
  11521. function handleLiveTracerouteEvent(evt) {
  11522. const statHops = document.getElementById('tools-tr-hops-count');
  11523. const tbody = document.getElementById('tools-tr-tbody');
  11524. const rawEl = document.getElementById('tools-tr-raw');
  11525. if (evt.raw && rawEl) {
  11526. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11527. rawEl.scrollTop = rawEl.scrollHeight;
  11528. }
  11529. if (evt.hops_count !== undefined && statHops) {
  11530. statHops.innerText = `${evt.hops_count} Hops`;
  11531. }
  11532. if (evt.type === 'hop' && evt.hop && tbody) {
  11533. const h = evt.hop;
  11534. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11535. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11536. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11537. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11538. const tr = document.createElement('tr');
  11539. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11540. tr.innerHTML = `
  11541. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11542. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11543. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11544. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11545. <td class="py-2.5 px-3 text-right">
  11546. ${isTimeout
  11547. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11548. : '<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>'}
  11549. </td>
  11550. `;
  11551. tbody.appendChild(tr);
  11552. } else if (evt.type === 'done') {
  11553. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11554. }
  11555. }
  11556. async function executeMTR(e) {
  11557. if (e) e.preventDefault();
  11558. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11559. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11560. if (!target) {
  11561. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11562. return;
  11563. }
  11564. const btn = document.getElementById('tools-mtr-btn');
  11565. const spinner = document.getElementById('tools-mtr-spinner');
  11566. if (btn) btn.disabled = true;
  11567. if (spinner) spinner.classList.remove('hidden');
  11568. try {
  11569. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11570. method: 'POST',
  11571. headers: { 'Content-Type': 'application/json' },
  11572. body: JSON.stringify({ target, count: cycles })
  11573. });
  11574. const data = await res.json();
  11575. if (!res.ok) {
  11576. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11577. return;
  11578. }
  11579. const resCard = document.getElementById('tools-mtr-results');
  11580. if (resCard) resCard.classList.remove('hidden');
  11581. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11582. const statHops = document.getElementById('tools-mtr-hops-count');
  11583. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11584. const tbody = document.getElementById('tools-mtr-tbody');
  11585. if (tbody) {
  11586. if (hopsCount > 0) {
  11587. tbody.innerHTML = data.hops.map(h => {
  11588. 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');
  11589. return `
  11590. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11591. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11592. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11593. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11594. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11595. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11596. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11597. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11598. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11599. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11600. </tr>
  11601. `;
  11602. }).join('');
  11603. } else {
  11604. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11605. }
  11606. }
  11607. const rawEl = document.getElementById('tools-mtr-raw');
  11608. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11609. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11610. } catch (err) {
  11611. showToast('MTR Error', err.message, 'error');
  11612. } finally {
  11613. if (btn) btn.disabled = false;
  11614. if (spinner) spinner.classList.add('hidden');
  11615. }
  11616. }
  11617. async function executeDNS(e) {
  11618. if (e) e.preventDefault();
  11619. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11620. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11621. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11622. if (!domain) {
  11623. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11624. return;
  11625. }
  11626. const btn = document.getElementById('tools-dns-btn');
  11627. const spinner = document.getElementById('tools-dns-spinner');
  11628. if (btn) btn.disabled = true;
  11629. if (spinner) spinner.classList.remove('hidden');
  11630. try {
  11631. const res = await fetch(`${API_BASE}/tools/dns`, {
  11632. method: 'POST',
  11633. headers: { 'Content-Type': 'application/json' },
  11634. body: JSON.stringify({ domain, type, server })
  11635. });
  11636. const data = await res.json();
  11637. if (!res.ok) {
  11638. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11639. return;
  11640. }
  11641. const resCard = document.getElementById('tools-dns-results');
  11642. if (resCard) resCard.classList.remove('hidden');
  11643. const metaEl = document.getElementById('tools-dns-meta');
  11644. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11645. const tbody = document.getElementById('tools-dns-tbody');
  11646. if (tbody) {
  11647. if (Array.isArray(data.records) && data.records.length > 0) {
  11648. tbody.innerHTML = data.records.map(r => `
  11649. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11650. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11651. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11652. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11653. <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>
  11654. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11655. </tr>
  11656. `).join('');
  11657. } else {
  11658. 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>`;
  11659. }
  11660. }
  11661. const rawEl = document.getElementById('tools-dns-raw');
  11662. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11663. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11664. } catch (err) {
  11665. showToast('DNS Error', err.message, 'error');
  11666. } finally {
  11667. if (btn) btn.disabled = false;
  11668. if (spinner) spinner.classList.add('hidden');
  11669. }
  11670. }
  11671. async function executePortProbe(e) {
  11672. if (e) e.preventDefault();
  11673. const target = document.getElementById('tools-port-target')?.value?.trim();
  11674. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11675. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11676. if (!target || !port) {
  11677. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11678. return;
  11679. }
  11680. const btn = document.getElementById('tools-port-btn');
  11681. const spinner = document.getElementById('tools-port-spinner');
  11682. if (btn) btn.disabled = true;
  11683. if (spinner) spinner.classList.remove('hidden');
  11684. try {
  11685. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11686. method: 'POST',
  11687. headers: { 'Content-Type': 'application/json' },
  11688. body: JSON.stringify({ target, port, timeout })
  11689. });
  11690. const data = await res.json();
  11691. if (!res.ok) {
  11692. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11693. return;
  11694. }
  11695. const resCard = document.getElementById('tools-port-results');
  11696. if (resCard) resCard.classList.remove('hidden');
  11697. const banner = document.getElementById('tools-port-banner');
  11698. const icon = document.getElementById('tools-port-icon');
  11699. const title = document.getElementById('tools-port-title');
  11700. const sub = document.getElementById('tools-port-sub');
  11701. const latency = document.getElementById('tools-port-latency');
  11702. if (data.open) {
  11703. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11704. if (icon) {
  11705. 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';
  11706. icon.innerText = '✓';
  11707. }
  11708. if (title) {
  11709. title.className = 'text-sm font-bold text-emerald-300';
  11710. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11711. }
  11712. if (sub) {
  11713. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11714. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11715. }
  11716. if (latency) {
  11717. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11718. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11719. }
  11720. } else {
  11721. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11722. if (icon) {
  11723. 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';
  11724. icon.innerText = '✕';
  11725. }
  11726. if (title) {
  11727. title.className = 'text-sm font-bold text-rose-300';
  11728. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11729. }
  11730. if (sub) {
  11731. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11732. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11733. }
  11734. if (latency) {
  11735. latency.className = 'text-base font-bold font-mono text-slate-500';
  11736. latency.innerText = '--';
  11737. }
  11738. }
  11739. const rawEl = document.getElementById('tools-port-raw');
  11740. 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'}`);
  11741. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11742. } catch (err) {
  11743. showToast('Probe Error', err.message, 'error');
  11744. } finally {
  11745. if (btn) btn.disabled = false;
  11746. if (spinner) spinner.classList.add('hidden');
  11747. }
  11748. }
  11749. // ==========================================
  11750. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11751. // ==========================================
  11752. async function loadDHCPClients(showToastMsg = false) {
  11753. try {
  11754. const [clientsRes, sumRes] = await Promise.all([
  11755. fetch(`${API_BASE}/dhcp/clients`),
  11756. fetch(`${API_BASE}/dhcp/clients/summary`)
  11757. ]);
  11758. if (clientsRes.ok) {
  11759. state.dhcpClients = await clientsRes.json();
  11760. }
  11761. if (sumRes.ok) {
  11762. state.dhcpSummary = await sumRes.json();
  11763. }
  11764. renderDHCPClients();
  11765. updateDHCPSummaryCards();
  11766. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11767. if (bDhcp && state.dhcpSummary) {
  11768. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11769. }
  11770. if (showToastMsg) {
  11771. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11772. }
  11773. } catch (err) {
  11774. console.error('Failed to load DHCP clients:', err);
  11775. if (showToastMsg) {
  11776. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11777. }
  11778. }
  11779. }
  11780. function updateDHCPSummaryCards() {
  11781. const sum = state.dhcpSummary || {
  11782. total_clients: (state.dhcpClients || []).length,
  11783. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11784. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11785. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11786. };
  11787. const totalEl = document.getElementById('dhcp-stat-total');
  11788. const boundEl = document.getElementById('dhcp-stat-bound');
  11789. const searchEl = document.getElementById('dhcp-stat-searching');
  11790. const disEl = document.getElementById('dhcp-stat-disabled');
  11791. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11792. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11793. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11794. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11795. }
  11796. function renderDHCPClients() {
  11797. const tbody = document.getElementById('dhcp-clients-tbody');
  11798. const emptyState = document.getElementById('dhcp-clients-empty');
  11799. if (!tbody) return;
  11800. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11801. if (clients.length === 0) {
  11802. tbody.innerHTML = '';
  11803. if (emptyState) emptyState.classList.remove('hidden');
  11804. return;
  11805. }
  11806. if (emptyState) emptyState.classList.add('hidden');
  11807. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11808. if (tbody.dataset.sig === sig) return;
  11809. tbody.dataset.sig = sig;
  11810. tbody.innerHTML = clients.map(c => {
  11811. let statusBadge = '';
  11812. if (!c.enabled) {
  11813. 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>';
  11814. } else if (c.status === 'bound') {
  11815. 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>';
  11816. } else if (c.status === 'searching') {
  11817. 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>';
  11818. } else if (c.status === 'stopped') {
  11819. 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>';
  11820. } else {
  11821. 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>`;
  11822. }
  11823. 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>';
  11824. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11825. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11826. 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>';
  11827. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11828. // Option flags
  11829. const flags = [];
  11830. 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>');
  11831. 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>');
  11832. 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>');
  11833. 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>`);
  11834. return `
  11835. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11836. <td class="py-3 px-4">
  11837. <div class="flex items-center gap-2">
  11838. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11839. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11840. </div>
  11841. </td>
  11842. <td class="py-3 px-4">${statusBadge}</td>
  11843. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11844. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11845. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11846. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11847. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11848. <td class="py-3 px-4">
  11849. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11850. </td>
  11851. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11852. ${c.enabled ? `
  11853. <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>
  11854. <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>
  11855. <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>
  11856. ` : `
  11857. <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>
  11858. `}
  11859. <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>
  11860. <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>
  11861. </td>
  11862. </tr>
  11863. `;
  11864. }).join('');
  11865. }
  11866. function openDHCPClientModal(clientId = null) {
  11867. const modal = document.getElementById('modal-dhcp-client');
  11868. if (!modal) return;
  11869. const title = document.getElementById('modal-dhcp-title');
  11870. const idInput = document.getElementById('modal-dhcp-id');
  11871. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11872. const distInput = document.getElementById('modal-dhcp-distance');
  11873. const commentInput = document.getElementById('modal-dhcp-comment');
  11874. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11875. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11876. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11877. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11878. // Populate interfaces
  11879. if (ifaceSelect) {
  11880. let opts = '<option value="">Select interface...</option>';
  11881. const allIfaces = state.interfaces || [];
  11882. const allVlans = state.vlans || [];
  11883. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11884. // Group 1: Physical & Bridge Interfaces
  11885. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11886. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11887. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11888. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11889. });
  11890. opts += '</optgroup>';
  11891. // Group 2: VLAN Interfaces
  11892. if (allVlans.length > 0) {
  11893. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11894. allVlans.forEach(v => {
  11895. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11896. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11897. });
  11898. opts += '</optgroup>';
  11899. }
  11900. ifaceSelect.innerHTML = opts;
  11901. }
  11902. if (clientId) {
  11903. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11904. if (client) {
  11905. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11906. if (idInput) idInput.value = client.id;
  11907. if (ifaceSelect) {
  11908. ifaceSelect.value = client.interface;
  11909. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11910. }
  11911. if (distInput) distInput.value = client.default_route_distance || 1;
  11912. if (commentInput) commentInput.value = client.comment || '';
  11913. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11914. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11915. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11916. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11917. }
  11918. } else {
  11919. if (title) title.innerText = 'Add DHCP Client';
  11920. if (idInput) idInput.value = '';
  11921. if (ifaceSelect) {
  11922. ifaceSelect.value = '';
  11923. ifaceSelect.disabled = false;
  11924. }
  11925. if (distInput) distInput.value = 1;
  11926. if (commentInput) commentInput.value = '';
  11927. if (defRouteCheck) defRouteCheck.checked = true;
  11928. if (peerDnsCheck) peerDnsCheck.checked = true;
  11929. if (peerNtpCheck) peerNtpCheck.checked = true;
  11930. if (enabledCheck) enabledCheck.checked = true;
  11931. }
  11932. modal.classList.remove('hidden');
  11933. }
  11934. function openDHCPClientModalForIface(ifaceName) {
  11935. openDHCPClientModal();
  11936. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11937. if (ifaceSelect && ifaceName) {
  11938. ifaceSelect.value = ifaceName;
  11939. }
  11940. }
  11941. function closeDHCPClientModal() {
  11942. const modal = document.getElementById('modal-dhcp-client');
  11943. if (modal) modal.classList.add('hidden');
  11944. }
  11945. async function submitSaveDHCPClient(e) {
  11946. if (e) e.preventDefault();
  11947. const id = document.getElementById('modal-dhcp-id')?.value;
  11948. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11949. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11950. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11951. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11952. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11953. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11954. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11955. if (!id && !iface) {
  11956. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11957. return;
  11958. }
  11959. try {
  11960. let res;
  11961. if (id) {
  11962. // PUT update
  11963. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11964. method: 'PUT',
  11965. headers: { 'Content-Type': 'application/json' },
  11966. body: JSON.stringify({
  11967. enabled,
  11968. add_default_route: defRoute,
  11969. default_route_distance: distance,
  11970. use_peer_dns: peerDns,
  11971. use_peer_ntp: peerNtp,
  11972. comment
  11973. })
  11974. });
  11975. } else {
  11976. // POST create
  11977. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11978. method: 'POST',
  11979. headers: { 'Content-Type': 'application/json' },
  11980. body: JSON.stringify({
  11981. interface: iface,
  11982. enabled,
  11983. add_default_route: defRoute,
  11984. default_route_distance: distance,
  11985. use_peer_dns: peerDns,
  11986. use_peer_ntp: peerNtp,
  11987. comment
  11988. })
  11989. });
  11990. }
  11991. const data = await res.json();
  11992. if (!res.ok) {
  11993. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11994. return;
  11995. }
  11996. closeDHCPClientModal();
  11997. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11998. await loadDHCPClients();
  11999. fetchData(); // refresh interfaces list with new lease/status
  12000. } catch (err) {
  12001. showToast('Error', err.message, 'error');
  12002. }
  12003. }
  12004. async function toggleDHCPClientState(id, enabled) {
  12005. try {
  12006. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12007. method: 'POST',
  12008. headers: { 'Content-Type': 'application/json' },
  12009. body: JSON.stringify({ enabled })
  12010. });
  12011. const data = await res.json();
  12012. if (!res.ok) {
  12013. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12014. return;
  12015. }
  12016. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12017. await loadDHCPClients();
  12018. fetchData();
  12019. } catch (err) {
  12020. showToast('Error', err.message, 'error');
  12021. }
  12022. }
  12023. async function renewDHCPClient(id) {
  12024. try {
  12025. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12026. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12027. method: 'POST'
  12028. });
  12029. const data = await res.json();
  12030. if (!res.ok) {
  12031. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12032. return;
  12033. }
  12034. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12035. setTimeout(() => {
  12036. loadDHCPClients();
  12037. fetchData();
  12038. }, 1500);
  12039. } catch (err) {
  12040. showToast('Error', err.message, 'error');
  12041. }
  12042. }
  12043. async function releaseDHCPClient(id) {
  12044. try {
  12045. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12046. method: 'POST'
  12047. });
  12048. const data = await res.json();
  12049. if (!res.ok) {
  12050. showToast('Error', data.error || 'Failed to release lease', 'error');
  12051. return;
  12052. }
  12053. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12054. await loadDHCPClients();
  12055. fetchData();
  12056. } catch (err) {
  12057. showToast('Error', err.message, 'error');
  12058. }
  12059. }
  12060. async function deleteDHCPClient(id, ifaceName) {
  12061. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12062. return;
  12063. }
  12064. try {
  12065. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12066. method: 'DELETE'
  12067. });
  12068. const data = await res.json();
  12069. if (!res.ok) {
  12070. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12071. return;
  12072. }
  12073. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12074. await loadDHCPClients();
  12075. fetchData();
  12076. } catch (err) {
  12077. showToast('Error', err.message, 'error');
  12078. }
  12079. }
  12080. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12081. async function loadDHCPServer(populate = true) {
  12082. try {
  12083. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12084. fetch(`${API_BASE}/dhcp-server/summary`),
  12085. fetch(`${API_BASE}/dhcp-server/servers`),
  12086. fetch(`${API_BASE}/dhcp-server/networks`),
  12087. fetch(`${API_BASE}/dhcp-server/leases`),
  12088. fetch(`${API_BASE}/dhcp-server/options`)
  12089. ]);
  12090. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12091. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12092. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12093. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12094. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12095. const sum = state.dhcpServerSummary || {};
  12096. const srvs = state.dhcpServers || [];
  12097. const nets = state.dhcpNetworks || [];
  12098. const leases = state.dhcpLeases || [];
  12099. const opts = state.dhcpOptions || [];
  12100. // KPI Cards
  12101. const statActive = document.getElementById('dhcp-server-stat-active');
  12102. if (statActive) {
  12103. const activeCount = srvs.filter(s => s.running).length;
  12104. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12105. }
  12106. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12107. if (statLeases) {
  12108. statLeases.innerText = leases.length;
  12109. }
  12110. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12111. if (statLeasesSub) {
  12112. const dyn = leases.filter(l => l.dynamic).length;
  12113. const st = leases.filter(l => !l.dynamic).length;
  12114. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12115. }
  12116. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12117. if (statNetworks) {
  12118. statNetworks.innerText = nets.length;
  12119. }
  12120. // Subtab Badges
  12121. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12122. if (bSrv) bSrv.innerText = srvs.length;
  12123. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12124. if (bNet) bNet.innerText = nets.length;
  12125. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12126. if (bLease) bLease.innerText = leases.length;
  12127. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12128. if (bOpt) bOpt.innerText = opts.length;
  12129. // Sidebar Badge
  12130. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12131. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12132. renderCurrentDHCPServerTab();
  12133. } catch (err) {
  12134. console.error('Failed to load DHCP Server:', err);
  12135. }
  12136. }
  12137. function switchDHCPServerTab(tab) {
  12138. state.dhcpServerTab = tab;
  12139. const tabs = ['servers', 'networks', 'leases', 'options'];
  12140. tabs.forEach(t => {
  12141. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12142. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12143. if (panel) {
  12144. if (t === tab) panel.classList.remove('hidden');
  12145. else panel.classList.add('hidden');
  12146. }
  12147. if (btn) {
  12148. if (t === tab) {
  12149. 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';
  12150. } else {
  12151. 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';
  12152. }
  12153. }
  12154. });
  12155. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12156. if (addBtn) {
  12157. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12158. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12159. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12160. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12161. }
  12162. renderCurrentDHCPServerTab();
  12163. }
  12164. function handleDHCPServerPrimaryAdd() {
  12165. const tab = state.dhcpServerTab || 'servers';
  12166. if (tab === 'servers') openAddDHCPServerModal();
  12167. else if (tab === 'networks') openAddDHCPNetworkModal();
  12168. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12169. else if (tab === 'options') openAddDHCPOptionModal();
  12170. }
  12171. function renderCurrentDHCPServerTab() {
  12172. const tab = state.dhcpServerTab || 'servers';
  12173. if (tab === 'servers') renderDHCPServers();
  12174. else if (tab === 'networks') renderDHCPNetworks();
  12175. else if (tab === 'leases') renderDHCPLeases();
  12176. else if (tab === 'options') renderDHCPOptions();
  12177. }
  12178. function renderDHCPServers() {
  12179. const tbody = document.getElementById('dhcp-server-tbody');
  12180. const empty = document.getElementById('dhcp-server-empty');
  12181. if (!tbody) return;
  12182. const servers = state.dhcpServers || [];
  12183. if (servers.length === 0) {
  12184. tbody.innerHTML = '';
  12185. empty?.classList.remove('hidden');
  12186. return;
  12187. }
  12188. empty?.classList.add('hidden');
  12189. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12190. if (tbody.dataset.sig === sig) return;
  12191. tbody.dataset.sig = sig;
  12192. tbody.innerHTML = '';
  12193. servers.forEach(s => {
  12194. const tr = document.createElement('tr');
  12195. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12196. tr.innerHTML = `
  12197. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12198. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12199. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12200. <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>
  12201. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12202. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12203. <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>
  12204. <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>
  12205. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12206. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12207. <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>
  12208. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12209. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12210. </td>
  12211. `;
  12212. tbody.appendChild(tr);
  12213. });
  12214. }
  12215. function renderDHCPNetworks() {
  12216. const tbody = document.getElementById('dhcp-networks-tbody');
  12217. const empty = document.getElementById('dhcp-networks-empty');
  12218. if (!tbody) return;
  12219. tbody.innerHTML = '';
  12220. const networks = state.dhcpNetworks || [];
  12221. if (networks.length === 0) {
  12222. empty?.classList.remove('hidden');
  12223. return;
  12224. }
  12225. empty?.classList.add('hidden');
  12226. networks.forEach(n => {
  12227. const tr = document.createElement('tr');
  12228. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12229. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12230. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  12231. tr.innerHTML = `
  12232. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12233. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12234. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12235. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12236. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12237. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  12238. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  12239. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  12240. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12241. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12242. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12243. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12244. </td>
  12245. `;
  12246. tbody.appendChild(tr);
  12247. });
  12248. }
  12249. function renderDHCPLeases() {
  12250. const tbody = document.getElementById('dhcp-leases-tbody');
  12251. const empty = document.getElementById('dhcp-leases-empty');
  12252. if (!tbody) return;
  12253. tbody.innerHTML = '';
  12254. const leases = state.dhcpLeases || [];
  12255. if (leases.length === 0) {
  12256. empty?.classList.remove('hidden');
  12257. return;
  12258. }
  12259. empty?.classList.add('hidden');
  12260. leases.forEach(l => {
  12261. const tr = document.createElement('tr');
  12262. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12263. 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>';
  12264. const statusBadge = l.status === 'bound'
  12265. ? '<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>'
  12266. : l.status === 'static'
  12267. ? '<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>'
  12268. : '<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>';
  12269. const makeStaticBtn = l.dynamic
  12270. ? `<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>`
  12271. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12272. tr.innerHTML = `
  12273. <td class="py-2.5 px-3 text-center">${flag}</td>
  12274. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12275. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12276. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12277. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12278. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12279. <td class="py-2.5 px-3">${statusBadge}</td>
  12280. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12281. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12282. ${makeStaticBtn}
  12283. </td>
  12284. `;
  12285. tbody.appendChild(tr);
  12286. });
  12287. }
  12288. function renderDHCPOptions() {
  12289. const tbody = document.getElementById('dhcp-options-tbody');
  12290. const empty = document.getElementById('dhcp-options-empty');
  12291. if (!tbody) return;
  12292. tbody.innerHTML = '';
  12293. const options = state.dhcpOptions || [];
  12294. if (options.length === 0) {
  12295. empty?.classList.remove('hidden');
  12296. return;
  12297. }
  12298. empty?.classList.add('hidden');
  12299. options.forEach(o => {
  12300. const tr = document.createElement('tr');
  12301. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12302. tr.innerHTML = `
  12303. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12304. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12305. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12306. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12307. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12308. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12309. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12310. </td>
  12311. `;
  12312. tbody.appendChild(tr);
  12313. });
  12314. }
  12315. // ==================== MODALS & ACTIONS: SERVER ====================
  12316. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12317. const sel = document.getElementById(elemId);
  12318. if (!sel) return;
  12319. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12320. const networks = state.dhcpNetworks || [];
  12321. networks.forEach(n => {
  12322. const opt = document.createElement('option');
  12323. opt.value = n.address;
  12324. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12325. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12326. opt.selected = true;
  12327. }
  12328. sel.appendChild(opt);
  12329. });
  12330. }
  12331. function onDHCPServerNetworkChange() {
  12332. const netSel = document.getElementById('dhcp-server-modal-network');
  12333. if (!netSel) return;
  12334. const netVal = netSel.value;
  12335. if (!netVal) return;
  12336. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12337. if (!poolInput) return;
  12338. // Auto-calculate suggested address pool based on subnet CIDR
  12339. const parts = netVal.split('/');
  12340. const ip = parts[0];
  12341. const cidr = parseInt(parts[1] || '24', 10);
  12342. if (cidr === 24) {
  12343. const octets = ip.split('.');
  12344. if (octets.length === 4) {
  12345. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12346. poolInput.value = `${base}.10-${base}.254`;
  12347. }
  12348. }
  12349. }
  12350. function openAddDHCPServerModal() {
  12351. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12352. document.getElementById('dhcp-server-modal-id').value = '';
  12353. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12354. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12355. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12356. document.getElementById('dhcp-server-modal-comment').value = '';
  12357. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12358. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12359. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12360. const networks = state.dhcpNetworks || [];
  12361. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12362. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12363. if (defaultNet) {
  12364. onDHCPServerNetworkChange();
  12365. }
  12366. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12367. }
  12368. function openEditDHCPServerModal(id) {
  12369. const s = (state.dhcpServers || []).find(item => item.id === id);
  12370. if (!s) return;
  12371. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12372. document.getElementById('dhcp-server-modal-id').value = s.id;
  12373. document.getElementById('dhcp-server-modal-name').value = s.name;
  12374. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12375. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12376. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12377. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12378. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12379. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12380. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12381. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12382. }
  12383. function closeDHCPServerModal() {
  12384. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12385. }
  12386. async function submitSaveDHCPServer(e) {
  12387. e.preventDefault();
  12388. const id = document.getElementById('dhcp-server-modal-id').value;
  12389. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12390. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12391. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12392. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12393. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12394. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12395. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12396. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12397. try {
  12398. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12399. method: 'POST',
  12400. headers: { 'Content-Type': 'application/json' },
  12401. body: JSON.stringify({
  12402. id,
  12403. name,
  12404. interface: iface,
  12405. network,
  12406. address_pool: pool,
  12407. lease_time: leaseTime,
  12408. authoritative,
  12409. disabled,
  12410. comment
  12411. })
  12412. });
  12413. if (res.ok) {
  12414. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12415. closeDHCPServerModal();
  12416. loadDHCPServer(false);
  12417. fetchData(false);
  12418. } else {
  12419. const err = await res.text();
  12420. showToast('Error', err, 'error');
  12421. }
  12422. } catch (err) {
  12423. showToast('Error', err.message, 'error');
  12424. }
  12425. }
  12426. async function toggleDHCPServerState(id, disabled) {
  12427. try {
  12428. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12429. method: 'POST',
  12430. headers: { 'Content-Type': 'application/json' },
  12431. body: JSON.stringify({ disabled })
  12432. });
  12433. if (res.ok) {
  12434. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12435. loadDHCPServer(false);
  12436. fetchData(false);
  12437. }
  12438. } catch (err) {
  12439. showToast('Error', err.message, 'error');
  12440. }
  12441. }
  12442. async function deleteDHCPServer(id, name) {
  12443. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12444. try {
  12445. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12446. if (res.ok) {
  12447. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12448. loadDHCPServer(false);
  12449. fetchData(false);
  12450. }
  12451. } catch (err) {
  12452. showToast('Error', err.message, 'error');
  12453. }
  12454. }
  12455. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12456. function openAddDHCPNetworkModal() {
  12457. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12458. document.getElementById('dhcp-network-modal-id').value = '';
  12459. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12460. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12461. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12462. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12463. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  12464. document.getElementById('dhcp-network-modal-tftp').value = '';
  12465. document.getElementById('dhcp-network-modal-bootfile').value = '';
  12466. document.getElementById('dhcp-network-modal-wins').value = '';
  12467. document.getElementById('dhcp-network-modal-netmask').value = '';
  12468. document.getElementById('dhcp-network-modal-comment').value = '';
  12469. renderDHCPNetworkOptionsCheckboxes([]);
  12470. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12471. }
  12472. function openEditDHCPNetworkModal(id) {
  12473. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12474. if (!n) return;
  12475. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12476. document.getElementById('dhcp-network-modal-id').value = n.id;
  12477. document.getElementById('dhcp-network-modal-address').value = n.address;
  12478. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12479. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12480. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12481. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  12482. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  12483. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  12484. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  12485. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12486. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12487. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12488. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12489. }
  12490. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12491. const container = document.getElementById('dhcp-network-modal-options-list');
  12492. if (!container) return;
  12493. container.innerHTML = '';
  12494. const opts = state.dhcpOptions || [];
  12495. if (opts.length === 0) {
  12496. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12497. return;
  12498. }
  12499. opts.forEach(o => {
  12500. const isChecked = selectedIds.includes(o.id);
  12501. const label = document.createElement('label');
  12502. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12503. label.innerHTML = `
  12504. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12505. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12506. `;
  12507. container.appendChild(label);
  12508. });
  12509. }
  12510. function closeDHCPNetworkModal() {
  12511. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12512. }
  12513. async function submitSaveDHCPNetwork(e) {
  12514. e.preventDefault();
  12515. const id = document.getElementById('dhcp-network-modal-id').value;
  12516. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12517. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12518. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12519. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12520. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12521. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12522. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12523. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12524. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12525. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12526. const selectedOpts = [];
  12527. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12528. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12529. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12530. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12531. try {
  12532. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12533. method: 'POST',
  12534. headers: { 'Content-Type': 'application/json' },
  12535. body: JSON.stringify({
  12536. id,
  12537. address,
  12538. gateway,
  12539. netmask,
  12540. dns_servers: dnsServers,
  12541. domain,
  12542. ntp_servers: ntpServers,
  12543. next_server: tftp,
  12544. boot_file_name: bootfile,
  12545. wins_servers: winsServers,
  12546. dhcp_options: selectedOpts,
  12547. comment
  12548. })
  12549. });
  12550. if (res.ok) {
  12551. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12552. closeDHCPNetworkModal();
  12553. loadDHCPServer(false);
  12554. fetchData(false);
  12555. } else {
  12556. const err = await res.text();
  12557. showToast('Error', err, 'error');
  12558. }
  12559. } catch (err) {
  12560. showToast('Error', err.message, 'error');
  12561. }
  12562. }
  12563. async function deleteDHCPNetwork(id, addr) {
  12564. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12565. try {
  12566. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12567. if (res.ok) {
  12568. showToast('Deleted', `Network ${addr} removed`, 'success');
  12569. loadDHCPServer(false);
  12570. fetchData(false);
  12571. }
  12572. } catch (err) {
  12573. showToast('Error', err.message, 'error');
  12574. }
  12575. }
  12576. // ==================== MODALS & ACTIONS: LEASES ====================
  12577. function openAddDHCPStaticLeaseModal() {
  12578. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12579. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12580. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12581. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12582. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12583. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12584. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12585. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12586. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12587. }
  12588. function closeDHCPStaticLeaseModal() {
  12589. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12590. }
  12591. async function submitSaveDHCPStaticLease(e) {
  12592. e.preventDefault();
  12593. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12594. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12595. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12596. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12597. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12598. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12599. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12600. try {
  12601. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12602. method: 'POST',
  12603. headers: { 'Content-Type': 'application/json' },
  12604. body: JSON.stringify({
  12605. id,
  12606. mac_address: mac,
  12607. address: ip,
  12608. hostname,
  12609. server,
  12610. comment,
  12611. disabled
  12612. })
  12613. });
  12614. if (res.ok) {
  12615. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12616. closeDHCPStaticLeaseModal();
  12617. loadDHCPServer(false);
  12618. fetchData(false);
  12619. } else {
  12620. const err = await res.text();
  12621. showToast('Error', err, 'error');
  12622. }
  12623. } catch (err) {
  12624. showToast('Error', err.message, 'error');
  12625. }
  12626. }
  12627. async function deleteDHCPStaticLease(id) {
  12628. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12629. try {
  12630. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12631. if (res.ok) {
  12632. showToast('Deleted', 'Static lease removed', 'success');
  12633. loadDHCPServer(false);
  12634. fetchData(false);
  12635. }
  12636. } catch (err) {
  12637. showToast('Error', err.message, 'error');
  12638. }
  12639. }
  12640. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12641. try {
  12642. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12643. method: 'POST',
  12644. headers: { 'Content-Type': 'application/json' },
  12645. body: JSON.stringify({
  12646. mac_address: mac,
  12647. address: ip,
  12648. hostname,
  12649. comment: comment || 'Converted to static'
  12650. })
  12651. });
  12652. if (res.ok) {
  12653. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12654. loadDHCPServer(false);
  12655. fetchData(false);
  12656. } else {
  12657. const err = await res.text();
  12658. showToast('Error', err, 'error');
  12659. }
  12660. } catch (err) {
  12661. showToast('Error', err.message, 'error');
  12662. }
  12663. }
  12664. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12665. function openAddDHCPOptionModal() {
  12666. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12667. document.getElementById('dhcp-option-modal-id').value = '';
  12668. document.getElementById('dhcp-option-modal-name').value = '';
  12669. document.getElementById('dhcp-option-modal-code').value = '';
  12670. document.getElementById('dhcp-option-modal-value').value = '';
  12671. document.getElementById('dhcp-option-modal-comment').value = '';
  12672. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12673. }
  12674. function openEditDHCPOptionModal(id) {
  12675. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12676. if (!o) return;
  12677. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12678. document.getElementById('dhcp-option-modal-id').value = o.id;
  12679. document.getElementById('dhcp-option-modal-name').value = o.name;
  12680. document.getElementById('dhcp-option-modal-code').value = o.code;
  12681. document.getElementById('dhcp-option-modal-value').value = o.value;
  12682. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12683. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12684. }
  12685. function closeDHCPOptionModal() {
  12686. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12687. }
  12688. async function submitSaveDHCPOption(e) {
  12689. e.preventDefault();
  12690. const id = document.getElementById('dhcp-option-modal-id').value;
  12691. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12692. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12693. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12694. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12695. try {
  12696. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12697. method: 'POST',
  12698. headers: { 'Content-Type': 'application/json' },
  12699. body: JSON.stringify({ id, name, code, value, comment })
  12700. });
  12701. if (res.ok) {
  12702. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12703. closeDHCPOptionModal();
  12704. loadDHCPServer(false);
  12705. fetchData(false);
  12706. } else {
  12707. const err = await res.text();
  12708. showToast('Error', err, 'error');
  12709. }
  12710. } catch (err) {
  12711. showToast('Error', err.message, 'error');
  12712. }
  12713. }
  12714. async function deleteDHCPOption(id, name) {
  12715. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12716. try {
  12717. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12718. if (res.ok) {
  12719. showToast('Deleted', `Option ${name} removed`, 'success');
  12720. loadDHCPServer(false);
  12721. fetchData(false);
  12722. }
  12723. } catch (err) {
  12724. showToast('Error', err.message, 'error');
  12725. }
  12726. }
  12727. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12728. function openDHCPServerSetupModal() {
  12729. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12730. onDHCPWizardIfaceChange();
  12731. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12732. }
  12733. function closeDHCPServerSetupModal() {
  12734. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12735. }
  12736. function onDHCPWizardIfaceChange() {
  12737. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12738. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12739. let ip = '192.168.88.1';
  12740. let prefix = '24';
  12741. if (iface && iface.ip_address) {
  12742. const parts = iface.ip_address.split('/');
  12743. ip = parts[0];
  12744. if (parts.length > 1) prefix = parts[1];
  12745. }
  12746. // Calculate subnet base (e.g. 192.168.88.0/24)
  12747. const ipParts = ip.split('.');
  12748. if (ipParts.length === 4) {
  12749. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12750. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12751. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12752. document.getElementById('dhcp-wizard-gateway').value = ip;
  12753. document.getElementById('dhcp-wizard-pool').value = pool;
  12754. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12755. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12756. }
  12757. }
  12758. async function submitDHCPServerSetupWizard(e) {
  12759. e.preventDefault();
  12760. const iface = document.getElementById('dhcp-wizard-iface').value;
  12761. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12762. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12763. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12764. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12765. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12766. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12767. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12768. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12769. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12770. try {
  12771. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12772. method: 'POST',
  12773. headers: { 'Content-Type': 'application/json' },
  12774. body: JSON.stringify({
  12775. interface: iface,
  12776. address_space: space,
  12777. gateway: gw,
  12778. address_pool: pool,
  12779. dns_servers: dnsServers,
  12780. lease_time: leaseTime,
  12781. ntp_servers: ntpServers,
  12782. next_server: tftp
  12783. })
  12784. });
  12785. if (res.ok) {
  12786. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12787. closeDHCPServerSetupModal();
  12788. loadDHCPServer(false);
  12789. fetchData(false);
  12790. } else {
  12791. const err = await res.text();
  12792. showToast('Error', err, 'error');
  12793. }
  12794. } catch (err) {
  12795. showToast('Error', err.message, 'error');
  12796. }
  12797. }
  12798. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12799. const sel = document.getElementById(elemId);
  12800. if (!sel) return;
  12801. sel.innerHTML = '<option value="">Select interface...</option>';
  12802. const ifaces = state.interfaces || [];
  12803. ifaces.forEach(i => {
  12804. if (i.name === 'lo') return;
  12805. const opt = document.createElement('option');
  12806. opt.value = i.name;
  12807. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12808. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12809. if (i.name === selectedVal) opt.selected = true;
  12810. sel.appendChild(opt);
  12811. });
  12812. }
  12813. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12814. function initTableSorting() {
  12815. document.querySelectorAll('table').forEach(setupSortableTable);
  12816. }
  12817. function setupSortableTable(table) {
  12818. const thead = table.querySelector('thead');
  12819. const tbody = table.querySelector('tbody');
  12820. if (!thead || !tbody) return;
  12821. const headerRows = thead.querySelectorAll('tr');
  12822. if (headerRows.length === 0) return;
  12823. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12824. ths.forEach((th, colIdx) => {
  12825. if (th._sortBound) return;
  12826. th._sortBound = true;
  12827. const rawText = th.innerText.trim().toLowerCase();
  12828. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12829. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12830. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12831. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12832. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12833. return;
  12834. }
  12835. th.classList.add('table-sortable', 'group');
  12836. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12837. let icon = th.querySelector('.table-sort-icon');
  12838. if (!icon) {
  12839. icon = document.createElement('span');
  12840. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12841. icon.innerHTML = '⇅';
  12842. th.appendChild(icon);
  12843. }
  12844. th.addEventListener('click', (e) => {
  12845. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12846. handleHeaderClick(table, th, colIdx);
  12847. });
  12848. });
  12849. if (!tbody._sortObserved) {
  12850. tbody._sortObserved = true;
  12851. let sortDebounceTimer = null;
  12852. const observer = new MutationObserver((mutations) => {
  12853. if (tbody._isSorting) return;
  12854. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12855. if (!hasChildChanges) return;
  12856. clearTimeout(sortDebounceTimer);
  12857. sortDebounceTimer = setTimeout(() => {
  12858. if (tbody._isSorting) return;
  12859. if (table._activeSort && table._activeSort.dir !== 'none') {
  12860. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12861. } else {
  12862. tagOriginalRowOrder(tbody);
  12863. }
  12864. }, 50);
  12865. });
  12866. tbody._sortObserver = observer;
  12867. observer.observe(tbody, { childList: true });
  12868. }
  12869. tagOriginalRowOrder(tbody);
  12870. }
  12871. function tagOriginalRowOrder(tbody) {
  12872. let idx = 0;
  12873. Array.from(tbody.children).forEach(tr => {
  12874. if (!tr.querySelector('td[colspan]')) {
  12875. if (!tr.hasAttribute('data-orig-idx')) {
  12876. tr.setAttribute('data-orig-idx', idx++);
  12877. }
  12878. }
  12879. });
  12880. }
  12881. function handleHeaderClick(table, th, colIdx) {
  12882. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12883. let newDir = 'asc';
  12884. if (currentSort.colIdx === colIdx) {
  12885. if (currentSort.dir === 'asc') newDir = 'desc';
  12886. else if (currentSort.dir === 'desc') newDir = 'none';
  12887. else newDir = 'asc';
  12888. } else {
  12889. newDir = 'asc';
  12890. }
  12891. table._activeSort = { colIdx, dir: newDir };
  12892. updateHeaderIcons(table, colIdx, newDir);
  12893. applyTableSort(table, colIdx, newDir, true);
  12894. }
  12895. function updateHeaderIcons(table, activeColIdx, dir) {
  12896. const thead = table.querySelector('thead');
  12897. if (!thead) return;
  12898. const ths = thead.querySelectorAll('th');
  12899. ths.forEach((th, idx) => {
  12900. const icon = th.querySelector('.table-sort-icon');
  12901. if (!icon) return;
  12902. if (idx === activeColIdx && dir !== 'none') {
  12903. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12904. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12905. th.classList.add('table-sorted-active');
  12906. } else {
  12907. icon.innerHTML = '⇅';
  12908. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12909. th.classList.remove('table-sorted-active');
  12910. }
  12911. });
  12912. }
  12913. function applyTableSort(table, colIdx, dir, userInitiated) {
  12914. const tbody = table.querySelector('tbody');
  12915. if (!tbody || tbody.children.length <= 1) return;
  12916. tbody._isSorting = true;
  12917. tagOriginalRowOrder(tbody);
  12918. // Group parent rows and any attached drawer/sub-rows
  12919. const groups = [];
  12920. let currentGroup = null;
  12921. Array.from(tbody.children).forEach(tr => {
  12922. if (tr.querySelector('td[colspan]')) {
  12923. if (currentGroup) {
  12924. currentGroup.subRows.push(tr);
  12925. } else {
  12926. groups.push({ mainRow: tr, subRows: [] });
  12927. }
  12928. } else {
  12929. currentGroup = { mainRow: tr, subRows: [] };
  12930. groups.push(currentGroup);
  12931. }
  12932. });
  12933. if (dir === 'none') {
  12934. groups.sort((a, b) => {
  12935. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12936. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12937. return idxA - idxB;
  12938. });
  12939. } else {
  12940. groups.sort((a, b) => {
  12941. const cellA = a.mainRow.children[colIdx];
  12942. const cellB = b.mainRow.children[colIdx];
  12943. const res = compareTableCells(cellA, cellB);
  12944. return dir === 'asc' ? res : -res;
  12945. });
  12946. }
  12947. // Check if rows are already in correct order to avoid modifying DOM
  12948. let alreadyOrdered = true;
  12949. let childIdx = 0;
  12950. for (const g of groups) {
  12951. if (tbody.children[childIdx] !== g.mainRow) {
  12952. alreadyOrdered = false;
  12953. break;
  12954. }
  12955. childIdx++;
  12956. for (const sub of g.subRows) {
  12957. if (tbody.children[childIdx] !== sub) {
  12958. alreadyOrdered = false;
  12959. break;
  12960. }
  12961. childIdx++;
  12962. }
  12963. }
  12964. if (alreadyOrdered) {
  12965. tbody._isSorting = false;
  12966. return;
  12967. }
  12968. // Disconnect observer while re-ordering to prevent recursion and thrashing
  12969. if (tbody._sortObserver) {
  12970. tbody._sortObserver.disconnect();
  12971. }
  12972. // Re-append rows in sorted order
  12973. groups.forEach(g => {
  12974. tbody.appendChild(g.mainRow);
  12975. g.subRows.forEach(sub => tbody.appendChild(sub));
  12976. });
  12977. // Drain any queued mutations and re-connect observer
  12978. if (tbody._sortObserver) {
  12979. tbody._sortObserver.takeRecords();
  12980. tbody._sortObserver.observe(tbody, { childList: true });
  12981. }
  12982. tbody._isSorting = false;
  12983. }
  12984. function getCellRawText(cell) {
  12985. if (!cell) return '';
  12986. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12987. const input = cell.querySelector('input, select');
  12988. if (input) {
  12989. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12990. return input.value;
  12991. }
  12992. return cell.innerText.trim();
  12993. }
  12994. function parseTrafficToNumber(str) {
  12995. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12996. if (!m) return null;
  12997. const num = parseFloat(m[1].replace(/,/g, ''));
  12998. if (isNaN(num)) return null;
  12999. const unit = m[2].toUpperCase();
  13000. let mult = 1;
  13001. if (unit.startsWith('K')) mult = 1024;
  13002. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13003. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13004. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13005. return num * mult;
  13006. }
  13007. function parseIpToNumber(str) {
  13008. const clean = str.replace(/^[!~]/, '').trim();
  13009. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13010. if (!m) return null;
  13011. const o1 = parseInt(m[1], 10);
  13012. const o2 = parseInt(m[2], 10);
  13013. const o3 = parseInt(m[3], 10);
  13014. const o4 = parseInt(m[4], 10);
  13015. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13016. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13017. }
  13018. function parseCompoundPackets(str) {
  13019. const m = str.match(/^([\d,]+)p/);
  13020. if (!m) return null;
  13021. return parseInt(m[1].replace(/,/g, ''), 10);
  13022. }
  13023. function compareTableCells(cellA, cellB) {
  13024. const a = getCellRawText(cellA);
  13025. const b = getCellRawText(cellB);
  13026. if (a === '' && b !== '') return 1;
  13027. if (b === '' && a !== '') return -1;
  13028. if (a === b) return 0;
  13029. // 1. IP Addresses / CIDR
  13030. const ipA = parseIpToNumber(a);
  13031. const ipB = parseIpToNumber(b);
  13032. if (ipA !== null && ipB !== null) return ipA - ipB;
  13033. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13034. const pktA = parseCompoundPackets(a);
  13035. const pktB = parseCompoundPackets(b);
  13036. if (pktA !== null && pktB !== null) return pktA - pktB;
  13037. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13038. const trafA = parseTrafficToNumber(a);
  13039. const trafB = parseTrafficToNumber(b);
  13040. if (trafA !== null && trafB !== null) return trafA - trafB;
  13041. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13042. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13043. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13044. const numA = Number(cleanNumA);
  13045. const numB = Number(cleanNumB);
  13046. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13047. return numA - numB;
  13048. }
  13049. // 5. Natural case-insensitive string compare
  13050. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13051. }
  13052. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13053. async function loadVRRP(showToastNotification = false) {
  13054. try {
  13055. const [instRes, sumRes] = await Promise.all([
  13056. fetch(`${API_BASE}/vrrp/instances`),
  13057. fetch(`${API_BASE}/vrrp/summary`)
  13058. ]);
  13059. if (instRes.ok) {
  13060. state.vrrpInstances = await instRes.json();
  13061. renderVRRP();
  13062. }
  13063. if (sumRes.ok) {
  13064. state.vrrpSummary = await sumRes.json();
  13065. renderVRRPSummary();
  13066. }
  13067. if (showToastNotification) {
  13068. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13069. }
  13070. } catch (err) {
  13071. console.error('Failed to load VRRP:', err);
  13072. }
  13073. }
  13074. function renderVRRPSummary() {
  13075. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13076. const elTotal = document.getElementById('vrrp-stat-total');
  13077. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13078. const elMaster = document.getElementById('vrrp-stat-master');
  13079. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13080. const elBackup = document.getElementById('vrrp-stat-backup');
  13081. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13082. const bCount = document.getElementById('badge-vrrp-count');
  13083. if (bCount) bCount.innerText = s.total_instances || 0;
  13084. const dot = document.getElementById('badge-vrrp-dot');
  13085. if (dot) {
  13086. if (s.master_instances > 0) {
  13087. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13088. } else if (s.backup_instances > 0) {
  13089. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13090. } else {
  13091. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13092. }
  13093. }
  13094. }
  13095. function renderVRRP() {
  13096. const tbody = document.getElementById('vrrp-table-tbody');
  13097. const empty = document.getElementById('vrrp-table-empty');
  13098. if (!tbody) return;
  13099. tbody.innerHTML = '';
  13100. const instances = state.vrrpInstances || [];
  13101. if (instances.length === 0) {
  13102. empty?.classList.remove('hidden');
  13103. return;
  13104. }
  13105. empty?.classList.add('hidden');
  13106. instances.forEach(inst => {
  13107. const tr = document.createElement('tr');
  13108. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13109. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13110. 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>`;
  13111. if (inst.disabled) {
  13112. 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>`;
  13113. } else if (inst.state === 'MASTER') {
  13114. 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>`;
  13115. } else if (inst.state === 'BACKUP') {
  13116. 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>`;
  13117. } else if (inst.state === 'FAULT') {
  13118. 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>`;
  13119. }
  13120. // Render State Badge
  13121. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13122. if (!inst.disabled) {
  13123. if (inst.state === 'MASTER') {
  13124. 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>`;
  13125. } else if (inst.state === 'BACKUP') {
  13126. 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>`;
  13127. } else if (inst.state === 'FAULT') {
  13128. 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>`;
  13129. }
  13130. }
  13131. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13132. tr.innerHTML = `
  13133. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13134. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13135. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13136. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13137. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13138. <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>
  13139. <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>
  13140. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13141. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13142. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13143. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13144. <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>
  13145. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13146. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13147. </td>
  13148. `;
  13149. tbody.appendChild(tr);
  13150. });
  13151. }
  13152. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13153. const sel = document.getElementById(elemId);
  13154. if (!sel) return;
  13155. sel.innerHTML = '<option value="">Select interface...</option>';
  13156. const ifaces = state.interfaces || [];
  13157. ifaces.forEach(i => {
  13158. const opt = document.createElement('option');
  13159. opt.value = i.name;
  13160. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13161. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13162. sel.appendChild(opt);
  13163. });
  13164. }
  13165. function openAddVRRPModal() {
  13166. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13167. document.getElementById('modal-vrrp-id').value = '';
  13168. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13169. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13170. document.getElementById('modal-vrrp-priority').value = 100;
  13171. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13172. document.getElementById('modal-vrrp-version').value = '3';
  13173. document.getElementById('modal-vrrp-interval').value = 1;
  13174. document.getElementById('modal-vrrp-authtype').value = 'none';
  13175. document.getElementById('modal-vrrp-authpass').value = '';
  13176. document.getElementById('modal-vrrp-comment').value = '';
  13177. document.getElementById('modal-vrrp-preempt').checked = true;
  13178. document.getElementById('modal-vrrp-disabled').checked = false;
  13179. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13180. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13181. }
  13182. function openEditVRRPModal(id) {
  13183. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13184. if (!inst) return;
  13185. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13186. document.getElementById('modal-vrrp-id').value = inst.id;
  13187. document.getElementById('modal-vrrp-name').value = inst.name;
  13188. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13189. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13190. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13191. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13192. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13193. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13194. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13195. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13196. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13197. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13198. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13199. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13200. }
  13201. function closeVRRPModal() {
  13202. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13203. }
  13204. async function submitSaveVRRP(e) {
  13205. e.preventDefault();
  13206. const id = document.getElementById('modal-vrrp-id').value;
  13207. const name = document.getElementById('modal-vrrp-name').value.trim();
  13208. const iface = document.getElementById('modal-vrrp-iface').value;
  13209. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13210. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13211. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13212. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13213. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13214. const authType = document.getElementById('modal-vrrp-authtype').value;
  13215. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13216. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13217. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13218. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13219. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13220. try {
  13221. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13222. method: 'POST',
  13223. headers: { 'Content-Type': 'application/json' },
  13224. body: JSON.stringify({
  13225. id,
  13226. name,
  13227. interface: iface,
  13228. vrid,
  13229. priority,
  13230. virtual_ips: vips,
  13231. version,
  13232. interval,
  13233. auth_type: authType,
  13234. auth_password: authPass,
  13235. comment,
  13236. preempt,
  13237. disabled
  13238. })
  13239. });
  13240. if (res.ok) {
  13241. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13242. closeVRRPModal();
  13243. loadVRRP(false);
  13244. fetchData(false);
  13245. } else {
  13246. const err = await res.text();
  13247. showToast('Error', err, 'error');
  13248. }
  13249. } catch (err) {
  13250. showToast('Error', err.message, 'error');
  13251. }
  13252. }
  13253. async function deleteVRRP(id, name) {
  13254. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13255. try {
  13256. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13257. if (res.ok) {
  13258. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13259. loadVRRP(false);
  13260. fetchData(false);
  13261. } else {
  13262. const err = await res.text();
  13263. showToast('Error', err, 'error');
  13264. }
  13265. } catch (err) {
  13266. showToast('Error', err.message, 'error');
  13267. }
  13268. }
  13269. async function toggleVRRPState(id, disabled) {
  13270. try {
  13271. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13272. method: 'POST',
  13273. headers: { 'Content-Type': 'application/json' },
  13274. body: JSON.stringify({ disabled })
  13275. });
  13276. if (res.ok) {
  13277. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13278. loadVRRP(false);
  13279. fetchData(false);
  13280. } else {
  13281. const err = await res.text();
  13282. showToast('Error', err, 'error');
  13283. }
  13284. } catch (err) {
  13285. showToast('Error', err.message, 'error');
  13286. }
  13287. }
  13288. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13289. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13290. let docSortDebounce = null;
  13291. const docTableObserver = new MutationObserver((mutations) => {
  13292. let needsInit = false;
  13293. for (const m of mutations) {
  13294. for (const node of m.addedNodes) {
  13295. if (node.nodeType === 1) {
  13296. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13297. needsInit = true;
  13298. break;
  13299. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13300. needsInit = true;
  13301. break;
  13302. }
  13303. }
  13304. }
  13305. if (needsInit) break;
  13306. }
  13307. if (needsInit) {
  13308. clearTimeout(docSortDebounce);
  13309. docSortDebounce = setTimeout(initTableSorting, 100);
  13310. }
  13311. });
  13312. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13313. }
  13314. // =========================================================================
  13315. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13316. // =========================================================================
  13317. const bwtestState = {
  13318. running: false,
  13319. pollTimer: null,
  13320. eventSource: null,
  13321. chartPoints: [],
  13322. maxChartPoints: 60,
  13323. serverConfig: null,
  13324. peakTx: 0,
  13325. peakRx: 0,
  13326. targetDuration: 10,
  13327. lastSampleIndex: 0
  13328. };
  13329. async function loadBwTestView() {
  13330. fetchBwTestServerStatus();
  13331. loadBwTestHistory();
  13332. resizeBwTestCanvas();
  13333. checkActiveBwTest();
  13334. }
  13335. async function fetchBwTestServerStatus() {
  13336. try {
  13337. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13338. if (!res.ok) return;
  13339. const s = await res.json();
  13340. bwtestState.serverConfig = s;
  13341. // Update indicator and badges
  13342. const indicator = document.getElementById('bwtest-server-indicator');
  13343. const badge = document.getElementById('bwtest-server-badge');
  13344. const sideBadge = document.getElementById('badge-bwtest-server');
  13345. if (s.enabled && s.running) {
  13346. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13347. if (badge) {
  13348. badge.innerText = `Port ${s.port} (Active)`;
  13349. badge.className = 'text-emerald-400 font-bold';
  13350. }
  13351. if (sideBadge) {
  13352. sideBadge.innerText = s.port;
  13353. 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';
  13354. }
  13355. } else {
  13356. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13357. if (badge) {
  13358. badge.innerText = `Disabled`;
  13359. badge.className = 'text-slate-500 font-bold';
  13360. }
  13361. if (sideBadge) {
  13362. sideBadge.innerText = 'Off';
  13363. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13364. }
  13365. }
  13366. // Modal fields
  13367. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13368. if (toggle) toggle.checked = !!s.enabled;
  13369. const portInp = document.getElementById('bwtest-server-port-input');
  13370. if (portInp) portInp.value = s.port || 2000;
  13371. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13372. if (actSess) actSess.innerText = s.active_sessions || 0;
  13373. const totServ = document.getElementById('bwtest-modal-total-served');
  13374. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13375. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13376. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13377. } catch (err) {
  13378. console.error('Failed to fetch BwTest server status:', err);
  13379. }
  13380. }
  13381. function openBwTestServerModal() {
  13382. fetchBwTestServerStatus();
  13383. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13384. }
  13385. function closeBwTestServerModal() {
  13386. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13387. }
  13388. async function submitBwTestServerSettings(e) {
  13389. e.preventDefault();
  13390. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13391. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13392. try {
  13393. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13394. method: 'POST',
  13395. headers: { 'Content-Type': 'application/json' },
  13396. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13397. });
  13398. if (!res.ok) {
  13399. const err = await res.json();
  13400. throw new Error(err.error || 'Failed to update server configuration');
  13401. }
  13402. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13403. closeBwTestServerModal();
  13404. fetchBwTestServerStatus();
  13405. } catch (err) {
  13406. showToast('Server Configuration Error', err.message, 'error');
  13407. }
  13408. }
  13409. function setBwTestTarget(target) {
  13410. const inp = document.getElementById('bwtest-input-target');
  13411. if (inp) inp.value = target;
  13412. }
  13413. function setBwTestProtocol(proto) {
  13414. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13415. if (hiddenInp) hiddenInp.value = proto;
  13416. const btnUdp = document.getElementById('bwtest-proto-udp');
  13417. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13418. const badge = document.getElementById('bwtest-proto-badge');
  13419. const pktField = document.getElementById('bwtest-field-pktsize');
  13420. 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';
  13421. 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';
  13422. 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';
  13423. if (proto === 'udp') {
  13424. if (btnUdp) {
  13425. btnUdp.className = activeUdpCls;
  13426. const dot = btnUdp.querySelector('span');
  13427. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13428. }
  13429. if (btnTcp) {
  13430. btnTcp.className = inactiveCls;
  13431. const dot = btnTcp.querySelector('span');
  13432. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13433. }
  13434. if (badge) {
  13435. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13436. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13437. }
  13438. if (pktField) pktField.classList.remove('opacity-40');
  13439. } else {
  13440. if (btnUdp) {
  13441. btnUdp.className = inactiveCls;
  13442. const dot = btnUdp.querySelector('span');
  13443. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13444. }
  13445. if (btnTcp) {
  13446. btnTcp.className = activeTcpCls;
  13447. const dot = btnTcp.querySelector('span');
  13448. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13449. }
  13450. if (badge) {
  13451. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13452. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13453. }
  13454. if (pktField) pktField.classList.add('opacity-40');
  13455. }
  13456. }
  13457. function setBwTestDirection(dir) {
  13458. const hiddenInp = document.getElementById('bwtest-input-direction');
  13459. if (hiddenInp) hiddenInp.value = dir;
  13460. const btnBoth = document.getElementById('bwtest-dir-both');
  13461. const btnTx = document.getElementById('bwtest-dir-tx');
  13462. const btnRx = document.getElementById('bwtest-dir-rx');
  13463. 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';
  13464. 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';
  13465. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13466. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13467. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13468. }
  13469. function setBwTestLimit(bps) {
  13470. const sel = document.getElementById('bwtest-input-limit');
  13471. if (sel) sel.value = String(bps);
  13472. }
  13473. async function checkActiveBwTest() {
  13474. try {
  13475. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13476. if (!res.ok) return;
  13477. const st = await res.json();
  13478. if (st.running) {
  13479. setBwTestRunningUI(true);
  13480. if (st.current_sample) handleBwTestSample(st.current_sample);
  13481. startBwTestTelemetry();
  13482. }
  13483. } catch (err) {
  13484. console.error('Failed to check active BwTest:', err);
  13485. }
  13486. }
  13487. async function startBwTest(e) {
  13488. if (e && e.preventDefault) e.preventDefault();
  13489. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13490. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13491. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13492. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13493. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13494. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13495. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13496. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13497. bwtestState.targetDuration = duration;
  13498. bwtestState.chartPoints = [];
  13499. bwtestState.peakTx = 0;
  13500. bwtestState.peakRx = 0;
  13501. bwtestState.lastSampleIndex = 0;
  13502. // Clear UI elements
  13503. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13504. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13505. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13506. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13507. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13508. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13509. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13510. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13511. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13512. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13513. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13514. const tbody = document.getElementById('bwtest-samples-tbody');
  13515. if (tbody) tbody.innerHTML = '';
  13516. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13517. setBwTestRunningUI(true);
  13518. try {
  13519. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13520. method: 'POST',
  13521. headers: { 'Content-Type': 'application/json' },
  13522. body: JSON.stringify({
  13523. target,
  13524. port,
  13525. direction,
  13526. protocol,
  13527. bandwidth_limit,
  13528. packet_size,
  13529. streams,
  13530. duration
  13531. })
  13532. });
  13533. if (!res.ok) {
  13534. const err = await res.json();
  13535. throw new Error(err.error || 'Failed to start bandwidth test');
  13536. }
  13537. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13538. startBwTestTelemetry();
  13539. } catch (err) {
  13540. setBwTestRunningUI(false);
  13541. showToast('Start Failed', err.message, 'error');
  13542. }
  13543. }
  13544. function setBwTestRunningUI(running) {
  13545. bwtestState.running = running;
  13546. const startBtn = document.getElementById('bwtest-btn-start');
  13547. const stopBtn = document.getElementById('bwtest-btn-stop');
  13548. const badge = document.getElementById('bwtest-run-status-badge');
  13549. const ph = document.getElementById('bwtest-chart-placeholder');
  13550. if (running) {
  13551. if (startBtn) {
  13552. startBtn.disabled = true;
  13553. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13554. }
  13555. if (stopBtn) {
  13556. stopBtn.disabled = false;
  13557. stopBtn.classList.remove('opacity-40');
  13558. }
  13559. if (badge) {
  13560. badge.innerText = 'TESTING...';
  13561. 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';
  13562. }
  13563. if (ph) ph.style.display = 'none';
  13564. } else {
  13565. if (startBtn) {
  13566. startBtn.disabled = false;
  13567. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13568. }
  13569. if (stopBtn) {
  13570. stopBtn.disabled = true;
  13571. stopBtn.classList.add('opacity-40');
  13572. }
  13573. if (badge) {
  13574. badge.innerText = 'IDLE';
  13575. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13576. }
  13577. }
  13578. }
  13579. async function stopBwTest() {
  13580. try {
  13581. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13582. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13583. } catch (err) {
  13584. console.error('Failed to stop test:', err);
  13585. }
  13586. }
  13587. function startBwTestTelemetry() {
  13588. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13589. bwtestState.pollTimer = setInterval(async () => {
  13590. try {
  13591. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13592. if (!res.ok) return;
  13593. const st = await res.json();
  13594. if (st.recent_samples && st.recent_samples.length > 0) {
  13595. // Process new samples
  13596. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13597. newSamples.forEach(s => handleBwTestSample(s));
  13598. bwtestState.lastSampleIndex = st.recent_samples.length;
  13599. }
  13600. if (!st.running) {
  13601. clearInterval(bwtestState.pollTimer);
  13602. bwtestState.pollTimer = null;
  13603. setBwTestRunningUI(false);
  13604. handleBwTestFinish(st.summary, st.error);
  13605. }
  13606. } catch (err) {
  13607. console.error('BwTest polling error:', err);
  13608. }
  13609. }, 400);
  13610. }
  13611. function handleBwTestSample(s) {
  13612. if (!s) return;
  13613. const txMbps = s.tx_mbps || 0;
  13614. const rxMbps = s.rx_mbps || 0;
  13615. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13616. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13617. // KPI updates
  13618. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13619. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13620. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13621. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13622. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13623. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13624. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13625. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13626. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13627. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13628. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13629. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13630. const elLoss = document.getElementById('bwtest-stat-loss');
  13631. if (elLoss) {
  13632. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13633. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13634. }
  13635. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13636. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13637. const elJitter = document.getElementById('bwtest-stat-jitter');
  13638. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13639. const elTime = document.getElementById('bwtest-stat-time');
  13640. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13641. const elData = document.getElementById('bwtest-stat-data');
  13642. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13643. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13644. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13645. // Append point to chart buffer
  13646. bwtestState.chartPoints.push({
  13647. elapsed: s.elapsed_sec || 0,
  13648. tx: txMbps,
  13649. rx: rxMbps
  13650. });
  13651. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13652. bwtestState.chartPoints.shift();
  13653. }
  13654. drawBwTestChart();
  13655. // Add row to breakdown table
  13656. const tbody = document.getElementById('bwtest-samples-tbody');
  13657. if (tbody) {
  13658. const tr = document.createElement('tr');
  13659. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13660. tr.innerHTML = `
  13661. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13662. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13663. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13664. <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>
  13665. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13666. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13667. `;
  13668. tbody.insertBefore(tr, tbody.firstChild);
  13669. const countEl = document.getElementById('bwtest-sample-count');
  13670. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13671. }
  13672. }
  13673. function handleBwTestFinish(summary, error) {
  13674. const badge = document.getElementById('bwtest-run-status-badge');
  13675. if (error) {
  13676. showToast('Benchmark Error', error, 'error');
  13677. if (badge) {
  13678. badge.innerText = 'ERROR';
  13679. 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';
  13680. }
  13681. } else if (summary) {
  13682. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13683. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13684. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13685. if (badge) {
  13686. badge.innerText = 'COMPLETED';
  13687. 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';
  13688. }
  13689. }
  13690. loadBwTestHistory();
  13691. fetchBwTestServerStatus();
  13692. }
  13693. function resizeBwTestCanvas() {
  13694. const canvas = document.getElementById('bwtest-chart');
  13695. if (!canvas || !canvas.parentElement) return;
  13696. const rect = canvas.parentElement.getBoundingClientRect();
  13697. const dpr = window.devicePixelRatio || 1;
  13698. canvas.width = rect.width * dpr;
  13699. canvas.height = rect.height * dpr;
  13700. const ctx = canvas.getContext('2d');
  13701. ctx.scale(dpr, dpr);
  13702. drawBwTestChart();
  13703. }
  13704. window.addEventListener('resize', () => {
  13705. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13706. });
  13707. function drawBwTestChart() {
  13708. const canvas = document.getElementById('bwtest-chart');
  13709. if (!canvas) return;
  13710. const ctx = canvas.getContext('2d');
  13711. const dpr = window.devicePixelRatio || 1;
  13712. const width = canvas.width / dpr;
  13713. const height = canvas.height / dpr;
  13714. ctx.clearRect(0, 0, width, height);
  13715. const points = bwtestState.chartPoints;
  13716. if (!points || points.length === 0) return;
  13717. // Determine scale ceiling
  13718. let maxRate = 10;
  13719. for (const p of points) {
  13720. if (p.tx > maxRate) maxRate = p.tx;
  13721. if (p.rx > maxRate) maxRate = p.rx;
  13722. }
  13723. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13724. const paddingLeft = 55;
  13725. const paddingBottom = 24;
  13726. const paddingTop = 12;
  13727. const paddingRight = 16;
  13728. const chartW = width - paddingLeft - paddingRight;
  13729. const chartH = height - paddingTop - paddingBottom;
  13730. // Grid Lines and Y-Axis labels
  13731. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13732. ctx.lineWidth = 1;
  13733. ctx.fillStyle = '#94a3b8';
  13734. ctx.font = '10px monospace';
  13735. ctx.textAlign = 'right';
  13736. const gridSteps = 4;
  13737. for (let i = 0; i <= gridSteps; i++) {
  13738. const val = (maxRate / gridSteps) * i;
  13739. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13740. ctx.beginPath();
  13741. ctx.moveTo(paddingLeft, y);
  13742. ctx.lineTo(width - paddingRight, y);
  13743. ctx.stroke();
  13744. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13745. }
  13746. // Draw TX Line (Cyan #22d3ee)
  13747. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13748. // Draw RX Line (Purple #a855f7)
  13749. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13750. }
  13751. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13752. if (points.length < 2) return;
  13753. const stepX = w / Math.max(points.length - 1, 1);
  13754. // Gradient area fill
  13755. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13756. grad.addColorStop(0, fillColor);
  13757. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13758. ctx.beginPath();
  13759. points.forEach((p, idx) => {
  13760. const x = left + idx * stepX;
  13761. const val = valFn(p);
  13762. const y = top + h - (val / maxVal) * h;
  13763. if (idx === 0) {
  13764. ctx.moveTo(x, y);
  13765. } else {
  13766. ctx.lineTo(x, y);
  13767. }
  13768. });
  13769. // Complete path for fill
  13770. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13771. ctx.lineTo(left, top + h);
  13772. ctx.closePath();
  13773. ctx.fillStyle = grad;
  13774. ctx.fill();
  13775. // Draw line stroke
  13776. ctx.beginPath();
  13777. ctx.lineWidth = 2.5;
  13778. ctx.strokeStyle = strokeColor;
  13779. points.forEach((p, idx) => {
  13780. const x = left + idx * stepX;
  13781. const val = valFn(p);
  13782. const y = top + h - (val / maxVal) * h;
  13783. if (idx === 0) {
  13784. ctx.moveTo(x, y);
  13785. } else {
  13786. ctx.lineTo(x, y);
  13787. }
  13788. });
  13789. ctx.stroke();
  13790. // Draw end point halo
  13791. const lastP = points[points.length - 1];
  13792. const lastX = left + (points.length - 1) * stepX;
  13793. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13794. ctx.fillStyle = strokeColor;
  13795. ctx.beginPath();
  13796. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13797. ctx.fill();
  13798. }
  13799. async function loadBwTestHistory() {
  13800. try {
  13801. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13802. if (!res.ok) return;
  13803. const list = await res.json();
  13804. renderBwTestHistory(Array.isArray(list) ? list : []);
  13805. } catch (err) {
  13806. console.error('Failed to load BwTest history:', err);
  13807. }
  13808. }
  13809. function renderBwTestHistory(list) {
  13810. const tbody = document.getElementById('bwtest-history-tbody');
  13811. if (!tbody) return;
  13812. if (list.length === 0) {
  13813. 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>`;
  13814. return;
  13815. }
  13816. tbody.innerHTML = '';
  13817. list.forEach(item => {
  13818. const s = item.summary || {};
  13819. const tr = document.createElement('tr');
  13820. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13821. const dirBadge = item.direction === 'both'
  13822. ? `<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>`
  13823. : item.direction === 'tx'
  13824. ? `<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>`
  13825. : `<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>`;
  13826. const protoBadge = item.protocol === 'tcp'
  13827. ? `<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>`
  13828. : `<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>`;
  13829. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13830. tr.innerHTML = `
  13831. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13832. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13833. <td class="py-2.5 px-4">${protoBadge}</td>
  13834. <td class="py-2.5 px-4">${dirBadge}</td>
  13835. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13836. <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>
  13837. <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>
  13838. <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>
  13839. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13840. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13841. `;
  13842. tbody.appendChild(tr);
  13843. });
  13844. }
  13845. // ======================== SETTINGS & ROUTER DNS ========================
  13846. state.settingsSubTab = 'dns';
  13847. state.dnsSettings = null;
  13848. state.dnsStaticRecords = [];
  13849. state.dnsStatus = null;
  13850. function switchSettingsSubTab(sub) {
  13851. state.settingsSubTab = sub;
  13852. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13853. const btnSys = document.getElementById('btn-settings-subtab-system');
  13854. const tabDns = document.getElementById('settings-subtab-dns');
  13855. const tabSys = document.getElementById('settings-subtab-system');
  13856. if (sub === 'dns') {
  13857. if (btnDns) {
  13858. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13859. }
  13860. if (btnSys) {
  13861. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13862. }
  13863. tabDns?.classList.remove('hidden');
  13864. tabSys?.classList.add('hidden');
  13865. loadDNSSettings();
  13866. } else {
  13867. if (btnSys) {
  13868. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13869. }
  13870. if (btnDns) {
  13871. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13872. }
  13873. tabSys?.classList.remove('hidden');
  13874. tabDns?.classList.add('hidden');
  13875. loadSystemSettings();
  13876. }
  13877. }
  13878. async function loadSettingsData(showLoading = false) {
  13879. if (state.settingsSubTab === 'system') {
  13880. await loadSystemSettings();
  13881. } else {
  13882. await loadDNSSettings();
  13883. }
  13884. }
  13885. async function loadDNSSettings() {
  13886. try {
  13887. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13888. fetch(`${API_BASE}/dns/settings`),
  13889. fetch(`${API_BASE}/dns/static`),
  13890. fetch(`${API_BASE}/dns/status`)
  13891. ]);
  13892. if (settingsRes.ok) {
  13893. state.dnsSettings = await settingsRes.json();
  13894. populateDNSSettingsForm(state.dnsSettings);
  13895. }
  13896. if (staticRes.ok) {
  13897. state.dnsStaticRecords = await staticRes.json();
  13898. renderStaticDNSList();
  13899. }
  13900. if (statusRes.ok) {
  13901. state.dnsStatus = await statusRes.json();
  13902. updateDNSStatusView(state.dnsStatus);
  13903. }
  13904. } catch (err) {
  13905. console.error('Failed to load DNS settings:', err);
  13906. }
  13907. }
  13908. function populateDNSSettingsForm(s) {
  13909. if (!s) return;
  13910. const dnsForm = document.getElementById('form-dns-settings');
  13911. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13912. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13913. if (dynamicEl) {
  13914. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13915. 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(' ');
  13916. } else {
  13917. dynamicEl.innerText = 'None';
  13918. }
  13919. }
  13920. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13921. if (isEditing) return;
  13922. const serversInput = document.getElementById('dns-servers-input');
  13923. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13924. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13925. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13926. const domainInput = document.getElementById('dns-domain-input');
  13927. if (domainInput) domainInput.value = s.domain || '';
  13928. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13929. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13930. }
  13931. function updateDNSStatusView(st) {
  13932. if (!st) return;
  13933. const preview = document.getElementById('dns-resolv-preview');
  13934. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13935. const pillText = document.getElementById('dns-live-status-text');
  13936. const pill = document.getElementById('dns-live-status-pill');
  13937. if (pill && pillText) {
  13938. if (st.service_running) {
  13939. 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';
  13940. pillText.innerText = 'DNS Service Active';
  13941. } else {
  13942. 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';
  13943. pillText.innerText = 'DNS Service Inactive';
  13944. }
  13945. }
  13946. }
  13947. function appendDNSPreset(preset) {
  13948. const input = document.getElementById('dns-servers-input');
  13949. if (!input) return;
  13950. const dnsForm = document.getElementById('form-dns-settings');
  13951. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13952. const current = input.value.trim();
  13953. if (!current) {
  13954. input.value = preset;
  13955. } else {
  13956. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13957. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13958. toAdd.forEach(ip => {
  13959. if (!existing.includes(ip)) existing.push(ip);
  13960. });
  13961. input.value = existing.join(', ');
  13962. }
  13963. }
  13964. async function saveDNSSettings(e) {
  13965. e.preventDefault();
  13966. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13967. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13968. if (servers.length === 0) {
  13969. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13970. return;
  13971. }
  13972. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13973. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13974. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13975. try {
  13976. const res = await fetch(`${API_BASE}/dns/settings`, {
  13977. method: 'POST',
  13978. headers: { 'Content-Type': 'application/json' },
  13979. body: JSON.stringify({
  13980. servers: servers,
  13981. cache_size: cacheSize,
  13982. domain: domain,
  13983. allow_remote_requests: allowRemote
  13984. })
  13985. });
  13986. const data = await res.json();
  13987. if (res.ok) {
  13988. const dnsForm = document.getElementById('form-dns-settings');
  13989. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13990. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13991. loadDNSSettings();
  13992. } else {
  13993. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13994. }
  13995. } catch (err) {
  13996. showToast('Error', err.message, 'error');
  13997. }
  13998. }
  13999. async function flushDNSCache() {
  14000. try {
  14001. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14002. if (res.ok) {
  14003. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14004. loadDNSSettings();
  14005. } else {
  14006. const err = await res.json();
  14007. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14008. }
  14009. } catch (err) {
  14010. showToast('Error', err.message, 'error');
  14011. }
  14012. }
  14013. function renderStaticDNSList() {
  14014. const tbody = document.getElementById('dns-static-tbody');
  14015. const empty = document.getElementById('dns-static-empty');
  14016. const badge = document.getElementById('dns-static-count-badge');
  14017. if (!tbody) return;
  14018. tbody.innerHTML = '';
  14019. const records = state.dnsStaticRecords || [];
  14020. if (badge) badge.innerText = `${records.length} Records`;
  14021. if (records.length === 0) {
  14022. empty?.classList.remove('hidden');
  14023. return;
  14024. }
  14025. empty?.classList.add('hidden');
  14026. records.forEach(rec => {
  14027. const tr = document.createElement('tr');
  14028. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14029. tr.innerHTML = `
  14030. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14031. <td class="py-2.5 px-4">
  14032. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14033. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14034. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14035. }">
  14036. ${rec.type || 'A'}
  14037. </span>
  14038. </td>
  14039. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14040. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14041. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14042. <td class="py-2.5 px-4">
  14043. <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'}">
  14044. ${rec.disabled ? 'Disabled' : 'Active'}
  14045. </span>
  14046. </td>
  14047. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14048. <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>
  14049. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14050. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14051. </td>
  14052. `;
  14053. tbody.appendChild(tr);
  14054. });
  14055. }
  14056. function openStaticDNSModal(id = null) {
  14057. const modal = document.getElementById('modal-static-dns');
  14058. const title = document.getElementById('modal-static-dns-title');
  14059. const form = document.getElementById('form-static-dns');
  14060. if (!modal || !form) return;
  14061. form.reset();
  14062. document.getElementById('modal-static-dns-id').value = '';
  14063. if (id) {
  14064. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14065. if (rec) {
  14066. if (title) title.innerText = 'Edit Static DNS Record';
  14067. document.getElementById('modal-static-dns-id').value = rec.id;
  14068. document.getElementById('modal-static-dns-name').value = rec.name;
  14069. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14070. document.getElementById('modal-static-dns-addr').value = rec.address;
  14071. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14072. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14073. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14074. }
  14075. } else {
  14076. if (title) title.innerText = 'Add Static DNS Record';
  14077. }
  14078. modal.classList.remove('hidden');
  14079. }
  14080. function closeStaticDNSModal() {
  14081. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14082. }
  14083. async function submitSaveStaticDNS(e) {
  14084. e.preventDefault();
  14085. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14086. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14087. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14088. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14089. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14090. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14091. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14092. if (!name || !address) {
  14093. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14094. return;
  14095. }
  14096. try {
  14097. const res = await fetch(`${API_BASE}/dns/static`, {
  14098. method: 'POST',
  14099. headers: { 'Content-Type': 'application/json' },
  14100. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14101. });
  14102. const data = await res.json();
  14103. if (res.ok) {
  14104. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14105. closeStaticDNSModal();
  14106. loadDNSSettings();
  14107. } else {
  14108. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14109. }
  14110. } catch (err) {
  14111. showToast('Error', err.message, 'error');
  14112. }
  14113. }
  14114. async function deleteStaticDNS(id) {
  14115. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14116. try {
  14117. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14118. if (res.ok) {
  14119. showToast('Deleted', 'Static DNS record deleted', 'success');
  14120. loadDNSSettings();
  14121. }
  14122. } catch (err) {
  14123. showToast('Error', err.message, 'error');
  14124. }
  14125. }
  14126. async function toggleStaticDNS(id, disabled) {
  14127. try {
  14128. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14129. method: 'POST',
  14130. headers: { 'Content-Type': 'application/json' },
  14131. body: JSON.stringify({ disabled })
  14132. });
  14133. if (res.ok) {
  14134. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14135. loadDNSSettings();
  14136. }
  14137. } catch (err) {
  14138. showToast('Error', err.message, 'error');
  14139. }
  14140. }
  14141. async function loadSystemSettings() {
  14142. try {
  14143. const sysForm = document.getElementById('form-system-settings');
  14144. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14145. const res = await fetch(`${API_BASE}/system/settings`);
  14146. if (res.ok) {
  14147. const data = await res.json();
  14148. if (!isEditing) {
  14149. const hostInput = document.getElementById('system-hostname-input');
  14150. if (hostInput) hostInput.value = data.hostname || '';
  14151. const tzInput = document.getElementById('system-timezone-input');
  14152. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14153. }
  14154. }
  14155. } catch (err) {
  14156. console.error('Failed to load system settings:', err);
  14157. }
  14158. }
  14159. async function saveSystemSettings(e) {
  14160. e.preventDefault();
  14161. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14162. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14163. try {
  14164. const res = await fetch(`${API_BASE}/system/settings`, {
  14165. method: 'POST',
  14166. headers: { 'Content-Type': 'application/json' },
  14167. body: JSON.stringify({ hostname, timezone })
  14168. });
  14169. const data = await res.json();
  14170. if (res.ok) {
  14171. const sysForm = document.getElementById('form-system-settings');
  14172. if (sysForm) sysForm.dataset.dirty = 'false';
  14173. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14174. const sideH = document.getElementById('side-hostname');
  14175. if (sideH) sideH.innerText = data.hostname;
  14176. } else {
  14177. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14178. }
  14179. } catch (err) {
  14180. showToast('Error', err.message, 'error');
  14181. }
  14182. }