app.js 660 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697
  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. // Expand / Collapse Handlers
  701. function toggleExpand(parentName) {
  702. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  703. if (childVlans.length === 0) {
  704. // Cannot expand an interface with no VLANs
  705. state.expandedParents.delete(parentName);
  706. return;
  707. }
  708. if (state.expandedParents.has(parentName)) {
  709. state.expandedParents.delete(parentName);
  710. } else {
  711. state.expandedParents.add(parentName);
  712. }
  713. renderInterfacesList();
  714. }
  715. function expandAllIfaces(expand) {
  716. if (expand) {
  717. (state.interfaces || []).forEach(i => {
  718. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  719. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  720. });
  721. } else {
  722. state.expandedParents.clear();
  723. }
  724. renderInterfacesList();
  725. }
  726. // =========================================================================
  727. // INTERFACE ROLE TAGS MANAGEMENT
  728. // =========================================================================
  729. const ROLE_COLORS = {
  730. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  731. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  732. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  733. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  734. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  735. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  736. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  737. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  738. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  739. };
  740. function getRoleBadge(roleName) {
  741. const name = roleName || 'LAN';
  742. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  743. const colorKey = (role?.color || 'blue').toLowerCase();
  744. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  745. 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>`;
  746. }
  747. function switchIfaceSubTab(subTab) {
  748. state.activeIfaceSubTab = subTab;
  749. const treeTab = document.getElementById('ifaces-subtab-tree');
  750. const rolesTab = document.getElementById('ifaces-subtab-roles');
  751. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  752. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  753. if (subTab === 'roles') {
  754. treeTab?.classList.add('hidden');
  755. rolesTab?.classList.remove('hidden');
  756. if (btnRoles) {
  757. 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';
  758. }
  759. if (btnTree) {
  760. 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';
  761. }
  762. loadRoles();
  763. } else {
  764. rolesTab?.classList.add('hidden');
  765. treeTab?.classList.remove('hidden');
  766. if (btnTree) {
  767. 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';
  768. }
  769. if (btnRoles) {
  770. 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';
  771. }
  772. renderInterfacesList();
  773. }
  774. }
  775. async function loadRoles() {
  776. try {
  777. const res = await fetch(`${API_BASE}/roles`);
  778. if (res.ok) {
  779. state.roles = await res.json();
  780. const countEl = document.getElementById('badge-roles-count');
  781. if (countEl) countEl.innerText = (state.roles || []).length;
  782. renderRolesTable();
  783. populateRoleSelects();
  784. }
  785. } catch (err) {
  786. console.error('Failed to load role tags:', err);
  787. }
  788. }
  789. function renderRolesTable() {
  790. const tbody = document.getElementById('roles-table-body');
  791. const empty = document.getElementById('roles-empty-state');
  792. if (!tbody) return;
  793. const roles = state.roles || [];
  794. if (roles.length === 0) {
  795. tbody.innerHTML = '';
  796. empty?.classList.remove('hidden');
  797. return;
  798. }
  799. empty?.classList.add('hidden');
  800. tbody.innerHTML = roles.map(r => {
  801. const colorKey = (r.color || 'blue').toLowerCase();
  802. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  803. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  804. const ifacesChips = ifaces.length > 0
  805. ? 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('')
  806. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  807. return `
  808. <tr class="hover:bg-slate-800/40 transition">
  809. <td class="py-3 px-4">
  810. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  811. ${escapeHtml(r.name)}
  812. </span>
  813. </td>
  814. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  815. <span>${escapeHtml(r.name)}</span>
  816. ${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>' : ''}
  817. </td>
  818. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  819. <span class="inline-flex items-center gap-1.5">
  820. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  821. <span>${escapeHtml(r.color || 'blue')}</span>
  822. </span>
  823. </td>
  824. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  825. <td class="py-3 px-4 font-sans">
  826. <div class="flex flex-wrap items-center">
  827. ${ifacesChips}
  828. </div>
  829. </td>
  830. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  831. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  832. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  833. Edit
  834. </button>
  835. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  836. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  837. Delete
  838. </button>
  839. </td>
  840. </tr>
  841. `;
  842. }).join('');
  843. }
  844. function openRoleModal(id = null) {
  845. const modal = document.getElementById('role-modal');
  846. if (!modal) return;
  847. const idInput = document.getElementById('role-modal-id');
  848. const nameInput = document.getElementById('role-modal-name');
  849. const colorSelect = document.getElementById('role-modal-color');
  850. const descInput = document.getElementById('role-modal-desc');
  851. const title = document.getElementById('role-modal-title');
  852. if (id) {
  853. const role = (state.roles || []).find(r => r.id === id);
  854. if (role) {
  855. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  856. if (idInput) idInput.value = role.id;
  857. if (nameInput) nameInput.value = role.name;
  858. if (colorSelect) colorSelect.value = role.color || 'blue';
  859. if (descInput) descInput.value = role.description || '';
  860. }
  861. } else {
  862. if (title) title.innerText = 'Add Role Tag';
  863. if (idInput) idInput.value = '';
  864. if (nameInput) nameInput.value = '';
  865. if (colorSelect) colorSelect.value = 'blue';
  866. if (descInput) descInput.value = '';
  867. }
  868. updateRoleModalPreview();
  869. modal.classList.remove('hidden');
  870. }
  871. function closeRoleModal() {
  872. const modal = document.getElementById('role-modal');
  873. if (modal) modal.classList.add('hidden');
  874. }
  875. function updateRoleModalPreview() {
  876. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  877. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  878. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  879. const preview = document.getElementById('role-modal-preview');
  880. if (preview) {
  881. preview.innerText = name;
  882. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  883. }
  884. }
  885. async function submitSaveRole(e) {
  886. e.preventDefault();
  887. const id = document.getElementById('role-modal-id')?.value;
  888. const name = document.getElementById('role-modal-name')?.value.trim();
  889. const color = document.getElementById('role-modal-color')?.value;
  890. const desc = document.getElementById('role-modal-desc')?.value.trim();
  891. if (!name) return;
  892. try {
  893. const payload = { id, name, color, description: desc };
  894. const method = id ? 'PUT' : 'POST';
  895. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  896. const res = await fetch(url, {
  897. method,
  898. headers: { 'Content-Type': 'application/json' },
  899. body: JSON.stringify(payload)
  900. });
  901. if (res.ok) {
  902. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  903. closeRoleModal();
  904. await loadRoles();
  905. fetchData(false);
  906. } else {
  907. const err = await res.json();
  908. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  909. }
  910. } catch (err) {
  911. showToast('Error', err.message, 'error');
  912. }
  913. }
  914. async function deleteRoleTag(id, name) {
  915. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  916. try {
  917. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  918. method: 'DELETE'
  919. });
  920. if (res.ok) {
  921. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  922. await loadRoles();
  923. fetchData(false);
  924. } else {
  925. const err = await res.json();
  926. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  927. }
  928. } catch (err) {
  929. showToast('Error', err.message, 'error');
  930. }
  931. }
  932. function populateRoleSelects(selectedRole = '') {
  933. const ifaceSelect = document.getElementById('modal-iface-role');
  934. const vlanSelect = document.getElementById('vlan-role');
  935. const roles = state.roles || [];
  936. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  937. if (ifaceSelect) {
  938. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  939. ifaceSelect.innerHTML = optionsHtml;
  940. if (currentVal) ifaceSelect.value = currentVal;
  941. }
  942. if (vlanSelect) {
  943. const currentVal = vlanSelect.value || 'LAN';
  944. vlanSelect.innerHTML = optionsHtml;
  945. if (currentVal) vlanSelect.value = currentVal;
  946. }
  947. }
  948. // Filter and Render Hierarchical Interfaces List
  949. function filterIfaces(filter) {
  950. state.ifaceFilter = filter || 'all';
  951. renderInterfacesList();
  952. }
  953. function renderInterfacesList() {
  954. const tbody = document.getElementById('interfaces-tree-tbody');
  955. const emptyState = document.getElementById('interfaces-empty-state');
  956. const summary = document.getElementById('ifaces-list-summary');
  957. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  958. const allIfaces = state.interfaces || [];
  959. const allVlans = state.vlans || [];
  960. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  961. const filteredParents = parentIfaces.filter(parent => {
  962. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  963. if (query) {
  964. const matchName = parent.name.toLowerCase().includes(query);
  965. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  966. const matchRole = (parent.role || '').toLowerCase().includes(query);
  967. const matchType = (parent.type || '').toLowerCase().includes(query);
  968. const matchVlan = childVlans.some(v =>
  969. v.name.toLowerCase().includes(query) ||
  970. String(v.vlan_id).includes(query) ||
  971. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  972. (v.description || '').toLowerCase().includes(query)
  973. );
  974. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  975. }
  976. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  977. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  978. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  979. return true;
  980. });
  981. if (summary) {
  982. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  983. }
  984. if (filteredParents.length === 0) {
  985. emptyState?.classList.remove('hidden');
  986. tbody.innerHTML = '';
  987. return;
  988. }
  989. emptyState?.classList.add('hidden');
  990. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  991. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  992. return `${p.name}:${p.state}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}`;
  993. }).join(';');
  994. if (tbody.dataset.sig === sig) {
  995. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  996. }
  997. tbody.dataset.sig = sig;
  998. tbody.innerHTML = '';
  999. filteredParents.forEach(parent => {
  1000. const isUp = parent.state === 'UP';
  1001. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1002. const hasVlans = childVlans.length > 0;
  1003. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1004. const canHaveVlan = supportsVLAN(parent);
  1005. const parentRow = document.createElement('tr');
  1006. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1007. parentRow.innerHTML = `
  1008. <td class="py-3 px-3 text-center">
  1009. ${hasVlans ? `
  1010. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1011. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1012. <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">
  1013. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1014. </svg>
  1015. </button>
  1016. ` : `
  1017. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1018. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1019. </div>
  1020. `}
  1021. </td>
  1022. <td class="py-3 px-4">
  1023. <div class="flex items-center space-x-2.5">
  1024. <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">
  1025. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1026. </div>
  1027. <div>
  1028. <div class="flex items-center gap-2">
  1029. <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'}">
  1030. <span>${parent.name}</span>
  1031. <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>
  1032. </span>
  1033. ${hasVlans ? `
  1034. <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>
  1035. ` : `
  1036. <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>
  1037. `}
  1038. </div>
  1039. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1040. </div>
  1041. </div>
  1042. </td>
  1043. <td class="py-3 px-4 font-sans">
  1044. <div class="flex items-center gap-1.5">
  1045. ${getRoleBadge(parent.role || 'LAN')}
  1046. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1047. </div>
  1048. </td>
  1049. <td class="py-3 px-4">
  1050. ${parent.ipv4 && parent.ipv4.length > 0
  1051. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1052. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1053. }
  1054. ${(() => {
  1055. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1056. if (!c) return '';
  1057. 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');
  1058. 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>`;
  1059. })()}
  1060. </td>
  1061. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1062. <div>${parent.mac || 'N/A'}</div>
  1063. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1064. </td>
  1065. <td class="py-3 px-4 text-[11px]">
  1066. <div class="flex items-center space-x-2">
  1067. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1068. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1069. </div>
  1070. </td>
  1071. <td class="py-3 px-4 font-sans">
  1072. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1073. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1074. 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'
  1075. }" title="Click to toggle link status">
  1076. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1077. <span>${parent.state}</span>
  1078. </button>
  1079. </td>
  1080. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1081. ${(() => {
  1082. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1083. if (c) {
  1084. 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>`;
  1085. }
  1086. 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>`;
  1087. })()}
  1088. ${canHaveVlan ? `
  1089. <button onclick="openVlanModal('${parent.name}')"
  1090. 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">
  1091. + Add VLAN
  1092. </button>
  1093. ` : ''}
  1094. <button onclick="openIfaceModal('${parent.name}')"
  1095. 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">
  1096. Configure
  1097. </button>
  1098. </td>
  1099. `;
  1100. tbody.appendChild(parentRow);
  1101. if (isExpanded) {
  1102. const drawerRow = document.createElement('tr');
  1103. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1104. const drawerCell = document.createElement('td');
  1105. drawerCell.colSpan = 8;
  1106. drawerCell.className = 'p-0';
  1107. drawerCell.innerHTML = `
  1108. <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">
  1109. <div class="flex items-center justify-between mb-3">
  1110. <div class="flex items-center space-x-3">
  1111. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1112. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1113. </span>
  1114. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1115. ${childVlans.length} Attached
  1116. </span>
  1117. </div>
  1118. <button onclick="openVlanModal('${parent.name}')"
  1119. 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">
  1120. <span>+ Create VLAN on ${parent.name}</span>
  1121. </button>
  1122. </div>
  1123. ${childVlans.length === 0 ? `
  1124. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1125. <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>
  1126. <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">
  1127. <span>+ Create Your First VLAN on ${parent.name}</span>
  1128. </button>
  1129. </div>
  1130. ` : `
  1131. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1132. <table class="w-full text-left text-xs font-mono">
  1133. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1134. <tr>
  1135. <th class="py-2.5 px-4">VLAN ID</th>
  1136. <th class="py-2.5 px-4">Interface Device</th>
  1137. <th class="py-2.5 px-4">Subnet Gateway</th>
  1138. <th class="py-2.5 px-4">Role / Alias</th>
  1139. <th class="py-2.5 px-4">MTU</th>
  1140. <th class="py-2.5 px-4">Throughput</th>
  1141. <th class="py-2.5 px-4">Status</th>
  1142. <th class="py-2.5 px-4 text-right">Actions</th>
  1143. </tr>
  1144. </thead>
  1145. <tbody class="divide-y divide-slate-800/70">
  1146. ${childVlans.map(v => {
  1147. const isVlanUp = v.state === 'UP';
  1148. return `
  1149. <tr class="hover:bg-slate-800/40 transition">
  1150. <td class="py-2.5 px-4">
  1151. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1152. VLAN ${v.vlan_id}
  1153. </span>
  1154. </td>
  1155. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1156. <span class="text-cyan-500">└─</span>
  1157. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1158. <span>${v.name}</span>
  1159. <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>
  1160. </span>
  1161. </td>
  1162. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1163. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1164. ${(() => {
  1165. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1166. if (!c) return '';
  1167. 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';
  1168. 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>`;
  1169. })()}
  1170. </td>
  1171. <td class="py-2.5 px-4 font-sans text-slate-300">
  1172. <div class="flex items-center gap-1.5">
  1173. ${getRoleBadge(v.role || 'LAN')}
  1174. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1175. </div>
  1176. </td>
  1177. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1178. <td class="py-2.5 px-4 text-[11px]">
  1179. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1180. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1181. </td>
  1182. <td class="py-2.5 px-4 font-sans">
  1183. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1184. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1185. 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'
  1186. }">
  1187. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1188. <span>${v.state}</span>
  1189. </button>
  1190. </td>
  1191. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1192. ${(() => {
  1193. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1194. if (c) {
  1195. 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>`;
  1196. }
  1197. 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>`;
  1198. })()}
  1199. <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>
  1200. <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>
  1201. </td>
  1202. </tr>
  1203. `;
  1204. }).join('')}
  1205. </tbody>
  1206. </table>
  1207. </div>
  1208. `}
  1209. </div>
  1210. `;
  1211. drawerRow.appendChild(drawerCell);
  1212. tbody.appendChild(drawerRow);
  1213. }
  1214. });
  1215. }
  1216. // Render VLANs Dedicated View
  1217. function renderVlansList() {
  1218. const tbody = document.getElementById('vlans-table-body');
  1219. if (!tbody) return;
  1220. const emptyState = document.getElementById('vlans-empty-state');
  1221. const countBadge = document.getElementById('vlans-table-count');
  1222. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1223. const allVlans = state.vlans || [];
  1224. if (countBadge) countBadge.innerText = allVlans.length;
  1225. const filtered = allVlans.filter(v => {
  1226. if (!query) return true;
  1227. return v.name.toLowerCase().includes(query) ||
  1228. String(v.vlan_id).includes(query) ||
  1229. (v.description || '').toLowerCase().includes(query) ||
  1230. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1231. });
  1232. if (allVlans.length === 0) {
  1233. emptyState.classList.remove('hidden');
  1234. tbody.innerHTML = '';
  1235. return;
  1236. }
  1237. emptyState.classList.add('hidden');
  1238. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1239. if (tbody.dataset.sig === sig) return;
  1240. tbody.dataset.sig = sig;
  1241. tbody.innerHTML = '';
  1242. filtered.forEach(v => {
  1243. const isUp = v.state === 'UP';
  1244. const tr = document.createElement('tr');
  1245. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1246. tr.innerHTML = `
  1247. <td class="py-3 px-4">
  1248. <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">
  1249. VLAN ${v.vlan_id}
  1250. </span>
  1251. </td>
  1252. <td class="py-3 px-4 font-bold text-white">
  1253. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1254. <span>${v.name}</span>
  1255. <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>
  1256. </span>
  1257. </td>
  1258. <td class="py-3 px-4 text-slate-300">
  1259. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1260. </td>
  1261. <td class="py-3 px-4 text-emerald-400 font-medium">
  1262. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1263. </td>
  1264. <td class="py-3 px-4 text-slate-300 font-sans">
  1265. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1266. </td>
  1267. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1268. <td class="py-3 px-4 font-sans">
  1269. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1270. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1271. 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'
  1272. }">
  1273. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1274. <span>${v.state}</span>
  1275. </button>
  1276. </td>
  1277. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1278. <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>
  1279. <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>
  1280. </td>
  1281. `;
  1282. tbody.appendChild(tr);
  1283. });
  1284. }
  1285. // Toggle interface UP / DOWN
  1286. async function toggleInterfaceState(name, newState) {
  1287. try {
  1288. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1289. method: 'POST',
  1290. headers: { 'Content-Type': 'application/json' },
  1291. body: JSON.stringify({ state: newState })
  1292. });
  1293. const data = await res.json();
  1294. if (res.ok) {
  1295. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1296. fetchData(false);
  1297. } else {
  1298. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1299. }
  1300. } catch (err) {
  1301. showToast('Error', err.message, 'error');
  1302. }
  1303. }
  1304. // ---------------- MikroTik Flag & Utilities ----------------
  1305. function renderMikroTikFlag(running, disabled) {
  1306. if (running) {
  1307. 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>`;
  1308. }
  1309. if (disabled) {
  1310. 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>`;
  1311. }
  1312. 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>`;
  1313. }
  1314. function copyToClipboard(text, label = 'Text') {
  1315. navigator.clipboard.writeText(text).then(() => {
  1316. showToast('Copied', `${label} copied to clipboard`, 'success');
  1317. }).catch(() => {
  1318. prompt('Copy value:', text);
  1319. });
  1320. }
  1321. // ======================== PPP Profiles Shared Helper ========================
  1322. async function fetchPPPProfilesList() {
  1323. try {
  1324. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1325. if (res.ok) {
  1326. state.pppProfiles = await res.json();
  1327. }
  1328. } catch (err) {
  1329. console.error('Failed to load PPP profiles:', err);
  1330. }
  1331. }
  1332. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1333. const sel = document.getElementById(selectId);
  1334. if (!sel) return;
  1335. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1336. { name: 'default', use_encryption: 'no' },
  1337. { name: 'default-encryption', use_encryption: 'required' }
  1338. ];
  1339. sel.innerHTML = '';
  1340. profiles.forEach(p => {
  1341. const opt = document.createElement('option');
  1342. opt.value = p.name;
  1343. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1344. opt.innerText = `${p.name}${encBadge}`;
  1345. sel.appendChild(opt);
  1346. });
  1347. if (selectedVal) {
  1348. sel.value = selectedVal;
  1349. } else {
  1350. sel.value = defaultVal;
  1351. }
  1352. if (!sel.value && sel.options.length > 0) {
  1353. sel.selectedIndex = 0;
  1354. }
  1355. }
  1356. // ======================== PPPoE Multi-Instance ========================
  1357. async function loadPPPoE(populateInputs = true) {
  1358. try {
  1359. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1360. await fetchPPPProfilesList();
  1361. }
  1362. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1363. const list = await res.json();
  1364. state.pppoeList = Array.isArray(list) ? list : [];
  1365. const badge = document.getElementById('pppoe-count-badge');
  1366. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1367. const tbody = document.getElementById('pppoe-table-body');
  1368. const empty = document.getElementById('pppoe-empty');
  1369. if (!tbody) return;
  1370. tbody.innerHTML = '';
  1371. if (state.pppoeList.length === 0) {
  1372. if (empty) empty.classList.remove('hidden');
  1373. } else {
  1374. if (empty) empty.classList.add('hidden');
  1375. state.pppoeList.forEach(inst => {
  1376. const tr = document.createElement('tr');
  1377. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1378. tr.innerHTML = `
  1379. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1380. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1381. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1382. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1383. <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>
  1384. <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>
  1385. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1386. <td class="py-2.5 px-3 text-center">
  1387. <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'}">
  1388. ${inst.default_route ? 'Yes' : 'No'}
  1389. </span>
  1390. </td>
  1391. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1392. ${inst.running ? `
  1393. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1394. ` : `
  1395. <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>
  1396. `}
  1397. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1398. ${inst.disabled ? 'Enable' : 'Disable'}
  1399. </button>
  1400. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1401. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1402. </td>
  1403. `;
  1404. tbody.appendChild(tr);
  1405. });
  1406. }
  1407. } catch (err) {
  1408. console.error('Failed to load PPPoE:', err);
  1409. }
  1410. }
  1411. function openAddPPPoEModal() {
  1412. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1413. document.getElementById('pppoe-modal-edit-orig').value = '';
  1414. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1415. document.getElementById('pppoe-modal-name').readOnly = false;
  1416. document.getElementById('pppoe-modal-user').value = '';
  1417. document.getElementById('pppoe-modal-pass').value = '';
  1418. document.getElementById('pppoe-modal-service').value = '';
  1419. document.getElementById('pppoe-modal-mtu').value = '1492';
  1420. document.getElementById('pppoe-modal-defroute').checked = true;
  1421. document.getElementById('pppoe-modal-reconnect').checked = true;
  1422. document.getElementById('pppoe-modal-disabled').checked = false;
  1423. // Populate profiles
  1424. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1425. // Populate interfaces
  1426. const sel = document.getElementById('pppoe-modal-iface');
  1427. sel.innerHTML = '';
  1428. (state.interfaces || []).forEach(i => {
  1429. if (i.name === 'lo') return;
  1430. const opt = document.createElement('option');
  1431. opt.value = i.name;
  1432. opt.innerText = `${i.name} (${i.role || i.type})`;
  1433. sel.appendChild(opt);
  1434. });
  1435. document.getElementById('pppoe-modal').classList.remove('hidden');
  1436. }
  1437. function openEditPPPoEModal(name) {
  1438. const inst = (state.pppoeList || []).find(i => i.name === name);
  1439. if (!inst) return;
  1440. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1441. document.getElementById('pppoe-modal-edit-orig').value = name;
  1442. document.getElementById('pppoe-modal-name').value = inst.name;
  1443. document.getElementById('pppoe-modal-name').readOnly = true;
  1444. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1445. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1446. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1447. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1448. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1449. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1450. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1451. // Populate profiles
  1452. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1453. const sel = document.getElementById('pppoe-modal-iface');
  1454. sel.innerHTML = '';
  1455. (state.interfaces || []).forEach(i => {
  1456. if (i.name === 'lo') return;
  1457. const opt = document.createElement('option');
  1458. opt.value = i.name;
  1459. opt.innerText = `${i.name} (${i.role || i.type})`;
  1460. if (i.name === inst.interface) opt.selected = true;
  1461. sel.appendChild(opt);
  1462. });
  1463. document.getElementById('pppoe-modal').classList.remove('hidden');
  1464. }
  1465. function closePPPoEModal() {
  1466. document.getElementById('pppoe-modal').classList.add('hidden');
  1467. }
  1468. async function submitSavePPPoE(e) {
  1469. e.preventDefault();
  1470. const name = document.getElementById('pppoe-modal-name').value.trim();
  1471. const iface = document.getElementById('pppoe-modal-iface').value;
  1472. const user = document.getElementById('pppoe-modal-user').value.trim();
  1473. const pass = document.getElementById('pppoe-modal-pass').value;
  1474. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1475. const service = document.getElementById('pppoe-modal-service').value.trim();
  1476. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1477. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1478. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1479. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1480. try {
  1481. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1482. method: 'POST',
  1483. headers: { 'Content-Type': 'application/json' },
  1484. body: JSON.stringify({
  1485. name,
  1486. interface: iface,
  1487. username: user,
  1488. password: pass,
  1489. profile: profile,
  1490. service_name: service,
  1491. mtu,
  1492. default_route: defRoute,
  1493. auto_reconnect: reconnect,
  1494. disabled
  1495. })
  1496. });
  1497. if (res.ok) {
  1498. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1499. closePPPoEModal();
  1500. loadPPPoE(false);
  1501. fetchData(false);
  1502. } else {
  1503. const err = await res.json();
  1504. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1505. }
  1506. } catch (err) {
  1507. showToast('Error', err.message, 'error');
  1508. }
  1509. }
  1510. async function connectPPPoEInstance(name) {
  1511. try {
  1512. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1513. if (res.ok) {
  1514. showToast('Connecting', `Dialing ${name}...`, 'info');
  1515. setTimeout(() => loadPPPoE(false), 2000);
  1516. }
  1517. } catch (err) {
  1518. showToast('Error', err.message, 'error');
  1519. }
  1520. }
  1521. async function disconnectPPPoEInstance(name) {
  1522. try {
  1523. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1524. if (res.ok) {
  1525. showToast('Disconnected', `${name} session terminated`, 'info');
  1526. setTimeout(() => loadPPPoE(false), 1000);
  1527. }
  1528. } catch (err) {
  1529. showToast('Error', err.message, 'error');
  1530. }
  1531. }
  1532. async function togglePPPoEState(name, enable) {
  1533. try {
  1534. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1535. method: 'POST',
  1536. headers: { 'Content-Type': 'application/json' },
  1537. body: JSON.stringify({ enabled: enable })
  1538. });
  1539. if (res.ok) {
  1540. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1541. loadPPPoE(false);
  1542. }
  1543. } catch (err) {
  1544. showToast('Error', err.message, 'error');
  1545. }
  1546. }
  1547. async function deletePPPoEInstance(name) {
  1548. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1551. if (res.ok) {
  1552. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1553. loadPPPoE(false);
  1554. fetchData(false);
  1555. }
  1556. } catch (err) {
  1557. showToast('Error', err.message, 'error');
  1558. }
  1559. }
  1560. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1561. state.wgSubTab = 'ifaces';
  1562. function switchWGSubTab(tab) {
  1563. state.wgSubTab = tab;
  1564. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1565. const peersPanel = document.getElementById('wg-subtab-peers');
  1566. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1567. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1568. if (tab === 'ifaces') {
  1569. ifacesPanel?.classList.remove('hidden');
  1570. peersPanel?.classList.add('hidden');
  1571. 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';
  1572. 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';
  1573. } else {
  1574. ifacesPanel?.classList.add('hidden');
  1575. peersPanel?.classList.remove('hidden');
  1576. 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';
  1577. 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';
  1578. renderWGPeers();
  1579. }
  1580. }
  1581. async function loadWireGuard(populateInputs = true) {
  1582. try {
  1583. const [ifacesRes, peersRes] = await Promise.all([
  1584. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1585. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1586. ]);
  1587. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1588. const peers = peersRes.ok ? await peersRes.json() : [];
  1589. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1590. state.wgPeers = Array.isArray(peers) ? peers : [];
  1591. // Badges
  1592. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1593. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1594. const peersCountBadge = document.getElementById('wg-peers-count');
  1595. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1596. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1597. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1598. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1599. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1600. // Render Interfaces
  1601. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1602. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1603. if (ifacesTbody) {
  1604. ifacesTbody.innerHTML = '';
  1605. if (state.wgInterfaces.length === 0) {
  1606. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1607. } else {
  1608. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1609. state.wgInterfaces.forEach(iface => {
  1610. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1611. const tr = document.createElement('tr');
  1612. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1613. tr.innerHTML = `
  1614. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1615. <td class="py-2.5 px-3">
  1616. <div class="flex items-center gap-1.5">
  1617. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1618. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1619. </div>
  1620. </td>
  1621. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1622. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1623. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1624. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1625. ${(iface.public_key || '').substring(0, 10)}... 📋
  1626. </span>
  1627. </td>
  1628. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1629. <td class="py-2.5 px-3 text-center">
  1630. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1631. </td>
  1632. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1633. ${iface.running ? `
  1634. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1635. ` : `
  1636. <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>
  1637. `}
  1638. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1639. ${iface.disabled ? 'Enable' : 'Disable'}
  1640. </button>
  1641. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1642. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1643. </td>
  1644. `;
  1645. ifacesTbody.appendChild(tr);
  1646. });
  1647. }
  1648. }
  1649. // Populate filter dropdown in peers tab
  1650. const filterSel = document.getElementById('wg-peers-filter-iface');
  1651. if (filterSel) {
  1652. const currentVal = filterSel.value;
  1653. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1654. state.wgInterfaces.forEach(i => {
  1655. const opt = document.createElement('option');
  1656. opt.value = i.name;
  1657. opt.innerText = i.name;
  1658. if (i.name === currentVal) opt.selected = true;
  1659. filterSel.appendChild(opt);
  1660. });
  1661. }
  1662. renderWGPeers();
  1663. } catch (err) {
  1664. console.error('Failed to load WireGuard:', err);
  1665. }
  1666. }
  1667. function formatWGPeerEndpoint(address, port) {
  1668. if (!address || address === '(none)') return '--';
  1669. let addr = address.trim();
  1670. let p = port || 0;
  1671. while (addr.includes(':') && !addr.startsWith('[')) {
  1672. const lastColon = addr.lastIndexOf(':');
  1673. const maybePort = addr.substring(lastColon + 1);
  1674. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1675. if (!p) p = parseInt(maybePort, 10);
  1676. addr = addr.substring(0, lastColon);
  1677. } else {
  1678. break;
  1679. }
  1680. }
  1681. return p ? `${addr}:${p}` : addr;
  1682. }
  1683. function renderWGPeers() {
  1684. const filterSel = document.getElementById('wg-peers-filter-iface');
  1685. const selectedIface = filterSel ? filterSel.value : '';
  1686. const tbody = document.getElementById('wg-peers-table-body');
  1687. const empty = document.getElementById('wg-peers-empty');
  1688. if (!tbody) return;
  1689. tbody.innerHTML = '';
  1690. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1691. if (filtered.length === 0) {
  1692. if (empty) empty.classList.remove('hidden');
  1693. } else {
  1694. if (empty) empty.classList.add('hidden');
  1695. filtered.forEach(p => {
  1696. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1697. const tr = document.createElement('tr');
  1698. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1699. tr.innerHTML = `
  1700. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1701. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1702. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1703. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1704. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1705. ${(p.public_key || '').substring(0, 10)}... 📋
  1706. </span>
  1707. </td>
  1708. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1709. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1710. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1711. <td class="py-2.5 px-3 font-mono text-[11px]">
  1712. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1713. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1714. </td>
  1715. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1716. <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">
  1717. ${p.disabled ? 'Enable' : 'Disable'}
  1718. </button>
  1719. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1720. <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>
  1721. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1722. </td>
  1723. `;
  1724. tbody.appendChild(tr);
  1725. });
  1726. }
  1727. }
  1728. function openAddWGInterfaceModal() {
  1729. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1730. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1731. const nameEl = document.getElementById('wg-iface-modal-name');
  1732. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1733. nameEl.readOnly = false;
  1734. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1735. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1736. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1737. document.getElementById('wg-iface-modal-comment').value = '';
  1738. document.getElementById('wg-iface-modal-pubkey').value = '';
  1739. document.getElementById('wg-iface-modal-privkey').value = '';
  1740. document.getElementById('wg-iface-modal-disabled').checked = false;
  1741. generateWGInterfaceKeys();
  1742. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1743. }
  1744. function openEditWGInterfaceModal(name) {
  1745. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1746. if (!iface) return;
  1747. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1748. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1749. const nameEl = document.getElementById('wg-iface-modal-name');
  1750. nameEl.value = iface.name;
  1751. nameEl.readOnly = false; // ALLOW RENAMING
  1752. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1753. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1754. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1755. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1756. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1757. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1758. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1759. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1760. }
  1761. function closeAddWGInterfaceModal() {
  1762. document.getElementById('wg-iface-modal').classList.add('hidden');
  1763. }
  1764. async function generateWGInterfaceKeys() {
  1765. try {
  1766. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1767. const keys = await res.json();
  1768. if (res.ok) {
  1769. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1770. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1771. }
  1772. } catch (err) {
  1773. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1774. }
  1775. }
  1776. async function onWGInterfacePrivKeyInput() {
  1777. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1778. if (!privKey) return;
  1779. try {
  1780. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1781. method: 'POST',
  1782. headers: { 'Content-Type': 'application/json' },
  1783. body: JSON.stringify({ private_key: privKey })
  1784. });
  1785. if (res.ok) {
  1786. const data = await res.json();
  1787. if (data.public_key) {
  1788. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1789. }
  1790. }
  1791. } catch (err) {
  1792. // Ignore while typing
  1793. }
  1794. }
  1795. function toggleWGPrivKeyVisibility() {
  1796. const el = document.getElementById('wg-iface-modal-privkey');
  1797. const btn = document.getElementById('btn-toggle-wg-privkey');
  1798. if (el.type === 'password') {
  1799. el.type = 'text';
  1800. btn.innerText = '🙈 Hide';
  1801. } else {
  1802. el.type = 'password';
  1803. btn.innerText = '👁️ Show';
  1804. }
  1805. }
  1806. function copyWGInterfacePubKey() {
  1807. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1808. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1809. }
  1810. async function submitSaveWGInterface(e) {
  1811. e.preventDefault();
  1812. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1813. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1814. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1815. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1816. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1817. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1818. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1819. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1820. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1821. try {
  1822. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1823. method: 'POST',
  1824. headers: { 'Content-Type': 'application/json' },
  1825. body: JSON.stringify({
  1826. orig_name: origName,
  1827. name,
  1828. listen_port: port,
  1829. address: addr,
  1830. mtu,
  1831. comment,
  1832. public_key: pub,
  1833. private_key: priv,
  1834. disabled
  1835. })
  1836. });
  1837. const data = await res.json();
  1838. if (res.ok) {
  1839. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1840. closeAddWGInterfaceModal();
  1841. loadWireGuard(false);
  1842. fetchData(false);
  1843. } else {
  1844. showToast('Error', data.error || 'Failed to save interface', 'error');
  1845. }
  1846. } catch (err) {
  1847. showToast('Error', err.message, 'error');
  1848. }
  1849. }
  1850. async function startWGInterface(name) {
  1851. try {
  1852. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1853. if (res.ok) {
  1854. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1855. loadWireGuard(false);
  1856. fetchData(false);
  1857. }
  1858. } catch (err) {
  1859. showToast('Error', err.message, 'error');
  1860. }
  1861. }
  1862. async function stopWGInterface(name) {
  1863. try {
  1864. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1865. if (res.ok) {
  1866. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1867. loadWireGuard(false);
  1868. fetchData(false);
  1869. }
  1870. } catch (err) {
  1871. showToast('Error', err.message, 'error');
  1872. }
  1873. }
  1874. async function toggleWGInterfaceState(name, enable) {
  1875. try {
  1876. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1877. method: 'POST',
  1878. headers: { 'Content-Type': 'application/json' },
  1879. body: JSON.stringify({ enabled: enable })
  1880. });
  1881. if (res.ok) {
  1882. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1883. loadWireGuard(false);
  1884. fetchData(false);
  1885. }
  1886. } catch (err) {
  1887. showToast('Error', err.message, 'error');
  1888. }
  1889. }
  1890. async function deleteWGInterface(name) {
  1891. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1892. try {
  1893. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1894. if (res.ok) {
  1895. showToast('Deleted', `Interface ${name} removed`, 'success');
  1896. loadWireGuard(false);
  1897. fetchData(false);
  1898. }
  1899. } catch (err) {
  1900. showToast('Error', err.message, 'error');
  1901. }
  1902. }
  1903. function populateWGPeerIfaceSelect(selectedIface = '') {
  1904. const sel = document.getElementById('wg-peer-modal-iface');
  1905. if (!sel) return;
  1906. sel.innerHTML = '';
  1907. (state.wgInterfaces || []).forEach(i => {
  1908. const opt = document.createElement('option');
  1909. opt.value = i.name;
  1910. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1911. if (i.name === selectedIface) opt.selected = true;
  1912. sel.appendChild(opt);
  1913. });
  1914. }
  1915. function openAddWGPeerModal() {
  1916. if ((state.wgInterfaces || []).length === 0) {
  1917. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1918. openAddWGInterfaceModal();
  1919. return;
  1920. }
  1921. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1922. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1923. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1924. populateWGPeerIfaceSelect();
  1925. document.getElementById('wg-peer-modal-name').value = '';
  1926. document.getElementById('wg-peer-modal-pubkey').value = '';
  1927. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1928. document.getElementById('wg-peer-modal-endpoint').value = '';
  1929. document.getElementById('wg-peer-modal-port').value = '';
  1930. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1931. document.getElementById('wg-peer-modal-preshared').value = '';
  1932. document.getElementById('wg-peer-modal-disabled').checked = false;
  1933. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1934. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1935. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1936. }
  1937. function openEditWGPeerModal(ifaceName, pubKey) {
  1938. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1939. if (!peer) {
  1940. showToast('Not Found', 'Peer not found', 'warning');
  1941. return;
  1942. }
  1943. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1944. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1945. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1946. populateWGPeerIfaceSelect(peer.interface);
  1947. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1948. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1949. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1950. let epHost = (peer.endpoint_address || '').trim();
  1951. let epPort = peer.endpoint_port || '';
  1952. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1953. const lastColon = epHost.lastIndexOf(':');
  1954. const maybePort = epHost.substring(lastColon + 1);
  1955. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1956. if (!epPort) epPort = parseInt(maybePort, 10);
  1957. epHost = epHost.substring(0, lastColon);
  1958. } else {
  1959. break;
  1960. }
  1961. }
  1962. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  1963. document.getElementById('wg-peer-modal-port').value = epPort;
  1964. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1965. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1966. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1967. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1968. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1969. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1970. }
  1971. function closeAddWGPeerModal() {
  1972. document.getElementById('wg-peer-modal').classList.add('hidden');
  1973. }
  1974. async function generatePeerKeypairHelper() {
  1975. try {
  1976. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1977. const keys = await res.json();
  1978. if (res.ok) {
  1979. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1980. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1981. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1982. checkWGPeerKeyValidity();
  1983. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1984. }
  1985. } catch (err) {
  1986. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1987. }
  1988. }
  1989. function copyGeneratedPeerPrivKey() {
  1990. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1991. if (priv) copyToClipboard(priv, 'Client Private Key');
  1992. }
  1993. async function generatePeerPSK() {
  1994. try {
  1995. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1996. const keys = await res.json();
  1997. if (res.ok && keys.private_key) {
  1998. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1999. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2000. }
  2001. } catch (err) {
  2002. showToast('Error', err.message, 'error');
  2003. }
  2004. }
  2005. function checkWGPeerKeyValidity() {
  2006. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2007. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2008. const warningEl = document.getElementById('wg-peer-key-warning');
  2009. if (!warningEl) return;
  2010. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2011. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2012. warningEl.classList.remove('hidden');
  2013. } else {
  2014. warningEl.classList.add('hidden');
  2015. }
  2016. }
  2017. async function submitSaveWGPeer(e) {
  2018. e.preventDefault();
  2019. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2020. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2021. const iface = document.getElementById('wg-peer-modal-iface').value;
  2022. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2023. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2024. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2025. .split(',')
  2026. .map(s => s.trim())
  2027. .filter(s => s.length > 0);
  2028. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2029. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2030. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2031. const lastColon = epHost.lastIndexOf(':');
  2032. const maybePort = epHost.substring(lastColon + 1);
  2033. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2034. if (!epPort) epPort = parseInt(maybePort, 10);
  2035. epHost = epHost.substring(0, lastColon);
  2036. } else {
  2037. break;
  2038. }
  2039. }
  2040. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2041. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2042. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2043. // Validation
  2044. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2045. if (targetIface && targetIface.public_key === pub) {
  2046. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2047. return;
  2048. }
  2049. try {
  2050. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2051. method: 'POST',
  2052. headers: { 'Content-Type': 'application/json' },
  2053. body: JSON.stringify({
  2054. orig_interface: origIface,
  2055. orig_public_key: origPubKey,
  2056. interface: iface,
  2057. name,
  2058. public_key: pub,
  2059. allowed_ips: allowed,
  2060. endpoint_address: epHost,
  2061. endpoint_port: epPort,
  2062. persistent_keepalive: keepalive,
  2063. preshared_key: psk,
  2064. disabled
  2065. })
  2066. });
  2067. const data = await res.json();
  2068. if (res.ok) {
  2069. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2070. closeAddWGPeerModal();
  2071. loadWireGuard(false);
  2072. } else {
  2073. showToast('Error', data.error || 'Failed to save peer', 'error');
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function toggleWGPeerState(iface, pubkey, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2085. });
  2086. const data = await res.json();
  2087. if (res.ok) {
  2088. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2089. loadWireGuard(false);
  2090. } else {
  2091. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2092. }
  2093. } catch (err) {
  2094. showToast('Error', err.message, 'error');
  2095. }
  2096. }
  2097. async function deleteWGPeer(iface, pubkey) {
  2098. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2099. try {
  2100. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2101. method: 'POST',
  2102. headers: { 'Content-Type': 'application/json' },
  2103. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2108. loadWireGuard(false);
  2109. } else {
  2110. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2111. }
  2112. } catch (err) {
  2113. showToast('Error', err.message, 'error');
  2114. }
  2115. }
  2116. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2117. function switchIpsecModalTab(tab) {
  2118. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2119. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2120. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2121. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2122. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2123. if (tab === 'p1') {
  2124. if (p1Tab) {
  2125. 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';
  2126. }
  2127. if (p2Tab) {
  2128. 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';
  2129. }
  2130. if (p1Content) p1Content.classList.remove('hidden');
  2131. if (p2Content) p2Content.classList.add('hidden');
  2132. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2133. } else {
  2134. if (p1Tab) {
  2135. 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';
  2136. }
  2137. if (p2Tab) {
  2138. 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';
  2139. }
  2140. if (p1Content) p1Content.classList.add('hidden');
  2141. if (p2Content) p2Content.classList.remove('hidden');
  2142. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2143. }
  2144. }
  2145. function toggleIpsecPhaseStep() {
  2146. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2147. if (p1Content && !p1Content.classList.contains('hidden')) {
  2148. switchIpsecModalTab('p2');
  2149. } else {
  2150. switchIpsecModalTab('p1');
  2151. }
  2152. }
  2153. function toggleIpsecPskVisibility() {
  2154. const pskInput = document.getElementById('ipsec-modal-psk');
  2155. if (!pskInput) return;
  2156. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2157. }
  2158. function addIpsecLocalSubnet(val = '') {
  2159. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2160. if (!container) return;
  2161. const row = document.createElement('div');
  2162. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2163. row.innerHTML = `
  2164. <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">
  2165. <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>
  2166. `;
  2167. container.appendChild(row);
  2168. }
  2169. function addIpsecRemoteSubnet(val = '') {
  2170. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2171. if (!container) return;
  2172. const row = document.createElement('div');
  2173. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2174. row.innerHTML = `
  2175. <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">
  2176. <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>
  2177. `;
  2178. container.appendChild(row);
  2179. }
  2180. function updateIpsecEspProposalFromPFS(val) {
  2181. const prop = document.getElementById('ipsec-modal-espprop');
  2182. if (!prop) return;
  2183. if (val === 'none') {
  2184. prop.value = 'aes256-sha256,aes128-sha256,default';
  2185. } else {
  2186. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2187. }
  2188. }
  2189. function updateIpsecIkeProposalFromDH(dh) {
  2190. const el = document.getElementById('ipsec-modal-ikeprop');
  2191. if (el) {
  2192. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2193. }
  2194. }
  2195. function safeSetVal(id, val) {
  2196. const el = document.getElementById(id);
  2197. if (el) el.value = val;
  2198. }
  2199. function safeSetChecked(id, val) {
  2200. const el = document.getElementById(id);
  2201. if (el) el.checked = !!val;
  2202. }
  2203. function safeGetVal(id, def = '') {
  2204. const el = document.getElementById(id);
  2205. return el ? el.value : def;
  2206. }
  2207. async function loadIPSec(populateInputs = true) {
  2208. try {
  2209. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2210. const list = await res.json();
  2211. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2212. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2213. const badge = document.getElementById('ipsec-sas-badge');
  2214. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2215. const tbody = document.getElementById('ipsec-table-body');
  2216. const empty = document.getElementById('ipsec-empty');
  2217. if (!tbody) return;
  2218. tbody.innerHTML = '';
  2219. if (state.ipsecTunnels.length === 0) {
  2220. if (empty) empty.classList.remove('hidden');
  2221. } else {
  2222. if (empty) empty.classList.add('hidden');
  2223. state.ipsecTunnels.forEach(c => {
  2224. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2225. const tr = document.createElement('tr');
  2226. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2227. // Local subnets tags
  2228. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2229. 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('');
  2230. // Remote subnets tags
  2231. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2232. 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('');
  2233. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2234. const p2Name = c.phase2_name || `${c.name}_p2`;
  2235. tr.innerHTML = `
  2236. <td class="py-2.5 px-3 text-center">
  2237. ${isEstablished ? `
  2238. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2239. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2240. <span>UP</span>
  2241. </span>
  2242. ` : (c.disabled ? `
  2243. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2244. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2245. <span>DOWN</span>
  2246. </span>
  2247. ` : `
  2248. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2249. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2250. <span>IDLE</span>
  2251. </span>
  2252. `)}
  2253. </td>
  2254. <td class="py-2.5 px-4 font-bold text-white">
  2255. <div class="flex items-center gap-2">
  2256. <span class="text-amber-400">🛡</span>
  2257. <div>
  2258. <div>${escapeHtml(c.name)}</div>
  2259. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2260. </div>
  2261. </div>
  2262. </td>
  2263. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2264. <td class="py-2.5 px-4 font-sans">
  2265. <div class="flex items-center gap-1.5">
  2266. <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>
  2267. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2268. </div>
  2269. </td>
  2270. <td class="py-2.5 px-4">
  2271. <div class="space-y-1">
  2272. <div class="flex items-center flex-wrap gap-1">
  2273. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2274. ${localBadges}
  2275. </div>
  2276. <div class="flex items-center flex-wrap gap-1">
  2277. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2278. ${remoteBadges}
  2279. </div>
  2280. </div>
  2281. </td>
  2282. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2283. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2284. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2285. </div>
  2286. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2287. </td>
  2288. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2289. ${isEstablished ? `
  2290. <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>
  2291. ` : `
  2292. <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>
  2293. `}
  2294. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2295. ${c.disabled ? 'Enable' : 'Disable'}
  2296. </button>
  2297. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2298. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2299. </td>
  2300. `;
  2301. tbody.appendChild(tr);
  2302. });
  2303. }
  2304. } catch (err) {
  2305. console.error('Failed to load IPSec:', err);
  2306. }
  2307. }
  2308. function openAddIPSecModal() {
  2309. const modal = document.getElementById('ipsec-modal');
  2310. if (!modal) return;
  2311. const title = document.getElementById('ipsec-modal-title');
  2312. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2313. // Phase 1 Fields
  2314. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2315. const nameEl = document.getElementById('ipsec-modal-name');
  2316. if (nameEl) nameEl.readOnly = false;
  2317. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2318. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2319. safeSetVal('ipsec-modal-remotegw', '');
  2320. safeSetVal('ipsec-modal-localaddrs', '');
  2321. safeSetVal('ipsec-modal-comments', '');
  2322. safeSetVal('ipsec-modal-psk', '');
  2323. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2324. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2325. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2326. safeSetVal('ipsec-modal-localid', '');
  2327. safeSetVal('ipsec-modal-remoteid', '');
  2328. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2329. // Phase 2 Fields
  2330. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2331. safeSetVal('ipsec-modal-espkeylife', '28800');
  2332. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2333. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2334. safeSetChecked('ipsec-modal-autostart', true);
  2335. safeSetChecked('ipsec-modal-disabled', false);
  2336. // Clear & Populate default dynamic subnets
  2337. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2338. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2339. if (localContainer) {
  2340. localContainer.innerHTML = '';
  2341. addIpsecLocalSubnet('192.168.10.0/24');
  2342. }
  2343. if (remoteContainer) {
  2344. remoteContainer.innerHTML = '';
  2345. addIpsecRemoteSubnet('192.168.20.0/24');
  2346. }
  2347. switchIpsecModalTab('p1');
  2348. modal.classList.remove('hidden');
  2349. }
  2350. function openEditIPSecModal(name) {
  2351. const modal = document.getElementById('ipsec-modal');
  2352. if (!modal) return;
  2353. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2354. if (!conn) return;
  2355. const title = document.getElementById('ipsec-modal-title');
  2356. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2357. // Phase 1 Fields
  2358. safeSetVal('ipsec-modal-name', conn.name);
  2359. const nameEl = document.getElementById('ipsec-modal-name');
  2360. if (nameEl) nameEl.readOnly = true;
  2361. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2362. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2363. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2364. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2365. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2366. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2367. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2368. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2369. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2370. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2371. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2372. // Phase 2 Fields
  2373. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2374. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2375. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2376. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2377. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2378. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2379. // Populate dynamic subnets
  2380. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2381. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2382. if (localContainer) {
  2383. localContainer.innerHTML = '';
  2384. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2385. locals.forEach(s => addIpsecLocalSubnet(s));
  2386. }
  2387. if (remoteContainer) {
  2388. remoteContainer.innerHTML = '';
  2389. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2390. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2391. }
  2392. switchIpsecModalTab('p1');
  2393. modal.classList.remove('hidden');
  2394. }
  2395. function closeAddIPSecModal() {
  2396. const modal = document.getElementById('ipsec-modal');
  2397. if (modal) modal.classList.add('hidden');
  2398. }
  2399. async function submitSaveIPSec(e) {
  2400. if (e) e.preventDefault();
  2401. const name = safeGetVal('ipsec-modal-name').trim();
  2402. if (!name) {
  2403. showToast('Error', 'Tunnel name is required', 'error');
  2404. return;
  2405. }
  2406. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2407. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2408. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2409. const comments = safeGetVal('ipsec-modal-comments').trim();
  2410. const psk = safeGetVal('ipsec-modal-psk');
  2411. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2412. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2413. const localId = safeGetVal('ipsec-modal-localid').trim();
  2414. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2415. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2416. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2417. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2418. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2419. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2420. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2421. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2422. // Scrape dynamic local and remote subnets
  2423. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2424. const localSubnets = [];
  2425. localInputs.forEach(inp => {
  2426. const v = inp.value.trim();
  2427. if (v) localSubnets.push(v);
  2428. });
  2429. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2430. const remoteSubnets = [];
  2431. remoteInputs.forEach(inp => {
  2432. const v = inp.value.trim();
  2433. if (v) remoteSubnets.push(v);
  2434. });
  2435. try {
  2436. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2437. method: 'POST',
  2438. headers: { 'Content-Type': 'application/json' },
  2439. body: JSON.stringify({
  2440. name,
  2441. comment: comments,
  2442. ike_version: ikeVersion,
  2443. local_addrs: localAddrs,
  2444. remote_addrs: remotegw,
  2445. preshared_key: psk,
  2446. ike_proposals: ikeProposals,
  2447. ike_keylife: ikeKeylife,
  2448. local_id: localId,
  2449. remote_id: remoteId,
  2450. dpd: dpd,
  2451. phase2_name: phase2Name,
  2452. esp_proposals: espProposals,
  2453. esp_keylife: espKeylife,
  2454. pfs_group: pfsGroup,
  2455. pfs: pfsGroup !== 'none',
  2456. local_subnets: localSubnets,
  2457. remote_subnets: remoteSubnets,
  2458. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2459. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2460. auto_start: autostart,
  2461. disabled
  2462. })
  2463. });
  2464. if (res.ok) {
  2465. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2466. closeAddIPSecModal();
  2467. loadIPSec(false);
  2468. } else {
  2469. const err = await res.json();
  2470. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2471. }
  2472. } catch (err) {
  2473. showToast('Error', err.message, 'error');
  2474. }
  2475. }
  2476. async function startIPSecTunnel(name) {
  2477. try {
  2478. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2479. if (res.ok) {
  2480. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2481. setTimeout(() => loadIPSec(false), 2000);
  2482. }
  2483. } catch (err) {
  2484. showToast('Error', err.message, 'error');
  2485. }
  2486. }
  2487. async function stopIPSecTunnel(name) {
  2488. try {
  2489. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2490. if (res.ok) {
  2491. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2492. loadIPSec(false);
  2493. }
  2494. } catch (err) {
  2495. showToast('Error', err.message, 'error');
  2496. }
  2497. }
  2498. async function toggleIPSecState(name, enable) {
  2499. try {
  2500. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2501. method: 'POST',
  2502. headers: { 'Content-Type': 'application/json' },
  2503. body: JSON.stringify({ enabled: enable })
  2504. });
  2505. if (res.ok) {
  2506. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2507. loadIPSec(false);
  2508. }
  2509. } catch (err) {
  2510. showToast('Error', err.message, 'error');
  2511. }
  2512. }
  2513. async function deleteIPSecConn(name) {
  2514. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2515. try {
  2516. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2517. if (res.ok) {
  2518. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2519. loadIPSec(false);
  2520. fetchData(false);
  2521. }
  2522. } catch (err) {
  2523. showToast('Error', err.message, 'error');
  2524. }
  2525. }
  2526. // ======================== L2TP Multi-Instance ========================
  2527. async function loadL2TP(populateInputs = true) {
  2528. try {
  2529. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2530. await fetchPPPProfilesList();
  2531. }
  2532. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2533. const list = await res.json();
  2534. state.l2tpList = Array.isArray(list) ? list : [];
  2535. const badge = document.getElementById('l2tp-count-badge');
  2536. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2537. const tbody = document.getElementById('l2tp-table-body');
  2538. const empty = document.getElementById('l2tp-empty');
  2539. if (!tbody) return;
  2540. tbody.innerHTML = '';
  2541. if (state.l2tpList.length === 0) {
  2542. if (empty) empty.classList.remove('hidden');
  2543. } else {
  2544. if (empty) empty.classList.add('hidden');
  2545. state.l2tpList.forEach(inst => {
  2546. const tr = document.createElement('tr');
  2547. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2548. tr.innerHTML = `
  2549. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2550. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2551. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2552. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2553. <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>
  2554. <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>
  2555. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2556. <td class="py-2.5 px-3 text-center">
  2557. <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'}">
  2558. ${inst.default_route ? 'Yes' : 'No'}
  2559. </span>
  2560. </td>
  2561. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2562. ${inst.running ? `
  2563. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2564. ` : `
  2565. <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>
  2566. `}
  2567. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2568. ${inst.disabled ? 'Enable' : 'Disable'}
  2569. </button>
  2570. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2571. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2572. </td>
  2573. `;
  2574. tbody.appendChild(tr);
  2575. });
  2576. }
  2577. } catch (err) {
  2578. console.error('Failed to load L2TP:', err);
  2579. }
  2580. }
  2581. async function openAddL2TPModal() {
  2582. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2583. await fetchPPPProfilesList();
  2584. }
  2585. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2586. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2587. document.getElementById('l2tp-modal-name').readOnly = false;
  2588. document.getElementById('l2tp-modal-server').value = '';
  2589. document.getElementById('l2tp-modal-user').value = '';
  2590. document.getElementById('l2tp-modal-pass').value = '';
  2591. document.getElementById('l2tp-modal-ipsec').value = '';
  2592. document.getElementById('l2tp-modal-defroute').checked = true;
  2593. document.getElementById('l2tp-modal-disabled').checked = false;
  2594. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2595. document.getElementById('l2tp-modal').classList.remove('hidden');
  2596. }
  2597. async function openEditL2TPModal(name) {
  2598. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2599. await fetchPPPProfilesList();
  2600. }
  2601. const inst = (state.l2tpList || []).find(i => i.name === name);
  2602. if (!inst) return;
  2603. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2604. document.getElementById('l2tp-modal-name').value = inst.name;
  2605. document.getElementById('l2tp-modal-name').readOnly = true;
  2606. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2607. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2608. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2609. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2610. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2611. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2612. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2613. document.getElementById('l2tp-modal').classList.remove('hidden');
  2614. }
  2615. function closeL2TPModal() {
  2616. document.getElementById('l2tp-modal').classList.add('hidden');
  2617. }
  2618. async function submitSaveL2TP(e) {
  2619. e.preventDefault();
  2620. const name = document.getElementById('l2tp-modal-name').value.trim();
  2621. const server = document.getElementById('l2tp-modal-server').value.trim();
  2622. const user = document.getElementById('l2tp-modal-user').value.trim();
  2623. const pass = document.getElementById('l2tp-modal-pass').value;
  2624. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2625. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2626. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2627. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2628. try {
  2629. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2630. method: 'POST',
  2631. headers: { 'Content-Type': 'application/json' },
  2632. body: JSON.stringify({
  2633. name,
  2634. connect_to: server,
  2635. username: user,
  2636. password: pass,
  2637. profile: profile,
  2638. ipsec_secret: ipsec,
  2639. default_route: defRoute,
  2640. disabled
  2641. })
  2642. });
  2643. if (res.ok) {
  2644. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2645. closeL2TPModal();
  2646. loadL2TP(false);
  2647. fetchData(false);
  2648. }
  2649. } catch (err) {
  2650. showToast('Error', err.message, 'error');
  2651. }
  2652. }
  2653. async function connectL2TPInstance(name) {
  2654. try {
  2655. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2656. if (res.ok) {
  2657. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2658. setTimeout(() => loadL2TP(false), 2000);
  2659. }
  2660. } catch (err) {
  2661. showToast('Error', err.message, 'error');
  2662. }
  2663. }
  2664. async function disconnectL2TPInstance(name) {
  2665. try {
  2666. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2667. if (res.ok) {
  2668. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2669. loadL2TP(false);
  2670. }
  2671. } catch (err) {
  2672. showToast('Error', err.message, 'error');
  2673. }
  2674. }
  2675. async function toggleL2TPState(name, enable) {
  2676. try {
  2677. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2678. method: 'POST',
  2679. headers: { 'Content-Type': 'application/json' },
  2680. body: JSON.stringify({ enabled: enable })
  2681. });
  2682. if (res.ok) {
  2683. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2684. loadL2TP(false);
  2685. }
  2686. } catch (err) {
  2687. showToast('Error', err.message, 'error');
  2688. }
  2689. }
  2690. async function deleteL2TPInstance(name) {
  2691. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2692. try {
  2693. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2694. if (res.ok) {
  2695. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2696. loadL2TP(false);
  2697. fetchData(false);
  2698. }
  2699. } catch (err) {
  2700. showToast('Error', err.message, 'error');
  2701. }
  2702. }
  2703. // ======================== PPTP Multi-Instance ========================
  2704. async function loadPPTP(populateInputs = true) {
  2705. try {
  2706. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2707. await fetchPPPProfilesList();
  2708. }
  2709. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2710. const list = await res.json();
  2711. state.pptpList = Array.isArray(list) ? list : [];
  2712. const badge = document.getElementById('pptp-count-badge');
  2713. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2714. const tbody = document.getElementById('pptp-table-body');
  2715. const empty = document.getElementById('pptp-empty');
  2716. if (!tbody) return;
  2717. tbody.innerHTML = '';
  2718. if (state.pptpList.length === 0) {
  2719. if (empty) empty.classList.remove('hidden');
  2720. } else {
  2721. if (empty) empty.classList.add('hidden');
  2722. state.pptpList.forEach(inst => {
  2723. const tr = document.createElement('tr');
  2724. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2725. tr.innerHTML = `
  2726. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2727. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2728. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2729. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2730. <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>
  2731. <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>
  2732. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2733. <td class="py-2.5 px-3 text-center">
  2734. <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'}">
  2735. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2736. </span>
  2737. </td>
  2738. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2739. ${inst.running ? `
  2740. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2741. ` : `
  2742. <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>
  2743. `}
  2744. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2745. ${inst.disabled ? 'Enable' : 'Disable'}
  2746. </button>
  2747. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2748. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2749. </td>
  2750. `;
  2751. tbody.appendChild(tr);
  2752. });
  2753. }
  2754. } catch (err) {
  2755. console.error('Failed to load PPTP:', err);
  2756. }
  2757. }
  2758. async function openAddPPTPModal() {
  2759. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2760. await fetchPPPProfilesList();
  2761. }
  2762. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2763. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2764. document.getElementById('pptp-modal-name').readOnly = false;
  2765. document.getElementById('pptp-modal-server').value = '';
  2766. document.getElementById('pptp-modal-user').value = '';
  2767. document.getElementById('pptp-modal-pass').value = '';
  2768. document.getElementById('pptp-modal-mppe').checked = true;
  2769. document.getElementById('pptp-modal-defroute').checked = true;
  2770. document.getElementById('pptp-modal-disabled').checked = false;
  2771. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2772. document.getElementById('pptp-modal').classList.remove('hidden');
  2773. }
  2774. async function openEditPPTPModal(name) {
  2775. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2776. await fetchPPPProfilesList();
  2777. }
  2778. const inst = (state.pptpList || []).find(i => i.name === name);
  2779. if (!inst) return;
  2780. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2781. document.getElementById('pptp-modal-name').value = inst.name;
  2782. document.getElementById('pptp-modal-name').readOnly = true;
  2783. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2784. document.getElementById('pptp-modal-user').value = inst.username || '';
  2785. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2786. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2787. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2788. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2789. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2790. document.getElementById('pptp-modal').classList.remove('hidden');
  2791. }
  2792. function closePPTPModal() {
  2793. document.getElementById('pptp-modal').classList.add('hidden');
  2794. }
  2795. async function submitSavePPTP(e) {
  2796. e.preventDefault();
  2797. const name = document.getElementById('pptp-modal-name').value.trim();
  2798. const server = document.getElementById('pptp-modal-server').value.trim();
  2799. const user = document.getElementById('pptp-modal-user').value.trim();
  2800. const pass = document.getElementById('pptp-modal-pass').value;
  2801. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2802. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2803. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2804. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2805. try {
  2806. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2807. method: 'POST',
  2808. headers: { 'Content-Type': 'application/json' },
  2809. body: JSON.stringify({
  2810. name,
  2811. connect_to: server,
  2812. username: user,
  2813. password: pass,
  2814. profile: profile,
  2815. require_mppe: mppe,
  2816. default_route: defRoute,
  2817. auto_reconnect: true,
  2818. disabled
  2819. })
  2820. });
  2821. if (res.ok) {
  2822. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2823. closePPTPModal();
  2824. loadPPTP(false);
  2825. fetchData(false);
  2826. }
  2827. } catch (err) {
  2828. showToast('Error', err.message, 'error');
  2829. }
  2830. }
  2831. async function connectPPTPInstance(name) {
  2832. try {
  2833. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2834. if (res.ok) {
  2835. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2836. setTimeout(() => loadPPTP(false), 2000);
  2837. }
  2838. } catch (err) {
  2839. showToast('Error', err.message, 'error');
  2840. }
  2841. }
  2842. async function disconnectPPTPInstance(name) {
  2843. try {
  2844. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2845. if (res.ok) {
  2846. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2847. loadPPTP(false);
  2848. }
  2849. } catch (err) {
  2850. showToast('Error', err.message, 'error');
  2851. }
  2852. }
  2853. async function togglePPTPState(name, enable) {
  2854. try {
  2855. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2856. method: 'POST',
  2857. headers: { 'Content-Type': 'application/json' },
  2858. body: JSON.stringify({ enabled: enable })
  2859. });
  2860. if (res.ok) {
  2861. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2862. loadPPTP(false);
  2863. }
  2864. } catch (err) {
  2865. showToast('Error', err.message, 'error');
  2866. }
  2867. }
  2868. async function deletePPTPInstance(name) {
  2869. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2872. if (res.ok) {
  2873. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2874. loadPPTP(false);
  2875. fetchData(false);
  2876. }
  2877. } catch (err) {
  2878. showToast('Error', err.message, 'error');
  2879. }
  2880. }
  2881. // ---------------- Modal & Helper Functions ----------------
  2882. function openVlanModal(defaultParent = '') {
  2883. const select = document.getElementById('vlan-parent');
  2884. select.innerHTML = '';
  2885. const allIfaces = state.interfaces || [];
  2886. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2887. if (eligible.length === 0) {
  2888. const opt = document.createElement('option');
  2889. opt.value = '';
  2890. opt.innerText = 'No VLAN-capable interfaces available';
  2891. select.appendChild(opt);
  2892. } else {
  2893. eligible.forEach(i => {
  2894. const opt = document.createElement('option');
  2895. opt.value = i.name;
  2896. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2897. if (i.name === defaultParent) opt.selected = true;
  2898. select.appendChild(opt);
  2899. });
  2900. }
  2901. document.getElementById('vlan-id').value = '';
  2902. document.getElementById('vlan-name').value = '';
  2903. document.getElementById('vlan-ip').value = '';
  2904. document.getElementById('vlan-desc').value = '';
  2905. populateRoleSelects('LAN');
  2906. autoSuggestVlanName();
  2907. document.getElementById('vlan-modal').classList.remove('hidden');
  2908. }
  2909. function closeVlanModal() {
  2910. document.getElementById('vlan-modal').classList.add('hidden');
  2911. }
  2912. function autoSuggestVlanName() {
  2913. const parent = document.getElementById('vlan-parent').value;
  2914. if (!parent) return;
  2915. const id = document.getElementById('vlan-id').value;
  2916. const nameInput = document.getElementById('vlan-name');
  2917. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2918. }
  2919. function setSubnetPreset(cidr) {
  2920. const ipInput = document.getElementById('vlan-ip');
  2921. const id = document.getElementById('vlan-id').value || '10';
  2922. ipInput.value = `192.168.${id}.1${cidr}`;
  2923. }
  2924. async function submitCreateVlan(e) {
  2925. e.preventDefault();
  2926. const btn = document.getElementById('vlan-submit-btn');
  2927. btn.disabled = true;
  2928. btn.innerText = 'Creating...';
  2929. const parent = document.getElementById('vlan-parent').value;
  2930. if (!parent) {
  2931. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2932. btn.disabled = false;
  2933. btn.innerText = 'Create VLAN';
  2934. return;
  2935. }
  2936. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2937. const name = document.getElementById('vlan-name').value.trim();
  2938. const ip = document.getElementById('vlan-ip').value.trim();
  2939. const role = document.getElementById('vlan-role').value;
  2940. const desc = document.getElementById('vlan-desc').value.trim();
  2941. try {
  2942. const res = await fetch(`${API_BASE}/vlans`, {
  2943. method: 'POST',
  2944. headers: { 'Content-Type': 'application/json' },
  2945. body: JSON.stringify({
  2946. parent_name: parent,
  2947. vlan_id: id,
  2948. name: name,
  2949. ip_address: ip,
  2950. role: role,
  2951. description: desc,
  2952. mtu: 1500,
  2953. auto_up: true
  2954. })
  2955. });
  2956. const data = await res.json();
  2957. if (res.ok) {
  2958. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2959. state.expandedParents.add(parent);
  2960. closeVlanModal();
  2961. await fetchData(true);
  2962. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2963. } else {
  2964. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2965. }
  2966. } catch (err) {
  2967. showToast('Error', err.message, 'error');
  2968. } finally {
  2969. btn.disabled = false;
  2970. btn.innerText = 'Create VLAN';
  2971. }
  2972. }
  2973. async function confirmDeleteVlan(name) {
  2974. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2975. try {
  2976. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2977. if (res.ok) {
  2978. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2979. closeIfaceModal();
  2980. fetchData(true);
  2981. }
  2982. } catch (err) {
  2983. showToast('Error', err.message, 'error');
  2984. }
  2985. }
  2986. function openIfaceModal(name) {
  2987. const iface = (state.interfaces || []).find(i => i.name === name);
  2988. if (!iface) return;
  2989. state.currentModalIface = iface.name;
  2990. document.getElementById('modal-iface-name').innerText = iface.name;
  2991. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2992. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2993. populateRoleSelects(iface.role || 'LAN');
  2994. document.getElementById('modal-iface-desc').value = iface.description || '';
  2995. const nameInput = document.getElementById('modal-iface-new-name');
  2996. const renameBtn = document.getElementById('modal-btn-rename');
  2997. const renameHelp = document.getElementById('modal-iface-rename-help');
  2998. if (nameInput) {
  2999. nameInput.value = iface.name;
  3000. if (iface.name === 'lo' || iface.type === 'loopback') {
  3001. nameInput.disabled = true;
  3002. if (renameBtn) renameBtn.disabled = true;
  3003. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3004. } else {
  3005. nameInput.disabled = false;
  3006. if (renameBtn) renameBtn.disabled = false;
  3007. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3008. }
  3009. }
  3010. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3011. if (iface.is_vlan) {
  3012. delBtn.classList.remove('hidden');
  3013. } else {
  3014. delBtn.classList.add('hidden');
  3015. }
  3016. renderModalIPs(iface);
  3017. document.getElementById('iface-modal').classList.remove('hidden');
  3018. }
  3019. function renderModalIPs(iface) {
  3020. const container = document.getElementById('modal-ip-list');
  3021. container.innerHTML = '';
  3022. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3023. if (addrs.length === 0) {
  3024. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3025. return;
  3026. }
  3027. addrs.forEach(addr => {
  3028. const row = document.createElement('div');
  3029. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3030. row.innerHTML = `
  3031. <span class="text-white">${addr}</span>
  3032. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3033. `;
  3034. container.appendChild(row);
  3035. });
  3036. }
  3037. function closeIfaceModal() {
  3038. document.getElementById('iface-modal').classList.add('hidden');
  3039. state.currentModalIface = null;
  3040. }
  3041. async function setIfaceState(name, newState) {
  3042. const target = name || state.currentModalIface;
  3043. if (!target) return;
  3044. await toggleInterfaceState(target, newState);
  3045. const updated = (state.interfaces || []).find(i => i.name === target);
  3046. if (updated) openIfaceModal(target);
  3047. }
  3048. async function applyMTU() {
  3049. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3050. try {
  3051. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3052. method: 'POST',
  3053. headers: { 'Content-Type': 'application/json' },
  3054. body: JSON.stringify({ mtu })
  3055. });
  3056. if (res.ok) {
  3057. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3058. fetchData(false);
  3059. }
  3060. } catch (err) {
  3061. showToast('Error', err.message, 'error');
  3062. }
  3063. }
  3064. async function addInterfaceIP() {
  3065. const ip = document.getElementById('modal-new-ip').value.trim();
  3066. if (!ip) return;
  3067. try {
  3068. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3069. method: 'POST',
  3070. headers: { 'Content-Type': 'application/json' },
  3071. body: JSON.stringify({ ip })
  3072. });
  3073. if (res.ok) {
  3074. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3075. document.getElementById('modal-new-ip').value = '';
  3076. await fetchData(false);
  3077. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3078. if (iface) renderModalIPs(iface);
  3079. } else {
  3080. const err = await res.json();
  3081. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3082. }
  3083. } catch (err) {
  3084. showToast('Error', err.message, 'error');
  3085. }
  3086. }
  3087. async function removeInterfaceIP(ip) {
  3088. if (!confirm(`Remove IP ${ip}?`)) return;
  3089. try {
  3090. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3091. method: 'DELETE',
  3092. headers: { 'Content-Type': 'application/json' },
  3093. body: JSON.stringify({ ip })
  3094. });
  3095. if (res.ok) {
  3096. showToast('IP Removed', `Removed ${ip}`, 'success');
  3097. await fetchData(false);
  3098. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3099. if (iface) renderModalIPs(iface);
  3100. }
  3101. } catch (err) {
  3102. showToast('Error', err.message, 'error');
  3103. }
  3104. }
  3105. async function renameInterface() {
  3106. const oldName = state.currentModalIface;
  3107. const newNameInput = document.getElementById('modal-iface-new-name');
  3108. const newName = (newNameInput?.value || '').trim();
  3109. if (!oldName) return;
  3110. if (!newName) {
  3111. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3112. return;
  3113. }
  3114. if (newName === oldName) {
  3115. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3116. return;
  3117. }
  3118. if (newName.length > 15) {
  3119. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3120. return;
  3121. }
  3122. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3123. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3124. return;
  3125. }
  3126. const renameBtn = document.getElementById('modal-btn-rename');
  3127. if (renameBtn) {
  3128. renameBtn.disabled = true;
  3129. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3130. }
  3131. try {
  3132. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3133. method: 'POST',
  3134. headers: { 'Content-Type': 'application/json' },
  3135. body: JSON.stringify({ new_name: newName })
  3136. });
  3137. const data = await res.json();
  3138. if (!res.ok) {
  3139. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3140. return;
  3141. }
  3142. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3143. state.currentModalIface = newName;
  3144. document.getElementById('modal-iface-name').innerText = newName;
  3145. // Refresh application state
  3146. await fetchData(false);
  3147. const updated = (state.interfaces || []).find(i => i.name === newName);
  3148. if (updated) {
  3149. openIfaceModal(newName);
  3150. } else {
  3151. closeIfaceModal();
  3152. }
  3153. } catch (err) {
  3154. showToast('Error', err.message, 'error');
  3155. } finally {
  3156. if (renameBtn) {
  3157. renameBtn.disabled = false;
  3158. renameBtn.innerHTML = `
  3159. <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>
  3160. <span>Rename</span>
  3161. `;
  3162. }
  3163. }
  3164. }
  3165. async function saveInterfaceMetadata() {
  3166. const oldName = state.currentModalIface;
  3167. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3168. const role = document.getElementById('modal-iface-role').value;
  3169. const desc = document.getElementById('modal-iface-desc').value.trim();
  3170. let targetName = oldName;
  3171. // If user changed the name before clicking Save Changes, execute rename first
  3172. if (newName && newName !== oldName && oldName !== 'lo') {
  3173. try {
  3174. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3175. method: 'POST',
  3176. headers: { 'Content-Type': 'application/json' },
  3177. body: JSON.stringify({ new_name: newName })
  3178. });
  3179. const data = await renameRes.json();
  3180. if (!renameRes.ok) {
  3181. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3182. return;
  3183. }
  3184. targetName = newName;
  3185. state.currentModalIface = newName;
  3186. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3187. } catch (err) {
  3188. showToast('Error', err.message, 'error');
  3189. return;
  3190. }
  3191. }
  3192. try {
  3193. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3194. method: 'POST',
  3195. headers: { 'Content-Type': 'application/json' },
  3196. body: JSON.stringify({ role, description: desc })
  3197. });
  3198. if (res.ok) {
  3199. showToast('Saved', 'Interface configuration updated', 'success');
  3200. closeIfaceModal();
  3201. fetchData(false);
  3202. } else {
  3203. const err = await res.json();
  3204. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3205. }
  3206. } catch (err) {
  3207. showToast('Error', err.message, 'error');
  3208. }
  3209. }
  3210. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3211. state.fwSubTab = 'filter';
  3212. state.routesSubTab = 'routes';
  3213. function renderRuleFlag(disabled, hasComment) {
  3214. let flags = '';
  3215. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3216. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3217. return flags || '<span class="text-slate-600">-</span>';
  3218. }
  3219. function renderActionBadge(action) {
  3220. const act = (action || '').toLowerCase();
  3221. let color = 'bg-slate-800 text-slate-300';
  3222. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3223. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3224. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3225. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3226. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3227. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3228. }
  3229. function switchFWSubTab(tab) {
  3230. state.fwSubTab = tab;
  3231. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3232. tabs.forEach(t => {
  3233. const panel = document.getElementById(`fw-subtab-${t}`);
  3234. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3235. if (panel) {
  3236. if (t === tab) panel.classList.remove('hidden');
  3237. else panel.classList.add('hidden');
  3238. }
  3239. if (btn) {
  3240. if (t === tab) {
  3241. 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';
  3242. } else {
  3243. 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';
  3244. }
  3245. }
  3246. });
  3247. const addBtn = document.getElementById('fw-primary-add-btn');
  3248. if (addBtn) {
  3249. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3250. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3251. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3252. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3253. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3254. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3255. }
  3256. if (tab === 'geo') loadGeoIP();
  3257. if (tab === 'connections') loadConnections();
  3258. setTimeout(initTableSorting, 50);
  3259. }
  3260. function openCurrentFWModal() {
  3261. if (state.fwSubTab === 'filter') openAddFilterModal();
  3262. else if (state.fwSubTab === 'nat') openAddNATModal();
  3263. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3264. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3265. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3266. else if (state.fwSubTab === 'connections') loadConnections();
  3267. }
  3268. async function loadFirewall(populateDropdowns = true) {
  3269. try {
  3270. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3271. fetch(`${API_BASE}/firewall/summary`),
  3272. fetch(`${API_BASE}/firewall/filter`),
  3273. fetch(`${API_BASE}/firewall/nat`),
  3274. fetch(`${API_BASE}/firewall/mangle`),
  3275. fetch(`${API_BASE}/firewall/address-lists`),
  3276. fetch(`${API_BASE}/firewall/geoip/status`),
  3277. fetch(`${API_BASE}/firewall/geoip/countries`)
  3278. ]);
  3279. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3280. if (filterRes.ok) state.filterRules = await filterRes.json();
  3281. if (natRes.ok) state.natRules = await natRes.json();
  3282. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3283. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3284. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3285. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3286. // Badges
  3287. const bFilter = document.getElementById('fw-badge-filter');
  3288. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3289. const bNat = document.getElementById('fw-badge-nat');
  3290. if (bNat) bNat.innerText = (state.natRules || []).length;
  3291. const bMangle = document.getElementById('fw-badge-mangle');
  3292. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3293. const bAddr = document.getElementById('fw-badge-addrlist');
  3294. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3295. const bGeo = document.getElementById('fw-badge-geo');
  3296. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3297. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3298. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3299. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3300. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3301. const tbodyFilter = document.getElementById('filter-rules-table-body');
  3302. if (tbodyFilter && (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter)) {
  3303. tbodyFilter.dataset.sig = sigFilter;
  3304. renderFilterRules();
  3305. }
  3306. const tbodyNat = document.getElementById('nat-rules-table-body');
  3307. if (tbodyNat && (populateDropdowns || tbodyNat.dataset.sig !== sigNat)) {
  3308. tbodyNat.dataset.sig = sigNat;
  3309. renderNATRules();
  3310. }
  3311. const tbodyMangle = document.getElementById('mangle-rules-table-body');
  3312. if (tbodyMangle && (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle)) {
  3313. tbodyMangle.dataset.sig = sigMangle;
  3314. renderMangleRules();
  3315. }
  3316. const tbodyAddr = document.getElementById('addr-list-table-body');
  3317. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3318. tbodyAddr.dataset.sig = sigAddr;
  3319. renderAddressLists();
  3320. }
  3321. renderGeoCountries();
  3322. if (state.fwSubTab === 'connections') {
  3323. loadConnections();
  3324. }
  3325. } catch (err) {
  3326. console.error('Failed to load firewall:', err);
  3327. }
  3328. }
  3329. // ----------------- Filter Rules -----------------
  3330. function renderFilterRules() {
  3331. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3332. const tbody = document.getElementById('filter-table-body');
  3333. const empty = document.getElementById('filter-empty');
  3334. if (!tbody) return;
  3335. tbody.innerHTML = '';
  3336. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3337. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3338. if (rules.length === 0) {
  3339. empty?.classList.remove('hidden');
  3340. return;
  3341. }
  3342. empty?.classList.add('hidden');
  3343. rules.forEach((r, idx) => {
  3344. const tr = document.createElement('tr');
  3345. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3346. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3347. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3348. let actionExtra = '';
  3349. if (r.action === 'reject') {
  3350. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3351. } else if (r.action === 'jump') {
  3352. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3353. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3354. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3355. } else if (r.action === 'log' && r.log_prefix) {
  3356. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3357. }
  3358. tr.innerHTML = `
  3359. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3360. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3361. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3362. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3363. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3364. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3365. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3366. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3367. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3368. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3369. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3370. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3371. </td>
  3372. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3373. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3374. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3375. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3376. <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>
  3377. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3378. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3379. </td>
  3380. `;
  3381. tbody.appendChild(tr);
  3382. });
  3383. }
  3384. function formatTarget(addr, list, geo) {
  3385. const parts = [];
  3386. if (addr) parts.push(`<span>${addr}</span>`);
  3387. if (list) {
  3388. const inv = list.startsWith('!') ? '!' : '';
  3389. const clean = list.replace(/^!/, '');
  3390. 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>`);
  3391. }
  3392. if (geo) {
  3393. const inv = geo.startsWith('!') ? '!' : '';
  3394. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3395. 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>`);
  3396. }
  3397. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3398. return parts.join(' ');
  3399. }
  3400. function populateInterfaceSelect(selectId, currentVal = '') {
  3401. const sel = document.getElementById(selectId);
  3402. if (!sel) return;
  3403. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3404. (state.interfaces || []).forEach(i => {
  3405. const opt = document.createElement('option');
  3406. opt.value = i.name;
  3407. opt.innerText = `${i.name} (${i.role || i.type})`;
  3408. if (i.name === currentVal) opt.selected = true;
  3409. sel.appendChild(opt);
  3410. });
  3411. }
  3412. function populateAddressListSelect(selectId, currentVal = '') {
  3413. const sel = document.getElementById(selectId);
  3414. if (!sel) return;
  3415. sel.innerHTML = '<option value="">(None)</option>';
  3416. const cleanVal = (currentVal || '').replace(/^!/, '');
  3417. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3418. customNames.forEach(name => {
  3419. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3420. const opt = document.createElement('option');
  3421. opt.value = name;
  3422. opt.innerText = `${name} (${count} entries)`;
  3423. if (name === cleanVal) opt.selected = true;
  3424. sel.appendChild(opt);
  3425. });
  3426. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3427. const opt = document.createElement('option');
  3428. opt.value = cleanVal;
  3429. opt.innerText = cleanVal;
  3430. opt.selected = true;
  3431. sel.appendChild(opt);
  3432. }
  3433. populateCommonAddrListDatalist();
  3434. }
  3435. function populateCommonAddrListDatalist() {
  3436. const dl = document.getElementById('fw-addrlist-datalist');
  3437. if (!dl) return;
  3438. dl.innerHTML = '';
  3439. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3440. names.forEach(name => {
  3441. const opt = document.createElement('option');
  3442. opt.value = name;
  3443. dl.appendChild(opt);
  3444. });
  3445. }
  3446. function populateGeoIPSelect(selectId, currentVal = '') {
  3447. const sel = document.getElementById(selectId);
  3448. if (!sel) return;
  3449. sel.innerHTML = '<option value="">(None)</option>';
  3450. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3451. // Presets optgroup
  3452. const grpPresets = document.createElement('optgroup');
  3453. grpPresets.label = '⚡ Regional Presets';
  3454. const presets = [
  3455. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3456. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3457. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3458. ];
  3459. presets.forEach(p => {
  3460. const opt = document.createElement('option');
  3461. opt.value = p.code;
  3462. opt.innerText = p.label;
  3463. if (p.code === cleanVal) opt.selected = true;
  3464. grpPresets.appendChild(opt);
  3465. });
  3466. sel.appendChild(grpPresets);
  3467. // All Countries optgroup
  3468. const grpCountries = document.createElement('optgroup');
  3469. grpCountries.label = '🌍 All Countries';
  3470. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3471. countries.forEach(c => {
  3472. const opt = document.createElement('option');
  3473. opt.value = c.code;
  3474. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3475. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3476. if (c.code === cleanVal) opt.selected = true;
  3477. grpCountries.appendChild(opt);
  3478. });
  3479. sel.appendChild(grpCountries);
  3480. }
  3481. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3482. function switchFwRuleTab(tab) {
  3483. state.activeFwRuleTab = tab;
  3484. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3485. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3486. btn.classList.add('text-slate-400', 'border-transparent');
  3487. });
  3488. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3489. if (activeBtn) {
  3490. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3491. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3492. }
  3493. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3494. const activePane = document.getElementById(`fw-pane-${tab}`);
  3495. if (activePane) activePane.classList.remove('hidden');
  3496. if (tab === 'statistics') {
  3497. startFwStatPolling();
  3498. } else {
  3499. stopFwStatPolling();
  3500. }
  3501. }
  3502. function toggleFwField(fieldKey, expand) {
  3503. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3504. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3505. if (!plusBtn || !fieldBox) return;
  3506. if (expand) {
  3507. plusBtn.classList.add('hidden');
  3508. fieldBox.classList.remove('hidden');
  3509. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3510. if (valInput) valInput.focus();
  3511. } else {
  3512. fieldBox.classList.add('hidden');
  3513. plusBtn.classList.remove('hidden');
  3514. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3515. if (valInput) {
  3516. if (valInput.tagName === 'SELECT') {
  3517. valInput.selectedIndex = 0;
  3518. } else {
  3519. valInput.value = '';
  3520. }
  3521. }
  3522. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3523. if (invInput) invInput.checked = false;
  3524. if (fieldKey === 'cs') {
  3525. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3526. const el = document.getElementById(id);
  3527. if (el) el.checked = false;
  3528. });
  3529. }
  3530. if (fieldKey === 'natstate') {
  3531. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3532. const el = document.getElementById(id);
  3533. if (el) el.checked = false;
  3534. });
  3535. }
  3536. if (fieldKey === 'days') {
  3537. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3538. const el = document.getElementById(`fw-day-${d}`);
  3539. if (el) el.checked = true;
  3540. });
  3541. }
  3542. }
  3543. }
  3544. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3545. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3546. toggleFwField(fieldKey, true);
  3547. let strVal = String(value);
  3548. if (hasInvert) {
  3549. const inv = strVal.startsWith('!');
  3550. if (inv) strVal = strVal.slice(1);
  3551. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3552. if (invEl) invEl.checked = inv;
  3553. }
  3554. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3555. if (valEl) valEl.value = strVal;
  3556. } else {
  3557. toggleFwField(fieldKey, false);
  3558. }
  3559. }
  3560. function getFwFieldVal(fieldKey, hasInvert = false) {
  3561. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3562. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3563. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3564. let v = valEl ? valEl.value.trim() : '';
  3565. if (!v) return '';
  3566. if (hasInvert) {
  3567. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3568. if (invEl && invEl.checked) {
  3569. v = '!' + v.replace(/^!/, '');
  3570. }
  3571. }
  3572. return v;
  3573. }
  3574. function toggleMaximizeFilterModal() {
  3575. const win = document.getElementById('filter-modal-window');
  3576. if (!win) return;
  3577. if (win.classList.contains('max-w-[720px]')) {
  3578. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3579. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3580. } else {
  3581. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3582. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3583. }
  3584. }
  3585. function openAddFilterModal() {
  3586. switchFwRuleTab('general');
  3587. const badge = document.getElementById('fw-modal-badge');
  3588. if (badge) badge.innerText = 'New...';
  3589. document.getElementById('filter-modal-id').value = '';
  3590. document.getElementById('filter-modal-enabled').checked = true;
  3591. document.getElementById('filter-modal-comment').value = '';
  3592. document.getElementById('filter-modal-chain').value = 'forward';
  3593. document.getElementById('filter-modal-action').value = 'accept';
  3594. document.getElementById('filter-modal-log').checked = false;
  3595. populateInterfaceSelect('fw-val-iniface');
  3596. populateInterfaceSelect('fw-val-outiface');
  3597. populateAddressListSelect('fw-val-srclist');
  3598. populateAddressListSelect('fw-val-dstlist');
  3599. populateGeoIPSelect('fw-val-srcgeo');
  3600. populateGeoIPSelect('fw-val-dstgeo');
  3601. const allFieldKeys = [
  3602. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3603. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3604. 'routingmark', 'conntype', 'cs', 'natstate',
  3605. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3606. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3607. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3608. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3609. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3610. ];
  3611. allFieldKeys.forEach(k => toggleFwField(k, false));
  3612. resetCurrentRuleCounters();
  3613. toggleFilterActionFields();
  3614. document.getElementById('filter-modal').classList.remove('hidden');
  3615. }
  3616. function openEditFilterModal(id) {
  3617. const r = (state.filterRules || []).find(rule => rule.id === id);
  3618. if (!r) return;
  3619. switchFwRuleTab('general');
  3620. const badge = document.getElementById('fw-modal-badge');
  3621. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3622. document.getElementById('filter-modal-id').value = r.id;
  3623. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3624. document.getElementById('filter-modal-comment').value = r.comment || '';
  3625. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3626. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3627. document.getElementById('filter-modal-log').checked = !!r.log;
  3628. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3629. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3630. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3631. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3632. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3633. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3634. setFwFieldVal('src', r.src_address, true);
  3635. setFwFieldVal('dst', r.dst_address, true);
  3636. setFwFieldVal('srclist', r.src_address_list, true);
  3637. setFwFieldVal('dstlist', r.dst_address_list, true);
  3638. setFwFieldVal('srcgeo', r.src_geoip, true);
  3639. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3640. if (r.protocol && r.protocol !== 'all') {
  3641. setFwFieldVal('proto', r.protocol, true);
  3642. } else {
  3643. toggleFwField('proto', false);
  3644. }
  3645. setFwFieldVal('sport', r.src_port, true);
  3646. setFwFieldVal('dport', r.dst_port, true);
  3647. setFwFieldVal('anyport', r.any_port, true);
  3648. setFwFieldVal('iniface', r.in_interface, true);
  3649. setFwFieldVal('outiface', r.out_interface, true);
  3650. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3651. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3652. setFwFieldVal('pktmark', r.packet_mark, true);
  3653. setFwFieldVal('connmark', r.connection_mark, true);
  3654. setFwFieldVal('routingmark', r.routing_mark, true);
  3655. setFwFieldVal('conntype', r.connection_type, false);
  3656. const states = r.connection_state || [];
  3657. if (states.length > 0) {
  3658. toggleFwField('cs', true);
  3659. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3660. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3661. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3662. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3663. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3664. } else {
  3665. toggleFwField('cs', false);
  3666. }
  3667. const natStates = r.connection_nat_state || [];
  3668. if (natStates.length > 0) {
  3669. toggleFwField('natstate', true);
  3670. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3671. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3672. } else {
  3673. toggleFwField('natstate', false);
  3674. }
  3675. // Advanced tab fields
  3676. setFwFieldVal('layer7', r.layer7_protocol, false);
  3677. setFwFieldVal('content', r.content, false);
  3678. setFwFieldVal('connbytes', r.connection_bytes, false);
  3679. setFwFieldVal('connrate', r.connection_rate, false);
  3680. setFwFieldVal('pcc', r.pcc, false);
  3681. setFwFieldVal('srcmac', r.src_mac_address, true);
  3682. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3683. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3684. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3685. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3686. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3687. setFwFieldVal('tlshost', r.tls_host, false);
  3688. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3689. setFwFieldVal('priority', r.priority, false);
  3690. setFwFieldVal('dscp', r.dscp, false);
  3691. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3692. if (r.tos) {
  3693. const tosEl = document.getElementById('fw-val-tos');
  3694. if (tosEl) tosEl.value = r.tos;
  3695. }
  3696. setFwFieldVal('pktsize', r.packet_size, false);
  3697. setFwFieldVal('random', r.random, false);
  3698. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3699. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3700. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3701. setFwFieldVal('ttl', r.ttl, false);
  3702. // Extra tab fields
  3703. setFwFieldVal('time', r.time, false);
  3704. if (r.days) {
  3705. toggleFwField('days', true);
  3706. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3707. const chk = document.getElementById(`fw-day-${d}`);
  3708. if (chk) chk.checked = r.days.includes(d);
  3709. });
  3710. } else {
  3711. toggleFwField('days', false);
  3712. }
  3713. setFwFieldVal('limit', r.limit, false);
  3714. setFwFieldVal('dstlimit', r.dst_limit, false);
  3715. setFwFieldVal('psd', r.psd, false);
  3716. // Action fields
  3717. if (r.reject_with) {
  3718. const rwEl = document.getElementById('filter-modal-rejectwith');
  3719. if (rwEl) rwEl.value = r.reject_with;
  3720. }
  3721. if (r.jump_target) {
  3722. const jtEl = document.getElementById('filter-modal-jumptarget');
  3723. if (jtEl) jtEl.value = r.jump_target;
  3724. }
  3725. if (r.address_list) {
  3726. const alEl = document.getElementById('filter-modal-action-addrlist');
  3727. if (alEl) alEl.value = r.address_list;
  3728. }
  3729. if (r.address_list_timeout) {
  3730. const toEl = document.getElementById('filter-modal-action-timeout');
  3731. if (toEl) toEl.value = r.address_list_timeout;
  3732. }
  3733. setFwFieldVal('logprefix', r.log_prefix, false);
  3734. // Statistics
  3735. const bEl = document.getElementById('fw-stat-bytes');
  3736. const pEl = document.getElementById('fw-stat-packets');
  3737. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3738. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3739. state.fwLastBytes = r.bytes || 0;
  3740. state.fwLastPackets = r.packets || 0;
  3741. state.fwLastTimestamp = Date.now();
  3742. state.fwStatRateHistory = new Array(30).fill(0);
  3743. state.fwStatPktHistory = new Array(30).fill(0);
  3744. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3745. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3746. toggleFilterActionFields();
  3747. document.getElementById('filter-modal').classList.remove('hidden');
  3748. }
  3749. function closeFilterModal() {
  3750. stopFwStatPolling();
  3751. document.getElementById('filter-modal').classList.add('hidden');
  3752. }
  3753. function toggleFilterActionFields() {
  3754. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3755. const rejectBox = document.getElementById('filter-action-reject-box');
  3756. const jumpBox = document.getElementById('filter-action-jump-box');
  3757. const addrBox = document.getElementById('filter-action-addrlist-box');
  3758. if (rejectBox) {
  3759. if (act === 'reject') rejectBox.classList.remove('hidden');
  3760. else rejectBox.classList.add('hidden');
  3761. }
  3762. if (jumpBox) {
  3763. if (act === 'jump') jumpBox.classList.remove('hidden');
  3764. else jumpBox.classList.add('hidden');
  3765. }
  3766. if (addrBox) {
  3767. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3768. addrBox.classList.remove('hidden');
  3769. } else {
  3770. addrBox.classList.add('hidden');
  3771. }
  3772. }
  3773. if (act === 'log') {
  3774. const logEl = document.getElementById('filter-modal-log');
  3775. if (logEl) logEl.checked = true;
  3776. toggleFwField('logprefix', true);
  3777. }
  3778. }
  3779. function toggleFwLogPrefix() {
  3780. const isLog = document.getElementById('filter-modal-log')?.checked;
  3781. toggleFwField('logprefix', !!isLog);
  3782. }
  3783. function copyFilterRule() {
  3784. document.getElementById('filter-modal-id').value = '';
  3785. const badge = document.getElementById('fw-modal-badge');
  3786. if (badge) badge.innerText = 'New...';
  3787. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3788. }
  3789. function resetCurrentRuleCounters() {
  3790. state.fwStatRateHistory = new Array(30).fill(0);
  3791. state.fwStatPktHistory = new Array(30).fill(0);
  3792. state.fwLastBytes = 0;
  3793. state.fwLastPackets = 0;
  3794. state.fwLastTimestamp = Date.now();
  3795. const bEl = document.getElementById('fw-stat-bytes');
  3796. const pEl = document.getElementById('fw-stat-packets');
  3797. const rEl = document.getElementById('fw-stat-rate');
  3798. const prEl = document.getElementById('fw-stat-pktrate');
  3799. if (bEl) bEl.value = '0 B';
  3800. if (pEl) pEl.value = '0';
  3801. if (rEl) rEl.value = '0 bps';
  3802. if (prEl) prEl.value = '0 p/s';
  3803. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3804. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3805. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3806. }
  3807. async function resetAllFwCounters() {
  3808. try {
  3809. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3810. if (res.ok) {
  3811. resetCurrentRuleCounters();
  3812. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3813. loadFirewall(false);
  3814. }
  3815. } catch (err) {
  3816. showToast('Error', err.message, 'error');
  3817. }
  3818. }
  3819. async function applyFilterRule(closeAfter = false) {
  3820. const id = document.getElementById('filter-modal-id').value;
  3821. const chain = document.getElementById('filter-modal-chain').value;
  3822. const action = document.getElementById('filter-modal-action').value;
  3823. const comment = document.getElementById('filter-modal-comment').value.trim();
  3824. const enabled = document.getElementById('filter-modal-enabled').checked;
  3825. const src = getFwFieldVal('src', true);
  3826. const dst = getFwFieldVal('dst', true);
  3827. const srclist = getFwFieldVal('srclist', true);
  3828. const dstlist = getFwFieldVal('dstlist', true);
  3829. const srcgeo = getFwFieldVal('srcgeo', true);
  3830. const dstgeo = getFwFieldVal('dstgeo', true);
  3831. const proto = getFwFieldVal('proto', true);
  3832. const sport = getFwFieldVal('sport', true);
  3833. const dport = getFwFieldVal('dport', true);
  3834. const anyport = getFwFieldVal('anyport', true);
  3835. const iniface = getFwFieldVal('iniface', true);
  3836. const outiface = getFwFieldVal('outiface', true);
  3837. const inifacelist = getFwFieldVal('inifacelist', true);
  3838. const outifacelist = getFwFieldVal('outifacelist', true);
  3839. const pktmark = getFwFieldVal('pktmark', true);
  3840. const connmark = getFwFieldVal('connmark', true);
  3841. const routingmark = getFwFieldVal('routingmark', true);
  3842. const conntype = getFwFieldVal('conntype', false);
  3843. const states = [];
  3844. const csBox = document.getElementById('fw-field-cs');
  3845. if (csBox && !csBox.classList.contains('hidden')) {
  3846. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3847. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3848. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3849. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3850. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3851. }
  3852. const natStates = [];
  3853. const natBox = document.getElementById('fw-field-natstate');
  3854. if (natBox && !natBox.classList.contains('hidden')) {
  3855. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3856. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3857. }
  3858. const payload = {
  3859. id,
  3860. chain,
  3861. action,
  3862. protocol: proto || 'all',
  3863. src_address: src,
  3864. dst_address: dst,
  3865. src_port: sport,
  3866. dst_port: dport,
  3867. any_port: anyport,
  3868. in_interface: iniface,
  3869. out_interface: outiface,
  3870. in_interface_list: inifacelist,
  3871. out_interface_list: outifacelist,
  3872. packet_mark: pktmark,
  3873. connection_mark: connmark,
  3874. routing_mark: routingmark,
  3875. connection_type: conntype,
  3876. connection_state: states,
  3877. connection_nat_state: natStates,
  3878. src_address_list: srclist,
  3879. dst_address_list: dstlist,
  3880. src_geoip: srcgeo,
  3881. dst_geoip: dstgeo,
  3882. comment,
  3883. disabled: !enabled,
  3884. // Advanced tab
  3885. layer7_protocol: getFwFieldVal('layer7', false),
  3886. content: getFwFieldVal('content', false),
  3887. connection_bytes: getFwFieldVal('connbytes', false),
  3888. connection_rate: getFwFieldVal('connrate', false),
  3889. pcc: getFwFieldVal('pcc', false),
  3890. src_mac_address: getFwFieldVal('srcmac', true),
  3891. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3892. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3893. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3894. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3895. ipsec_policy: getFwFieldVal('ipsec', false),
  3896. tls_host: getFwFieldVal('tlshost', false),
  3897. ingress_priority: getFwFieldVal('ingresspriority', false),
  3898. priority: getFwFieldVal('priority', false),
  3899. dscp: getFwFieldVal('dscp', false),
  3900. tcp_mss: getFwFieldVal('tcpmss', false),
  3901. tos: document.getElementById('fw-val-tos')?.value || '',
  3902. packet_size: getFwFieldVal('pktsize', false),
  3903. random: getFwFieldVal('random', false),
  3904. tcp_flags: getFwFieldVal('tcpflags', false),
  3905. icmp_options: getFwFieldVal('icmpoptions', false),
  3906. ipv4_options: getFwFieldVal('ipv4options', false),
  3907. ttl: getFwFieldVal('ttl', false),
  3908. // Extra tab
  3909. time: getFwFieldVal('time', false),
  3910. limit: getFwFieldVal('limit', false),
  3911. dst_limit: getFwFieldVal('dstlimit', false),
  3912. psd: getFwFieldVal('psd', false),
  3913. // Action tab
  3914. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3915. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3916. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3917. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3918. log: document.getElementById('filter-modal-log')?.checked || false,
  3919. log_prefix: getFwFieldVal('logprefix', false)
  3920. };
  3921. try {
  3922. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3923. method: 'POST',
  3924. headers: { 'Content-Type': 'application/json' },
  3925. body: JSON.stringify(payload)
  3926. });
  3927. if (res.ok) {
  3928. const data = await res.json();
  3929. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3930. loadFirewall(false);
  3931. if (closeAfter) {
  3932. closeFilterModal();
  3933. } else {
  3934. if (data.id) {
  3935. document.getElementById('filter-modal-id').value = data.id;
  3936. const badge = document.getElementById('fw-modal-badge');
  3937. if (badge) badge.innerText = `#${data.id}`;
  3938. }
  3939. }
  3940. } else {
  3941. const err = await res.json();
  3942. showToast('Error', err.message || 'Failed to save rule', 'error');
  3943. }
  3944. } catch (err) {
  3945. showToast('Error', err.message, 'error');
  3946. }
  3947. }
  3948. function submitSaveFilterRule(e) {
  3949. if (e && e.preventDefault) e.preventDefault();
  3950. return applyFilterRule(true);
  3951. }
  3952. function startFwStatPolling() {
  3953. stopFwStatPolling();
  3954. pollRuleStats();
  3955. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3956. }
  3957. function stopFwStatPolling() {
  3958. if (state.fwStatInterval) {
  3959. clearInterval(state.fwStatInterval);
  3960. state.fwStatInterval = null;
  3961. }
  3962. }
  3963. async function pollRuleStats() {
  3964. const id = document.getElementById('filter-modal-id')?.value;
  3965. if (!id) {
  3966. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3967. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3968. return;
  3969. }
  3970. try {
  3971. const res = await fetch(`${API_BASE}/firewall/filter`);
  3972. if (!res.ok) return;
  3973. const rules = await res.json();
  3974. const r = rules.find(x => x.id === id);
  3975. if (!r) return;
  3976. const now = Date.now();
  3977. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3978. state.fwLastTimestamp = now;
  3979. const curBytes = r.bytes || 0;
  3980. const curPackets = r.packets || 0;
  3981. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3982. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3983. state.fwLastBytes = curBytes;
  3984. state.fwLastPackets = curPackets;
  3985. const rateBps = Math.round((deltaBytes * 8) / dt);
  3986. const ratePkt = Math.round(deltaPkts / dt);
  3987. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3988. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3989. state.fwStatRateHistory.push(rateBps);
  3990. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3991. state.fwStatPktHistory.push(ratePkt);
  3992. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3993. const bEl = document.getElementById('fw-stat-bytes');
  3994. const pEl = document.getElementById('fw-stat-packets');
  3995. const rEl = document.getElementById('fw-stat-rate');
  3996. const prEl = document.getElementById('fw-stat-pktrate');
  3997. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3998. if (pEl) pEl.value = curPackets.toLocaleString();
  3999. if (rEl) rEl.value = formatBps(rateBps);
  4000. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4001. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4002. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4003. } catch (e) {
  4004. console.error('Error polling rule stats', e);
  4005. }
  4006. }
  4007. function formatBps(bps) {
  4008. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4009. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4010. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4011. return bps + ' bps';
  4012. }
  4013. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4014. const svg = document.getElementById(svgId);
  4015. if (!svg) return;
  4016. const w = 500;
  4017. const h = 100;
  4018. const paddingRight = 45;
  4019. const graphWidth = w - paddingRight;
  4020. const maxVal = Math.max(5, ...dataArray);
  4021. const currentVal = dataArray[dataArray.length - 1] || 0;
  4022. const leg = document.getElementById(legendId);
  4023. if (leg) {
  4024. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4025. }
  4026. let gridLines = '';
  4027. for (let i = 0; i <= 5; i++) {
  4028. const y = 8 + (i * (h - 18) / 5);
  4029. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4030. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4031. gridLines += `
  4032. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4033. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4034. `;
  4035. }
  4036. const step = graphWidth / (dataArray.length - 1);
  4037. const points = dataArray.map((val, idx) => {
  4038. const x = idx * step;
  4039. const y = (h - 10) - (val / maxVal) * (h - 20);
  4040. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4041. });
  4042. const polylineStr = points.join(' ');
  4043. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4044. svg.innerHTML = `
  4045. ${gridLines}
  4046. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4047. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4048. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4049. `;
  4050. }
  4051. async function moveFilterRule(id, dir) {
  4052. try {
  4053. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4054. method: 'POST',
  4055. headers: { 'Content-Type': 'application/json' },
  4056. body: JSON.stringify({ direction: dir })
  4057. });
  4058. if (res.ok) loadFirewall(false);
  4059. } catch (err) {
  4060. showToast('Error', err.message, 'error');
  4061. }
  4062. }
  4063. async function toggleFilterRuleState(id, disabled) {
  4064. try {
  4065. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4066. method: 'POST',
  4067. headers: { 'Content-Type': 'application/json' },
  4068. body: JSON.stringify({ disabled })
  4069. });
  4070. if (res.ok) loadFirewall(false);
  4071. } catch (err) {
  4072. showToast('Error', err.message, 'error');
  4073. }
  4074. }
  4075. async function deleteFilterRule(id) {
  4076. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4077. try {
  4078. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4079. if (res.ok) {
  4080. showToast('Deleted', 'Filter rule removed', 'success');
  4081. loadFirewall(false);
  4082. }
  4083. } catch (err) {
  4084. showToast('Error', err.message, 'error');
  4085. }
  4086. }
  4087. // ----------------- NAT Rules -----------------
  4088. function renderNATRules() {
  4089. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4090. const tbody = document.getElementById('nat-table-body');
  4091. const empty = document.getElementById('nat-empty');
  4092. if (!tbody) return;
  4093. tbody.innerHTML = '';
  4094. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4095. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4096. if (rules.length === 0) {
  4097. empty?.classList.remove('hidden');
  4098. return;
  4099. }
  4100. empty?.classList.add('hidden');
  4101. rules.forEach((r, idx) => {
  4102. const tr = document.createElement('tr');
  4103. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4104. let toTarget = '-';
  4105. if (r.action === 'jump') {
  4106. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4107. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4108. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4109. } else if (r.action === 'redirect') {
  4110. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4111. } else if (r.action === 'masquerade') {
  4112. 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>`;
  4113. } else if (r.action === 'log') {
  4114. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4115. } else {
  4116. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4117. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4118. }
  4119. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4120. tr.innerHTML = `
  4121. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4122. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4123. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4124. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4125. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4126. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4127. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4128. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4129. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4130. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4131. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4132. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4133. </td>
  4134. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4135. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4136. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4137. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4138. <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>
  4139. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4140. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4141. </td>
  4142. `;
  4143. tbody.appendChild(tr);
  4144. });
  4145. }
  4146. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4147. function switchNATRuleTab(tab) {
  4148. state.activeNATRuleTab = tab;
  4149. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4150. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4151. btn.classList.add('text-slate-400', 'border-transparent');
  4152. });
  4153. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4154. if (activeBtn) {
  4155. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4156. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4157. }
  4158. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4159. const activePane = document.getElementById(`nat-pane-${tab}`);
  4160. if (activePane) activePane.classList.remove('hidden');
  4161. if (tab === 'statistics') {
  4162. startNATStatPolling();
  4163. } else {
  4164. stopNATStatPolling();
  4165. }
  4166. }
  4167. function toggleNATField(fieldKey, expand) {
  4168. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4169. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4170. if (!plusBtn || !fieldBox) return;
  4171. if (expand) {
  4172. plusBtn.classList.add('hidden');
  4173. fieldBox.classList.remove('hidden');
  4174. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4175. if (valInput) valInput.focus();
  4176. } else {
  4177. fieldBox.classList.add('hidden');
  4178. plusBtn.classList.remove('hidden');
  4179. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4180. if (valInput) {
  4181. if (valInput.tagName === 'SELECT') {
  4182. valInput.selectedIndex = 0;
  4183. } else {
  4184. valInput.value = '';
  4185. }
  4186. }
  4187. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4188. if (invInput) invInput.checked = false;
  4189. if (fieldKey === 'days') {
  4190. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4191. const el = document.getElementById(`nat-day-${d}`);
  4192. if (el) el.checked = true;
  4193. });
  4194. }
  4195. }
  4196. }
  4197. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4198. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4199. toggleNATField(fieldKey, true);
  4200. let strVal = String(value);
  4201. if (hasInvert) {
  4202. const inv = strVal.startsWith('!');
  4203. if (inv) strVal = strVal.slice(1);
  4204. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4205. if (invEl) invEl.checked = inv;
  4206. }
  4207. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4208. if (valEl) valEl.value = strVal;
  4209. } else {
  4210. toggleNATField(fieldKey, false);
  4211. }
  4212. }
  4213. function getNATFieldVal(fieldKey, hasInvert = false) {
  4214. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4215. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4216. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4217. let v = valEl ? valEl.value.trim() : '';
  4218. if (!v) return '';
  4219. if (hasInvert) {
  4220. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4221. if (invEl && invEl.checked) {
  4222. v = '!' + v.replace(/^!/, '');
  4223. }
  4224. }
  4225. return v;
  4226. }
  4227. function toggleMaximizeNATModal() {
  4228. const win = document.getElementById('nat-modal-window');
  4229. if (!win) return;
  4230. if (win.classList.contains('max-w-[720px]')) {
  4231. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4232. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4233. } else {
  4234. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4235. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4236. }
  4237. }
  4238. function handleNATChainChange() {
  4239. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4240. const actSel = document.getElementById('nat-modal-action');
  4241. if (actSel) {
  4242. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4243. actSel.value = 'masquerade';
  4244. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4245. actSel.value = 'dst-nat';
  4246. }
  4247. }
  4248. toggleNATActionFields();
  4249. }
  4250. function toggleNATActionFields() {
  4251. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4252. const rowAddr = document.getElementById('nat-row-toaddr');
  4253. const rowPort = document.getElementById('nat-row-toport');
  4254. const jumpBox = document.getElementById('nat-action-jump-box');
  4255. const addrBox = document.getElementById('nat-action-addrlist-box');
  4256. // Hide all dynamic rows first
  4257. if (rowAddr) rowAddr.classList.add('hidden');
  4258. if (rowPort) rowPort.classList.add('hidden');
  4259. if (jumpBox) jumpBox.classList.add('hidden');
  4260. if (addrBox) addrBox.classList.add('hidden');
  4261. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4262. if (rowAddr) rowAddr.classList.remove('hidden');
  4263. if (rowPort) rowPort.classList.remove('hidden');
  4264. } else if (act === 'redirect' || act === 'masquerade') {
  4265. if (rowPort) rowPort.classList.remove('hidden');
  4266. } else if (act === 'jump') {
  4267. if (jumpBox) jumpBox.classList.remove('hidden');
  4268. } else if (act.includes('address-list') || act.includes('address list')) {
  4269. if (addrBox) addrBox.classList.remove('hidden');
  4270. }
  4271. if (act === 'log') {
  4272. const logEl = document.getElementById('nat-modal-log');
  4273. if (logEl) logEl.checked = true;
  4274. toggleNATField('logprefix', true);
  4275. }
  4276. }
  4277. function toggleNATLogPrefix() {
  4278. const isLog = document.getElementById('nat-modal-log')?.checked;
  4279. toggleNATField('logprefix', !!isLog);
  4280. }
  4281. function openAddNATModal() {
  4282. switchNATRuleTab('general');
  4283. const badge = document.getElementById('nat-modal-badge');
  4284. if (badge) badge.innerText = 'New...';
  4285. document.getElementById('nat-modal-id').value = '';
  4286. document.getElementById('nat-modal-enabled').checked = true;
  4287. document.getElementById('nat-modal-comment').value = '';
  4288. document.getElementById('nat-modal-chain').value = 'srcnat';
  4289. document.getElementById('nat-modal-action').value = 'masquerade';
  4290. document.getElementById('nat-modal-toaddr').value = '';
  4291. document.getElementById('nat-modal-toport').value = '';
  4292. document.getElementById('nat-modal-log').checked = false;
  4293. populateInterfaceSelect('nat-val-iniface');
  4294. populateInterfaceSelect('nat-val-outiface');
  4295. populateAddressListSelect('nat-val-srclist');
  4296. populateAddressListSelect('nat-val-dstlist');
  4297. populateGeoIPSelect('nat-val-srcgeo');
  4298. populateGeoIPSelect('nat-val-dstgeo');
  4299. const allFieldKeys = [
  4300. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4301. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4302. 'routingmark', 'conntype',
  4303. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4304. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4305. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4306. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4307. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4308. ];
  4309. allFieldKeys.forEach(k => toggleNATField(k, false));
  4310. resetCurrentNATRuleCounters();
  4311. toggleNATActionFields();
  4312. document.getElementById('nat-modal').classList.remove('hidden');
  4313. }
  4314. function openEditNATModal(id) {
  4315. const r = (state.natRules || []).find(rule => rule.id === id);
  4316. if (!r) return;
  4317. switchNATRuleTab('general');
  4318. const badge = document.getElementById('nat-modal-badge');
  4319. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4320. document.getElementById('nat-modal-id').value = r.id;
  4321. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4322. document.getElementById('nat-modal-comment').value = r.comment || '';
  4323. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4324. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4325. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4326. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4327. document.getElementById('nat-modal-log').checked = !!r.log;
  4328. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4329. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4330. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4331. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4332. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4333. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4334. setNATFieldVal('src', r.src_address, true);
  4335. setNATFieldVal('dst', r.dst_address, true);
  4336. setNATFieldVal('srclist', r.src_address_list, true);
  4337. setNATFieldVal('dstlist', r.dst_address_list, true);
  4338. setNATFieldVal('srcgeo', r.src_geoip, true);
  4339. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4340. if (r.protocol && r.protocol !== 'all') {
  4341. setNATFieldVal('proto', r.protocol, true);
  4342. } else {
  4343. toggleNATField('proto', false);
  4344. }
  4345. setNATFieldVal('sport', r.src_port, true);
  4346. setNATFieldVal('dport', r.dst_port, true);
  4347. setNATFieldVal('anyport', r.any_port, true);
  4348. setNATFieldVal('iniface', r.in_interface, true);
  4349. setNATFieldVal('outiface', r.out_interface, true);
  4350. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4351. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4352. setNATFieldVal('pktmark', r.packet_mark, true);
  4353. setNATFieldVal('connmark', r.connection_mark, true);
  4354. setNATFieldVal('routingmark', r.routing_mark, true);
  4355. setNATFieldVal('conntype', r.connection_type, false);
  4356. // Advanced tab fields
  4357. setNATFieldVal('layer7', r.layer7_protocol, false);
  4358. setNATFieldVal('content', r.content, false);
  4359. setNATFieldVal('connbytes', r.connection_bytes, false);
  4360. setNATFieldVal('connrate', r.connection_rate, false);
  4361. setNATFieldVal('pcc', r.pcc, false);
  4362. setNATFieldVal('srcmac', r.src_mac_address, true);
  4363. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4364. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4365. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4366. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4367. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4368. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4369. setNATFieldVal('priority', r.priority, false);
  4370. setNATFieldVal('dscp', r.dscp, false);
  4371. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4372. if (r.tos) {
  4373. const tosEl = document.getElementById('nat-val-tos');
  4374. if (tosEl) tosEl.value = r.tos;
  4375. }
  4376. setNATFieldVal('pktsize', r.packet_size, false);
  4377. setNATFieldVal('random', r.random, false);
  4378. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4379. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4380. setNATFieldVal('ttl', r.ttl, false);
  4381. // Extra tab fields
  4382. setNATFieldVal('time', r.time, false);
  4383. if (r.days) {
  4384. toggleNATField('days', true);
  4385. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4386. const chk = document.getElementById(`nat-day-${d}`);
  4387. if (chk) chk.checked = r.days.includes(d);
  4388. });
  4389. } else {
  4390. toggleNATField('days', false);
  4391. }
  4392. setNATFieldVal('limit', r.limit, false);
  4393. setNATFieldVal('dstlimit', r.dst_limit, false);
  4394. setNATFieldVal('psd', r.psd, false);
  4395. // Action fields
  4396. if (r.jump_target) {
  4397. const jtEl = document.getElementById('nat-modal-jumptarget');
  4398. if (jtEl) jtEl.value = r.jump_target;
  4399. }
  4400. if (r.address_list) {
  4401. const alEl = document.getElementById('nat-modal-action-addrlist');
  4402. if (alEl) alEl.value = r.address_list;
  4403. }
  4404. if (r.address_list_timeout) {
  4405. const toEl = document.getElementById('nat-modal-action-timeout');
  4406. if (toEl) toEl.value = r.address_list_timeout;
  4407. }
  4408. setNATFieldVal('logprefix', r.log_prefix, false);
  4409. // Statistics
  4410. const bEl = document.getElementById('nat-stat-bytes');
  4411. const pEl = document.getElementById('nat-stat-packets');
  4412. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4413. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4414. state.natLastBytes = r.bytes || 0;
  4415. state.natLastPackets = r.packets || 0;
  4416. state.natLastTimestamp = Date.now();
  4417. state.natStatRateHistory = new Array(30).fill(0);
  4418. state.natStatPktHistory = new Array(30).fill(0);
  4419. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4420. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4421. toggleNATActionFields();
  4422. document.getElementById('nat-modal').classList.remove('hidden');
  4423. }
  4424. function closeNATModal() {
  4425. stopNATStatPolling();
  4426. document.getElementById('nat-modal').classList.add('hidden');
  4427. }
  4428. function copyNATRule() {
  4429. document.getElementById('nat-modal-id').value = '';
  4430. const badge = document.getElementById('nat-modal-badge');
  4431. if (badge) badge.innerText = 'New...';
  4432. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4433. }
  4434. function resetCurrentNATRuleCounters() {
  4435. state.natStatRateHistory = new Array(30).fill(0);
  4436. state.natStatPktHistory = new Array(30).fill(0);
  4437. state.natLastBytes = 0;
  4438. state.natLastPackets = 0;
  4439. state.natLastTimestamp = Date.now();
  4440. const bEl = document.getElementById('nat-stat-bytes');
  4441. const pEl = document.getElementById('nat-stat-packets');
  4442. const rEl = document.getElementById('nat-stat-rate');
  4443. const prEl = document.getElementById('nat-stat-pktrate');
  4444. if (bEl) bEl.value = '0 B';
  4445. if (pEl) pEl.value = '0';
  4446. if (rEl) rEl.value = '0 bps';
  4447. if (prEl) prEl.value = '0 p/s';
  4448. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4449. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4450. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4451. }
  4452. async function applyNATRule(closeAfter = false) {
  4453. const id = document.getElementById('nat-modal-id').value;
  4454. const chain = document.getElementById('nat-modal-chain').value;
  4455. const action = document.getElementById('nat-modal-action').value;
  4456. const comment = document.getElementById('nat-modal-comment').value.trim();
  4457. const enabled = document.getElementById('nat-modal-enabled').checked;
  4458. const src = getNATFieldVal('src', true);
  4459. const dst = getNATFieldVal('dst', true);
  4460. const srclist = getNATFieldVal('srclist', true);
  4461. const dstlist = getNATFieldVal('dstlist', true);
  4462. const srcgeo = getNATFieldVal('srcgeo', true);
  4463. const dstgeo = getNATFieldVal('dstgeo', true);
  4464. const proto = getNATFieldVal('proto', true);
  4465. const sport = getNATFieldVal('sport', true);
  4466. const dport = getNATFieldVal('dport', true);
  4467. const anyport = getNATFieldVal('anyport', true);
  4468. const iniface = getNATFieldVal('iniface', true);
  4469. const outiface = getNATFieldVal('outiface', true);
  4470. const inifacelist = getNATFieldVal('inifacelist', true);
  4471. const outifacelist = getNATFieldVal('outifacelist', true);
  4472. const pktmark = getNATFieldVal('pktmark', true);
  4473. const connmark = getNATFieldVal('connmark', true);
  4474. const routingmark = getNATFieldVal('routingmark', true);
  4475. const conntype = getNATFieldVal('conntype', false);
  4476. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4477. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4478. const payload = {
  4479. id,
  4480. chain,
  4481. action,
  4482. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4483. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4484. protocol: proto || 'all',
  4485. src_address: src,
  4486. dst_address: dst,
  4487. src_port: sport,
  4488. dst_port: dport,
  4489. any_port: anyport,
  4490. in_interface: iniface,
  4491. out_interface: outiface,
  4492. in_interface_list: inifacelist,
  4493. out_interface_list: outifacelist,
  4494. packet_mark: pktmark,
  4495. connection_mark: connmark,
  4496. routing_mark: routingmark,
  4497. connection_type: conntype,
  4498. src_address_list: srclist,
  4499. dst_address_list: dstlist,
  4500. src_geoip: srcgeo,
  4501. dst_geoip: dstgeo,
  4502. comment,
  4503. disabled: !enabled,
  4504. // Advanced tab
  4505. layer7_protocol: getNATFieldVal('layer7', false),
  4506. content: getNATFieldVal('content', false),
  4507. connection_bytes: getNATFieldVal('connbytes', false),
  4508. connection_rate: getNATFieldVal('connrate', false),
  4509. pcc: getNATFieldVal('pcc', false),
  4510. src_mac_address: getNATFieldVal('srcmac', true),
  4511. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4512. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4513. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4514. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4515. ipsec_policy: getNATFieldVal('ipsec', false),
  4516. ingress_priority: getNATFieldVal('ingresspriority', false),
  4517. priority: getNATFieldVal('priority', false),
  4518. dscp: getNATFieldVal('dscp', false),
  4519. tcp_mss: getNATFieldVal('tcpmss', false),
  4520. tos: document.getElementById('nat-val-tos')?.value || '',
  4521. packet_size: getNATFieldVal('pktsize', false),
  4522. random: getNATFieldVal('random', false),
  4523. icmp_options: getNATFieldVal('icmpoptions', false),
  4524. ipv4_options: getNATFieldVal('ipv4options', false),
  4525. ttl: getNATFieldVal('ttl', false),
  4526. // Extra tab
  4527. time: getNATFieldVal('time', false),
  4528. limit: getNATFieldVal('limit', false),
  4529. dst_limit: getNATFieldVal('dstlimit', false),
  4530. psd: getNATFieldVal('psd', false),
  4531. // Action tab
  4532. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4533. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4534. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4535. log: document.getElementById('nat-modal-log')?.checked || false,
  4536. log_prefix: getNATFieldVal('logprefix', false)
  4537. };
  4538. try {
  4539. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4540. method: 'POST',
  4541. headers: { 'Content-Type': 'application/json' },
  4542. body: JSON.stringify(payload)
  4543. });
  4544. if (res.ok) {
  4545. const data = await res.json();
  4546. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4547. loadFirewall(false);
  4548. if (closeAfter) {
  4549. closeNATModal();
  4550. } else {
  4551. if (data.id) {
  4552. document.getElementById('nat-modal-id').value = data.id;
  4553. const badge = document.getElementById('nat-modal-badge');
  4554. if (badge) badge.innerText = `#${data.id}`;
  4555. }
  4556. }
  4557. } else {
  4558. const err = await res.json();
  4559. showToast('Error', err.message || 'Failed to save rule', 'error');
  4560. }
  4561. } catch (err) {
  4562. showToast('Error', err.message, 'error');
  4563. }
  4564. }
  4565. function submitSaveNATRule(e) {
  4566. if (e && e.preventDefault) e.preventDefault();
  4567. return applyNATRule(true);
  4568. }
  4569. function startNATStatPolling() {
  4570. stopNATStatPolling();
  4571. pollNATRuleStats();
  4572. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4573. }
  4574. function stopNATStatPolling() {
  4575. if (state.natStatInterval) {
  4576. clearInterval(state.natStatInterval);
  4577. state.natStatInterval = null;
  4578. }
  4579. }
  4580. async function pollNATRuleStats() {
  4581. const id = document.getElementById('nat-modal-id')?.value;
  4582. if (!id) {
  4583. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4584. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4585. return;
  4586. }
  4587. try {
  4588. const res = await fetch(`${API_BASE}/firewall/nat`);
  4589. if (!res.ok) return;
  4590. const rules = await res.json();
  4591. const r = rules.find(x => x.id === id);
  4592. if (!r) return;
  4593. const now = Date.now();
  4594. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4595. state.natLastTimestamp = now;
  4596. const curBytes = r.bytes || 0;
  4597. const curPackets = r.packets || 0;
  4598. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4599. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4600. state.natLastBytes = curBytes;
  4601. state.natLastPackets = curPackets;
  4602. const rateBps = Math.round((deltaBytes * 8) / dt);
  4603. const ratePkt = Math.round(deltaPkts / dt);
  4604. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4605. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4606. state.natStatRateHistory.push(rateBps);
  4607. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4608. state.natStatPktHistory.push(ratePkt);
  4609. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4610. const bEl = document.getElementById('nat-stat-bytes');
  4611. const pEl = document.getElementById('nat-stat-packets');
  4612. const rEl = document.getElementById('nat-stat-rate');
  4613. const prEl = document.getElementById('nat-stat-pktrate');
  4614. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4615. if (pEl) pEl.value = curPackets.toLocaleString();
  4616. if (rEl) rEl.value = formatBps(rateBps);
  4617. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4618. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4619. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4620. } catch (e) {
  4621. console.error('Error polling NAT rule stats', e);
  4622. }
  4623. }
  4624. async function moveNATRule(id, dir) {
  4625. try {
  4626. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4627. method: 'POST',
  4628. headers: { 'Content-Type': 'application/json' },
  4629. body: JSON.stringify({ direction: dir })
  4630. });
  4631. if (res.ok) loadFirewall(false);
  4632. } catch (err) {
  4633. showToast('Error', err.message, 'error');
  4634. }
  4635. }
  4636. async function toggleNATRuleState(id, disabled) {
  4637. try {
  4638. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4639. method: 'POST',
  4640. headers: { 'Content-Type': 'application/json' },
  4641. body: JSON.stringify({ disabled })
  4642. });
  4643. if (res.ok) loadFirewall(false);
  4644. } catch (err) {
  4645. showToast('Error', err.message, 'error');
  4646. }
  4647. }
  4648. async function deleteNATRule(id) {
  4649. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4650. try {
  4651. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4652. if (res.ok) {
  4653. showToast('Deleted', 'NAT rule removed', 'success');
  4654. loadFirewall(false);
  4655. }
  4656. } catch (err) {
  4657. showToast('Error', err.message, 'error');
  4658. }
  4659. }
  4660. // ----------------- Mangle Rules -----------------
  4661. function renderMangleRules() {
  4662. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4663. const tbody = document.getElementById('mangle-table-body');
  4664. const empty = document.getElementById('mangle-empty');
  4665. if (!tbody) return;
  4666. tbody.innerHTML = '';
  4667. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4668. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4669. if (rules.length === 0) {
  4670. empty?.classList.remove('hidden');
  4671. return;
  4672. }
  4673. empty?.classList.add('hidden');
  4674. rules.forEach((r, idx) => {
  4675. const tr = document.createElement('tr');
  4676. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4677. let markVal = '<span class="text-slate-500">-</span>';
  4678. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4679. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4680. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4681. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4682. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4683. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4684. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4685. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4686. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4687. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4688. 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>`;
  4689. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4690. tr.innerHTML = `
  4691. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4692. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4693. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4694. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4695. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4696. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4697. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4698. <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>
  4699. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4700. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4701. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4702. </td>
  4703. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4704. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4705. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4706. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4707. <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>
  4708. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4709. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4710. </td>
  4711. `;
  4712. tbody.appendChild(tr);
  4713. });
  4714. }
  4715. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4716. function switchMangleRuleTab(tab) {
  4717. state.activeMangleRuleTab = tab;
  4718. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4719. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4720. btn.classList.add('text-slate-400', 'border-transparent');
  4721. });
  4722. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4723. if (activeBtn) {
  4724. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4725. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4726. }
  4727. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4728. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4729. if (activePane) activePane.classList.remove('hidden');
  4730. if (tab === 'statistics') {
  4731. startMangleStatPolling();
  4732. } else {
  4733. stopMangleStatPolling();
  4734. }
  4735. }
  4736. function toggleMangleField(fieldKey, expand) {
  4737. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4738. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4739. if (!plusBtn || !fieldBox) return;
  4740. if (expand) {
  4741. plusBtn.classList.add('hidden');
  4742. fieldBox.classList.remove('hidden');
  4743. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4744. if (valInput) valInput.focus();
  4745. } else {
  4746. fieldBox.classList.add('hidden');
  4747. plusBtn.classList.remove('hidden');
  4748. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4749. if (valInput) {
  4750. if (valInput.tagName === 'SELECT') {
  4751. valInput.selectedIndex = 0;
  4752. } else {
  4753. valInput.value = '';
  4754. }
  4755. }
  4756. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4757. if (invInput) invInput.checked = false;
  4758. if (fieldKey === 'cs') {
  4759. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4760. const el = document.getElementById(id);
  4761. if (el) el.checked = false;
  4762. });
  4763. }
  4764. if (fieldKey === 'natstate') {
  4765. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4766. const el = document.getElementById(id);
  4767. if (el) el.checked = false;
  4768. });
  4769. }
  4770. }
  4771. }
  4772. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4773. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4774. toggleMangleField(fieldKey, true);
  4775. let strVal = String(value);
  4776. if (hasInvert) {
  4777. const inv = strVal.startsWith('!');
  4778. if (inv) strVal = strVal.slice(1);
  4779. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4780. if (invEl) invEl.checked = inv;
  4781. }
  4782. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4783. if (valEl) valEl.value = strVal;
  4784. } else {
  4785. toggleMangleField(fieldKey, false);
  4786. }
  4787. }
  4788. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4789. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4790. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4791. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4792. let v = valEl ? valEl.value.trim() : '';
  4793. if (!v) return '';
  4794. if (hasInvert) {
  4795. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4796. if (invEl && invEl.checked) {
  4797. v = '!' + v.replace(/^!/, '');
  4798. }
  4799. }
  4800. return v;
  4801. }
  4802. function toggleMaximizeMangleModal() {
  4803. const win = document.getElementById('mangle-modal-window');
  4804. if (!win) return;
  4805. if (win.classList.contains('max-w-[720px]')) {
  4806. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4807. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4808. } else {
  4809. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4810. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4811. }
  4812. }
  4813. function toggleMangleActionFields() {
  4814. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4815. // Hide all dynamic rows first
  4816. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4817. const el = document.getElementById(`mangle-row-${id}`);
  4818. if (el) el.classList.add('hidden');
  4819. });
  4820. const jumpBox = document.getElementById('mangle-action-jump-box');
  4821. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4822. if (jumpBox) jumpBox.classList.add('hidden');
  4823. if (addrBox) addrBox.classList.add('hidden');
  4824. // Activate matching rows
  4825. if (act === 'mark-connection') {
  4826. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4827. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4828. } else if (act === 'mark-routing') {
  4829. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4830. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4831. } else if (act === 'mark-packet') {
  4832. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4833. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4834. } else if (act === 'change-mss') {
  4835. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4836. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4837. } else if (act === 'change-dscp') {
  4838. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4839. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4840. } else if (act === 'change-ttl') {
  4841. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4842. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4843. } else if (act === 'set-priority') {
  4844. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4845. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4846. } else if (act === 'route') {
  4847. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4848. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4849. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4850. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4851. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4852. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4853. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4854. } else if (act === 'jump') {
  4855. if (jumpBox) jumpBox.classList.remove('hidden');
  4856. } else if (act.includes('address-list') || act.includes('address list')) {
  4857. if (addrBox) addrBox.classList.remove('hidden');
  4858. }
  4859. if (act === 'log') {
  4860. const logEl = document.getElementById('mangle-modal-log');
  4861. if (logEl) logEl.checked = true;
  4862. toggleMangleField('logprefix', true);
  4863. }
  4864. }
  4865. function toggleMangleLogPrefix() {
  4866. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4867. toggleMangleField('logprefix', !!isLog);
  4868. }
  4869. const allMangleFieldKeys = [
  4870. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4871. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4872. 'routingmark', 'conntype', 'cs', 'natstate',
  4873. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4874. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4875. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4876. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4877. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4878. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4879. ];
  4880. function openAddMangleModal() {
  4881. switchMangleRuleTab('general');
  4882. const badge = document.getElementById('mangle-modal-badge');
  4883. if (badge) badge.innerText = 'New...';
  4884. document.getElementById('mangle-modal-id').value = '';
  4885. document.getElementById('mangle-modal-enabled').checked = true;
  4886. document.getElementById('mangle-modal-comment').value = '';
  4887. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4888. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4889. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4890. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4891. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4892. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4893. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4894. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4895. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4896. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4897. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4898. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4899. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4900. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4901. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4902. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4903. populateInterfaceSelect('mangle-val-iniface');
  4904. populateInterfaceSelect('mangle-val-outiface');
  4905. populateAddressListSelect('mangle-val-srclist');
  4906. populateAddressListSelect('mangle-val-dstlist');
  4907. populateGeoIPSelect('mangle-val-srcgeo');
  4908. populateGeoIPSelect('mangle-val-dstgeo');
  4909. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4910. resetCurrentMangleRuleCounters();
  4911. toggleMangleActionFields();
  4912. document.getElementById('mangle-modal').classList.remove('hidden');
  4913. }
  4914. function openEditMangleModal(id) {
  4915. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4916. if (!r) return;
  4917. switchMangleRuleTab('general');
  4918. const badge = document.getElementById('mangle-modal-badge');
  4919. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4920. document.getElementById('mangle-modal-id').value = r.id;
  4921. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4922. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4923. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4924. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4925. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4926. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4927. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4928. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4929. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4930. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4931. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4932. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4933. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4934. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4935. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4936. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4937. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4938. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4939. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4940. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4941. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4942. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4943. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4944. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4945. setMangleFieldVal('src', r.src_address, true);
  4946. setMangleFieldVal('dst', r.dst_address, true);
  4947. setMangleFieldVal('srclist', r.src_address_list, true);
  4948. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4949. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4950. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4951. if (r.protocol && r.protocol !== 'all') {
  4952. setMangleFieldVal('proto', r.protocol, true);
  4953. } else {
  4954. toggleMangleField('proto', false);
  4955. }
  4956. setMangleFieldVal('sport', r.src_port, true);
  4957. setMangleFieldVal('dport', r.dst_port, true);
  4958. setMangleFieldVal('anyport', r.any_port, true);
  4959. setMangleFieldVal('iniface', r.in_interface, true);
  4960. setMangleFieldVal('outiface', r.out_interface, true);
  4961. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4962. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4963. setMangleFieldVal('pktmark', r.packet_mark, true);
  4964. setMangleFieldVal('connmark', r.connection_mark, true);
  4965. setMangleFieldVal('routingmark', r.routing_mark, true);
  4966. setMangleFieldVal('conntype', r.connection_type, false);
  4967. // Connection State
  4968. const states = r.connection_state || [];
  4969. if (states.length > 0) {
  4970. toggleMangleField('cs', true);
  4971. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4972. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4973. if (el) el.checked = states.includes(s);
  4974. });
  4975. } else {
  4976. toggleMangleField('cs', false);
  4977. }
  4978. // Connection NAT State
  4979. const natStates = r.connection_nat_state || [];
  4980. if (natStates.length > 0) {
  4981. toggleMangleField('natstate', true);
  4982. ['srcnat', 'dstnat'].forEach(s => {
  4983. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4984. if (el) el.checked = natStates.includes(s);
  4985. });
  4986. } else {
  4987. toggleMangleField('natstate', false);
  4988. }
  4989. // Advanced tab fields
  4990. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4991. setMangleFieldVal('content', r.content, false);
  4992. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4993. setMangleFieldVal('connrate', r.connection_rate, false);
  4994. setMangleFieldVal('pcc', r.pcc, false);
  4995. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4996. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4997. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4998. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4999. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5000. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5001. setMangleFieldVal('tlshost', r.tls_host, false);
  5002. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5003. setMangleFieldVal('priority', r.priority, false);
  5004. setMangleFieldVal('dscp', r.dscp, false);
  5005. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5006. if (r.tos) {
  5007. const tosEl = document.getElementById('mangle-val-tos');
  5008. if (tosEl) tosEl.value = r.tos;
  5009. }
  5010. setMangleFieldVal('pktsize', r.packet_size, false);
  5011. setMangleFieldVal('random', r.random, false);
  5012. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5013. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5014. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5015. setMangleFieldVal('ttl', r.ttl, false);
  5016. // Extra tab fields
  5017. setMangleFieldVal('nth', r.nth, false);
  5018. setMangleFieldVal('connlimit', r.connection_limit, false);
  5019. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5020. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5021. setMangleFieldVal('hotspot', r.hotspot, false);
  5022. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5023. setMangleFieldVal('limit', r.limit, false);
  5024. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5025. setMangleFieldVal('time', r.time, false);
  5026. setMangleFieldVal('psd', r.psd, false);
  5027. // Action fields
  5028. if (r.jump_target) {
  5029. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5030. if (jtEl) jtEl.value = r.jump_target;
  5031. }
  5032. if (r.address_list) {
  5033. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5034. if (alEl) alEl.value = r.address_list;
  5035. }
  5036. if (r.address_list_timeout) {
  5037. const toEl = document.getElementById('mangle-modal-action-timeout');
  5038. if (toEl) toEl.value = r.address_list_timeout;
  5039. }
  5040. setMangleFieldVal('logprefix', r.log_prefix, false);
  5041. // Statistics
  5042. const bEl = document.getElementById('mangle-stat-bytes');
  5043. const pEl = document.getElementById('mangle-stat-packets');
  5044. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5045. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5046. state.mangleLastBytes = r.bytes || 0;
  5047. state.mangleLastPackets = r.packets || 0;
  5048. state.mangleLastTimestamp = Date.now();
  5049. state.mangleStatRateHistory = new Array(30).fill(0);
  5050. state.mangleStatPktHistory = new Array(30).fill(0);
  5051. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5052. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5053. toggleMangleActionFields();
  5054. document.getElementById('mangle-modal').classList.remove('hidden');
  5055. }
  5056. function closeMangleModal() {
  5057. stopMangleStatPolling();
  5058. document.getElementById('mangle-modal').classList.add('hidden');
  5059. }
  5060. function copyMangleRule() {
  5061. document.getElementById('mangle-modal-id').value = '';
  5062. const badge = document.getElementById('mangle-modal-badge');
  5063. if (badge) badge.innerText = 'New...';
  5064. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5065. }
  5066. function resetCurrentMangleRuleCounters() {
  5067. state.mangleStatRateHistory = new Array(30).fill(0);
  5068. state.mangleStatPktHistory = new Array(30).fill(0);
  5069. state.mangleLastBytes = 0;
  5070. state.mangleLastPackets = 0;
  5071. state.mangleLastTimestamp = Date.now();
  5072. const bEl = document.getElementById('mangle-stat-bytes');
  5073. const pEl = document.getElementById('mangle-stat-packets');
  5074. const rEl = document.getElementById('mangle-stat-rate');
  5075. const prEl = document.getElementById('mangle-stat-pktrate');
  5076. if (bEl) bEl.value = '0 B';
  5077. if (pEl) pEl.value = '0';
  5078. if (rEl) rEl.value = '0 bps';
  5079. if (prEl) prEl.value = '0 p/s';
  5080. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5081. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5082. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5083. }
  5084. async function applyMangleRule(closeAfter = false) {
  5085. const id = document.getElementById('mangle-modal-id').value;
  5086. const chain = document.getElementById('mangle-modal-chain').value;
  5087. const action = document.getElementById('mangle-modal-action').value;
  5088. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5089. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5090. const src = getMangleFieldVal('src', true);
  5091. const dst = getMangleFieldVal('dst', true);
  5092. const srclist = getMangleFieldVal('srclist', true);
  5093. const dstlist = getMangleFieldVal('dstlist', true);
  5094. const srcgeo = getMangleFieldVal('srcgeo', true);
  5095. const dstgeo = getMangleFieldVal('dstgeo', true);
  5096. const proto = getMangleFieldVal('proto', true);
  5097. const sport = getMangleFieldVal('sport', true);
  5098. const dport = getMangleFieldVal('dport', true);
  5099. const anyport = getMangleFieldVal('anyport', true);
  5100. const iniface = getMangleFieldVal('iniface', true);
  5101. const outiface = getMangleFieldVal('outiface', true);
  5102. const inifacelist = getMangleFieldVal('inifacelist', true);
  5103. const outifacelist = getMangleFieldVal('outifacelist', true);
  5104. const pktmark = getMangleFieldVal('pktmark', true);
  5105. const connmark = getMangleFieldVal('connmark', true);
  5106. const routingmark = getMangleFieldVal('routingmark', true);
  5107. const conntype = getMangleFieldVal('conntype', false);
  5108. const states = [];
  5109. const csBox = document.getElementById('mangle-field-cs');
  5110. if (csBox && !csBox.classList.contains('hidden')) {
  5111. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5112. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5113. });
  5114. }
  5115. const natStates = [];
  5116. const natBox = document.getElementById('mangle-field-natstate');
  5117. if (natBox && !natBox.classList.contains('hidden')) {
  5118. ['srcnat', 'dstnat'].forEach(s => {
  5119. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5120. });
  5121. }
  5122. const payload = {
  5123. id,
  5124. chain,
  5125. action,
  5126. protocol: proto || 'all',
  5127. src_address: src,
  5128. dst_address: dst,
  5129. src_port: sport,
  5130. dst_port: dport,
  5131. any_port: anyport,
  5132. in_interface: iniface,
  5133. out_interface: outiface,
  5134. in_interface_list: inifacelist,
  5135. out_interface_list: outifacelist,
  5136. packet_mark: pktmark,
  5137. connection_mark: connmark,
  5138. routing_mark: routingmark,
  5139. connection_type: conntype,
  5140. connection_state: states,
  5141. connection_nat_state: natStates,
  5142. src_address_list: srclist,
  5143. dst_address_list: dstlist,
  5144. src_geoip: srcgeo,
  5145. dst_geoip: dstgeo,
  5146. comment,
  5147. disabled: !enabled,
  5148. // Advanced tab
  5149. layer7_protocol: getMangleFieldVal('layer7', false),
  5150. content: getMangleFieldVal('content', false),
  5151. connection_bytes: getMangleFieldVal('connbytes', false),
  5152. connection_rate: getMangleFieldVal('connrate', false),
  5153. pcc: getMangleFieldVal('pcc', false),
  5154. src_mac_address: getMangleFieldVal('srcmac', true),
  5155. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5156. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5157. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5158. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5159. ipsec_policy: getMangleFieldVal('ipsec', false),
  5160. tls_host: getMangleFieldVal('tlshost', false),
  5161. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5162. priority: getMangleFieldVal('priority', false),
  5163. dscp: getMangleFieldVal('dscp', false),
  5164. tcp_mss: getMangleFieldVal('tcpmss', false),
  5165. tos: document.getElementById('mangle-val-tos')?.value || '',
  5166. packet_size: getMangleFieldVal('pktsize', false),
  5167. random: getMangleFieldVal('random', false),
  5168. tcp_flags: getMangleFieldVal('tcpflags', false),
  5169. icmp_options: getMangleFieldVal('icmpoptions', false),
  5170. ipv4_options: getMangleFieldVal('ipv4options', false),
  5171. ttl: getMangleFieldVal('ttl', false),
  5172. // Extra tab
  5173. nth: getMangleFieldVal('nth', false),
  5174. connection_limit: getMangleFieldVal('connlimit', false),
  5175. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5176. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5177. hotspot: getMangleFieldVal('hotspot', false),
  5178. ip_fragment: getMangleFieldVal('ipfragment', false),
  5179. limit: getMangleFieldVal('limit', false),
  5180. dst_limit: getMangleFieldVal('dstlimit', false),
  5181. time: getMangleFieldVal('time', false),
  5182. psd: getMangleFieldVal('psd', false),
  5183. // Action tab
  5184. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5185. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5186. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5187. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5188. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5189. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5190. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5191. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5192. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5193. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5194. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5195. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5196. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5197. log: document.getElementById('mangle-modal-log')?.checked || false,
  5198. log_prefix: getMangleFieldVal('logprefix', false)
  5199. };
  5200. try {
  5201. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5202. method: 'POST',
  5203. headers: { 'Content-Type': 'application/json' },
  5204. body: JSON.stringify(payload)
  5205. });
  5206. if (res.ok) {
  5207. const data = await res.json();
  5208. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5209. loadFirewall(false);
  5210. if (closeAfter) {
  5211. closeMangleModal();
  5212. } else {
  5213. if (data.id) {
  5214. document.getElementById('mangle-modal-id').value = data.id;
  5215. const badge = document.getElementById('mangle-modal-badge');
  5216. if (badge) badge.innerText = `#${data.id}`;
  5217. }
  5218. }
  5219. } else {
  5220. const err = await res.json();
  5221. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5222. }
  5223. } catch (err) {
  5224. showToast('Error', err.message, 'error');
  5225. }
  5226. }
  5227. function submitSaveMangleRule(e) {
  5228. if (e && e.preventDefault) e.preventDefault();
  5229. return applyMangleRule(true);
  5230. }
  5231. function startMangleStatPolling() {
  5232. stopMangleStatPolling();
  5233. pollMangleRuleStats();
  5234. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5235. }
  5236. function stopMangleStatPolling() {
  5237. if (state.mangleStatInterval) {
  5238. clearInterval(state.mangleStatInterval);
  5239. state.mangleStatInterval = null;
  5240. }
  5241. }
  5242. async function pollMangleRuleStats() {
  5243. const id = document.getElementById('mangle-modal-id')?.value;
  5244. if (!id) {
  5245. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5246. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5247. return;
  5248. }
  5249. try {
  5250. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5251. if (!res.ok) return;
  5252. const rules = await res.json();
  5253. const r = rules.find(x => x.id === id);
  5254. if (!r) return;
  5255. const now = Date.now();
  5256. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5257. state.mangleLastTimestamp = now;
  5258. const curBytes = r.bytes || 0;
  5259. const curPackets = r.packets || 0;
  5260. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5261. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5262. state.mangleLastBytes = curBytes;
  5263. state.mangleLastPackets = curPackets;
  5264. const rateBps = Math.round((deltaBytes * 8) / dt);
  5265. const ratePkt = Math.round(deltaPkts / dt);
  5266. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5267. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5268. state.mangleStatRateHistory.push(rateBps);
  5269. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5270. state.mangleStatPktHistory.push(ratePkt);
  5271. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5272. const bEl = document.getElementById('mangle-stat-bytes');
  5273. const pEl = document.getElementById('mangle-stat-packets');
  5274. const rEl = document.getElementById('mangle-stat-rate');
  5275. const prEl = document.getElementById('mangle-stat-pktrate');
  5276. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5277. if (pEl) pEl.value = curPackets.toLocaleString();
  5278. if (rEl) rEl.value = formatBps(rateBps);
  5279. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5280. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5281. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5282. } catch (e) {
  5283. console.error('Error polling Mangle rule stats', e);
  5284. }
  5285. }
  5286. async function moveMangleRule(id, dir) {
  5287. try {
  5288. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5289. method: 'POST',
  5290. headers: { 'Content-Type': 'application/json' },
  5291. body: JSON.stringify({ direction: dir })
  5292. });
  5293. if (res.ok) loadFirewall(false);
  5294. } catch (err) {
  5295. showToast('Error', err.message, 'error');
  5296. }
  5297. }
  5298. async function toggleMangleRuleState(id, disabled) {
  5299. try {
  5300. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5301. method: 'POST',
  5302. headers: { 'Content-Type': 'application/json' },
  5303. body: JSON.stringify({ disabled })
  5304. });
  5305. if (res.ok) loadFirewall(false);
  5306. } catch (err) {
  5307. showToast('Error', err.message, 'error');
  5308. }
  5309. }
  5310. async function deleteMangleRule(id) {
  5311. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5312. try {
  5313. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5314. if (res.ok) {
  5315. showToast('Deleted', 'Mangle rule removed', 'success');
  5316. loadFirewall(false);
  5317. }
  5318. } catch (err) {
  5319. showToast('Error', err.message, 'error');
  5320. }
  5321. }
  5322. // ----------------- Address Lists -----------------
  5323. function renderAddressLists() {
  5324. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5325. const tbody = document.getElementById('addrlist-table-body');
  5326. const empty = document.getElementById('addrlist-empty');
  5327. if (!tbody) return;
  5328. tbody.innerHTML = '';
  5329. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5330. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5331. // Update filter select
  5332. const sel = document.getElementById('addrlist-filter-name');
  5333. if (sel) {
  5334. const cur = sel.value;
  5335. sel.innerHTML = '<option value="">All Lists</option>';
  5336. const set = new Set((state.addressLists || []).map(a => a.name));
  5337. set.forEach(n => {
  5338. const opt = document.createElement('option');
  5339. opt.value = n;
  5340. opt.innerText = n;
  5341. if (n === cur) opt.selected = true;
  5342. sel.appendChild(opt);
  5343. });
  5344. }
  5345. if (entries.length === 0) {
  5346. empty?.classList.remove('hidden');
  5347. return;
  5348. }
  5349. empty?.classList.add('hidden');
  5350. entries.forEach((e, idx) => {
  5351. const tr = document.createElement('tr');
  5352. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5353. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5354. tr.innerHTML = `
  5355. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5356. <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>
  5357. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5358. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5359. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5360. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5361. <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>
  5362. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5363. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5364. </td>
  5365. `;
  5366. tbody.appendChild(tr);
  5367. });
  5368. populateCommonAddrListDatalist();
  5369. }
  5370. function openAddAddrListModal() {
  5371. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5372. document.getElementById('addrlist-modal-id').value = '';
  5373. document.getElementById('addrlist-modal-name').value = '';
  5374. document.getElementById('addrlist-modal-addr').value = '';
  5375. document.getElementById('addrlist-modal-comment').value = '';
  5376. document.getElementById('addrlist-modal-disabled').checked = false;
  5377. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5378. if (submitBtn) submitBtn.innerText = 'Add to List';
  5379. document.getElementById('addrlist-modal').classList.remove('hidden');
  5380. }
  5381. function openEditAddrListModal(id) {
  5382. const e = (state.addressLists || []).find(item => item.id === id);
  5383. if (!e) return;
  5384. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5385. document.getElementById('addrlist-modal-id').value = e.id;
  5386. document.getElementById('addrlist-modal-name').value = e.name;
  5387. document.getElementById('addrlist-modal-addr').value = e.address;
  5388. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5389. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5390. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5391. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5392. document.getElementById('addrlist-modal').classList.remove('hidden');
  5393. }
  5394. function closeAddrListModal() {
  5395. document.getElementById('addrlist-modal').classList.add('hidden');
  5396. }
  5397. async function submitSaveAddrList(e) {
  5398. e.preventDefault();
  5399. const id = document.getElementById('addrlist-modal-id').value;
  5400. const name = document.getElementById('addrlist-modal-name').value.trim();
  5401. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5402. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5403. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5404. try {
  5405. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5406. method: 'POST',
  5407. headers: { 'Content-Type': 'application/json' },
  5408. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5409. });
  5410. if (res.ok) {
  5411. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5412. closeAddrListModal();
  5413. loadFirewall(false);
  5414. } else {
  5415. const err = await res.json();
  5416. showToast('Error', err.message || 'Failed to save address list', 'error');
  5417. }
  5418. } catch (err) {
  5419. showToast('Error', err.message, 'error');
  5420. }
  5421. }
  5422. async function toggleAddrListState(id, disabled) {
  5423. try {
  5424. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5425. method: 'POST',
  5426. headers: { 'Content-Type': 'application/json' },
  5427. body: JSON.stringify({ disabled })
  5428. });
  5429. if (res.ok) {
  5430. loadFirewall(false);
  5431. }
  5432. } catch (err) {
  5433. showToast('Error', err.message, 'error');
  5434. }
  5435. }
  5436. async function deleteAddrList(id) {
  5437. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5438. try {
  5439. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5440. if (res.ok) {
  5441. showToast('Deleted', 'Address list item removed', 'info');
  5442. loadFirewall(false);
  5443. }
  5444. } catch (err) {
  5445. showToast('Error', err.message, 'error');
  5446. }
  5447. }
  5448. // ----------------- Geo-Location IP Management -----------------
  5449. async function loadGeoIP() {
  5450. try {
  5451. const [statusRes, countriesRes] = await Promise.all([
  5452. fetch(`${API_BASE}/firewall/geoip/status`),
  5453. fetch(`${API_BASE}/firewall/geoip/countries`)
  5454. ]);
  5455. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5456. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5457. updateGeoHeader();
  5458. renderGeoCountries();
  5459. } catch (err) {
  5460. console.error('Failed to load GeoIP:', err);
  5461. }
  5462. }
  5463. function getGeoUsageMap() {
  5464. const usage = {};
  5465. const checkRule = (r, type) => {
  5466. ['src_geoip', 'dst_geoip'].forEach(field => {
  5467. let val = (r && r[field]) || '';
  5468. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5469. if (code) {
  5470. if (!usage[code]) usage[code] = [];
  5471. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5472. if (!usage[code].includes(label)) usage[code].push(label);
  5473. }
  5474. });
  5475. };
  5476. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5477. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5478. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5479. return usage;
  5480. }
  5481. function updateGeoHeader() {
  5482. const s = state.geoStatus || {};
  5483. const statusBadge = document.getElementById('geo-status-badge');
  5484. if (statusBadge) {
  5485. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5486. statusBadge.className = s.auto_update
  5487. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5488. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5489. }
  5490. const intervalLabel = document.getElementById('geo-interval-label');
  5491. if (intervalLabel) {
  5492. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5493. }
  5494. const usageMap = getGeoUsageMap();
  5495. const inUseCount = Object.keys(usageMap).length;
  5496. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5497. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5498. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5499. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5500. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5501. if (lastSyncEl) {
  5502. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5503. const d = new Date(s.last_updated);
  5504. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5505. } else {
  5506. lastSyncEl.innerText = 'Never (Sync Pending)';
  5507. }
  5508. }
  5509. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5510. if (nextSyncEl) {
  5511. if (s.next_update && !s.next_update.startsWith('0001')) {
  5512. const d = new Date(s.next_update);
  5513. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5514. } else {
  5515. nextSyncEl.innerText = '-';
  5516. }
  5517. }
  5518. const badge = document.getElementById('fw-badge-geo');
  5519. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5520. }
  5521. function renderGeoCountries() {
  5522. const tbody = document.getElementById('geo-table-body');
  5523. const empty = document.getElementById('geo-empty');
  5524. if (!tbody) return;
  5525. tbody.innerHTML = '';
  5526. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5527. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5528. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5529. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5530. const usageMap = getGeoUsageMap();
  5531. const countries = (state.geoCountries || []).filter(c => {
  5532. const isUsed = !!usageMap[c.code];
  5533. if (inUseOnly && !isUsed) return false;
  5534. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5535. if (continent && c.continent !== continent) return false;
  5536. if (q) {
  5537. const matchCode = c.code.toLowerCase().includes(q);
  5538. const matchName = c.name.toLowerCase().includes(q);
  5539. if (!matchCode && !matchName) return false;
  5540. }
  5541. return true;
  5542. });
  5543. if (countries.length === 0) {
  5544. empty?.classList.remove('hidden');
  5545. return;
  5546. }
  5547. empty?.classList.add('hidden');
  5548. countries.forEach(c => {
  5549. const tr = document.createElement('tr');
  5550. const isUsed = !!usageMap[c.code];
  5551. const rulesUsing = usageMap[c.code] || [];
  5552. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5553. let statusHtml = '';
  5554. if (isUsed) {
  5555. 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>`;
  5556. } else if (c.subnet_count > 0) {
  5557. 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>';
  5558. } else {
  5559. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5560. }
  5561. tr.innerHTML = `
  5562. <td class="py-2.5 px-3 text-center">
  5563. <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'}">
  5564. ${c.code}
  5565. </span>
  5566. </td>
  5567. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5568. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5569. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5570. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5571. </td>
  5572. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5573. <td class="py-2.5 px-3">
  5574. ${statusHtml}
  5575. </td>
  5576. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5577. <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>
  5578. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5579. </td>
  5580. `;
  5581. tbody.appendChild(tr);
  5582. });
  5583. }
  5584. function quickFilterGeo(preset) {
  5585. const searchInput = document.getElementById('geo-search-input');
  5586. const continentSel = document.getElementById('geo-continent-filter');
  5587. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5588. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5589. if (searchInput) searchInput.value = '';
  5590. if (continentSel) continentSel.value = '';
  5591. if (inUseCheck) inUseCheck.checked = false;
  5592. if (cachedCheck) cachedCheck.checked = false;
  5593. if (preset === 'GR') {
  5594. if (searchInput) searchInput.value = 'Greece';
  5595. } else if (preset === 'Europe') {
  5596. if (continentSel) continentSel.value = 'Europe';
  5597. } else if (preset === 'HIGHRISK') {
  5598. if (searchInput) searchInput.value = 'China';
  5599. }
  5600. renderGeoCountries();
  5601. }
  5602. async function toggleGeoCountry(code, enabled) {
  5603. try {
  5604. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5605. method: 'POST',
  5606. headers: { 'Content-Type': 'application/json' },
  5607. body: JSON.stringify({ enabled })
  5608. });
  5609. if (res.ok) {
  5610. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5611. loadGeoIP();
  5612. } else {
  5613. const err = await res.json();
  5614. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5615. }
  5616. } catch (err) {
  5617. showToast('Error', err.message, 'error');
  5618. }
  5619. }
  5620. async function updateGeoCountry(code) {
  5621. try {
  5622. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5623. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5624. if (res.ok) {
  5625. const data = await res.json();
  5626. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5627. loadGeoIP();
  5628. } else {
  5629. const err = await res.json();
  5630. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5631. }
  5632. } catch (err) {
  5633. showToast('Error', err.message, 'error');
  5634. }
  5635. }
  5636. async function triggerGeoUpdateNow() {
  5637. const spinner = document.getElementById('geo-update-spinner');
  5638. if (spinner) spinner.classList.remove('hidden');
  5639. try {
  5640. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5641. if (res.ok) {
  5642. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5643. setTimeout(() => {
  5644. loadGeoIP();
  5645. if (spinner) spinner.classList.add('hidden');
  5646. }, 2500);
  5647. } else {
  5648. const err = await res.json();
  5649. showToast('Notice', err.message || 'Update in progress', 'info');
  5650. if (spinner) spinner.classList.add('hidden');
  5651. }
  5652. } catch (err) {
  5653. showToast('Error', err.message, 'error');
  5654. if (spinner) spinner.classList.add('hidden');
  5655. }
  5656. }
  5657. async function applyGeoPreset(preset) {
  5658. try {
  5659. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5660. method: 'POST',
  5661. headers: { 'Content-Type': 'application/json' },
  5662. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5663. });
  5664. if (res.ok) {
  5665. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5666. loadGeoIP();
  5667. }
  5668. } catch (err) {
  5669. showToast('Error', err.message, 'error');
  5670. }
  5671. }
  5672. function openGeoIntervalModal() {
  5673. const s = state.geoStatus || {};
  5674. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5675. const sel = document.getElementById('geo-cfg-interval');
  5676. const customBox = document.getElementById('geo-cfg-custom-box');
  5677. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5678. const curHours = s.interval_hours || 24;
  5679. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5680. if (matchOption) {
  5681. sel.value = String(curHours);
  5682. customBox.classList.add('hidden');
  5683. } else {
  5684. sel.value = 'custom';
  5685. customHoursInput.value = curHours;
  5686. customBox.classList.remove('hidden');
  5687. }
  5688. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5689. }
  5690. function closeGeoIntervalModal() {
  5691. document.getElementById('geo-interval-modal').classList.add('hidden');
  5692. }
  5693. function toggleCustomGeoInterval() {
  5694. const val = document.getElementById('geo-cfg-interval').value;
  5695. const customBox = document.getElementById('geo-cfg-custom-box');
  5696. if (val === 'custom') {
  5697. customBox.classList.remove('hidden');
  5698. } else {
  5699. customBox.classList.add('hidden');
  5700. }
  5701. }
  5702. async function submitGeoIntervalSettings(e) {
  5703. e.preventDefault();
  5704. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5705. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5706. let hours = 24;
  5707. if (intervalVal === 'custom') {
  5708. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5709. } else {
  5710. hours = parseInt(intervalVal, 10) || 24;
  5711. }
  5712. try {
  5713. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5714. method: 'POST',
  5715. headers: { 'Content-Type': 'application/json' },
  5716. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5717. });
  5718. if (res.ok) {
  5719. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5720. closeGeoIntervalModal();
  5721. loadGeoIP();
  5722. } else {
  5723. const err = await res.json();
  5724. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5725. }
  5726. } catch (err) {
  5727. showToast('Error', err.message, 'error');
  5728. }
  5729. }
  5730. async function viewGeoSubnets(code, name) {
  5731. if (!name) {
  5732. const found = (state.geoCountries || []).find(x => x.code === code);
  5733. name = found ? found.name : code;
  5734. }
  5735. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5736. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5737. const listEl = document.getElementById('geo-subnets-list');
  5738. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5739. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5740. try {
  5741. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5742. if (res.ok) {
  5743. const data = await res.json();
  5744. const subnets = data.subnets || [];
  5745. if (subnets.length === 0) {
  5746. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5747. } else {
  5748. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5749. }
  5750. } else {
  5751. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5752. }
  5753. } catch (err) {
  5754. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5755. }
  5756. }
  5757. function closeGeoSubnetsModal() {
  5758. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5759. }
  5760. // ----------------- Active Connections Tracking -----------------
  5761. async function loadConnections() {
  5762. try {
  5763. const res = await fetch(`${API_BASE}/firewall/connections`);
  5764. const data = await res.json();
  5765. state.connections = Array.isArray(data) ? data : [];
  5766. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5767. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5768. renderConnections();
  5769. } catch (err) {
  5770. console.error('Failed to load connections:', err);
  5771. }
  5772. }
  5773. function renderConnections() {
  5774. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5775. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5776. const tbody = document.getElementById('conns-table-body');
  5777. const empty = document.getElementById('conns-empty');
  5778. if (!tbody) return;
  5779. tbody.innerHTML = '';
  5780. const conns = (state.connections || []).filter(c => {
  5781. if (protoFilter && c.protocol !== protoFilter) return false;
  5782. if (search) {
  5783. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5784. if (!line.includes(search)) return false;
  5785. }
  5786. return true;
  5787. });
  5788. if (conns.length === 0) {
  5789. empty?.classList.remove('hidden');
  5790. return;
  5791. }
  5792. empty?.classList.add('hidden');
  5793. conns.slice(0, 150).forEach(c => {
  5794. const tr = document.createElement('tr');
  5795. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5796. let stateColor = 'text-slate-400';
  5797. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5798. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5799. tr.innerHTML = `
  5800. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5801. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5802. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5803. <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>
  5804. <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>
  5805. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5806. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5807. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5808. <td class="py-2.5 px-3 text-right font-sans">
  5809. <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>
  5810. </td>
  5811. `;
  5812. tbody.appendChild(tr);
  5813. });
  5814. }
  5815. async function killConnection(protocol, src, sport, dst, dport) {
  5816. try {
  5817. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5818. method: 'POST',
  5819. headers: { 'Content-Type': 'application/json' },
  5820. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5821. });
  5822. if (res.ok) {
  5823. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5824. loadConnections();
  5825. }
  5826. } catch (err) {
  5827. showToast('Error', err.message, 'error');
  5828. }
  5829. }
  5830. async function resetFirewallCounters() {
  5831. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5832. try {
  5833. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5834. if (res.ok) {
  5835. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5836. loadFirewall(false);
  5837. }
  5838. } catch (err) {
  5839. showToast('Error', err.message, 'error');
  5840. }
  5841. }
  5842. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5843. function switchRoutesSubTab(tab) {
  5844. state.routesSubTab = tab;
  5845. const tabs = ['routes', 'rules', 'tables'];
  5846. tabs.forEach(t => {
  5847. const panel = document.getElementById(`routes-subtab-${t}`);
  5848. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5849. if (panel) {
  5850. if (t === tab) panel.classList.remove('hidden');
  5851. else panel.classList.add('hidden');
  5852. }
  5853. if (btn) {
  5854. if (t === tab) {
  5855. 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';
  5856. } else {
  5857. 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';
  5858. }
  5859. }
  5860. });
  5861. setTimeout(initTableSorting, 50);
  5862. }
  5863. async function loadRoutes() {
  5864. try {
  5865. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5866. fetch(`${API_BASE}/routes`),
  5867. fetch(`${API_BASE}/routing/rules`),
  5868. fetch(`${API_BASE}/routing/tables`)
  5869. ]);
  5870. if (routesRes.ok) state.routes = await routesRes.json();
  5871. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5872. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5873. const bRoutes = document.getElementById('routes-badge-routes');
  5874. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5875. const showSystem = document.getElementById('prule-show-system')?.checked;
  5876. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5877. const bRules = document.getElementById('routes-badge-rules');
  5878. if (bRules) bRules.innerText = userRules.length;
  5879. const bTables = document.getElementById('routes-badge-tables');
  5880. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5881. const bRoutesCount = document.getElementById('badge-routes-count');
  5882. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5883. renderRoutesList();
  5884. renderPolicyRules();
  5885. renderRoutingTables();
  5886. } catch (err) {
  5887. console.error('Failed to load routing:', err);
  5888. }
  5889. }
  5890. function getRouteProtocolBadge(proto) {
  5891. const p = (proto || 'static').toLowerCase();
  5892. switch (p) {
  5893. case 'bgp':
  5894. 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>`;
  5895. case 'ibgp':
  5896. 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>`;
  5897. case 'ospf':
  5898. 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>`;
  5899. case 'rip':
  5900. 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>`;
  5901. case 'static':
  5902. 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>`;
  5903. case 'connected':
  5904. 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>`;
  5905. case 'dhcp':
  5906. 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>`;
  5907. case 'multicast':
  5908. 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>`;
  5909. default:
  5910. 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>`;
  5911. }
  5912. }
  5913. function renderRoutesList() {
  5914. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5915. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5916. const tbody = document.getElementById('routes-table-body');
  5917. const empty = document.getElementById('routes-empty');
  5918. if (!tbody) return;
  5919. // Update table filter select
  5920. const sel = document.getElementById('routes-filter-table');
  5921. if (sel) {
  5922. const cur = sel.value;
  5923. sel.innerHTML = '<option value="">All Tables</option>';
  5924. (state.routingTables || []).forEach(t => {
  5925. const opt = document.createElement('option');
  5926. opt.value = t.name;
  5927. opt.innerText = t.name;
  5928. if (t.name === cur) opt.selected = true;
  5929. sel.appendChild(opt);
  5930. });
  5931. }
  5932. const routes = (state.routes || []).filter(r => {
  5933. if (tableFilter && r.routing_table !== tableFilter) return false;
  5934. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5935. if (typeFilter === 'multicast' && !r.multicast) return false;
  5936. if (typeFilter === 'static' && !r.static) return false;
  5937. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5938. if (typeFilter === 'connected' && !r.connect) return false;
  5939. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5940. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5941. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5942. return true;
  5943. });
  5944. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5945. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5946. let summaryText = `${routes.length} Routes`;
  5947. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5948. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5949. const badgeEl = document.getElementById('routes-count-badge');
  5950. if (badgeEl) badgeEl.innerText = summaryText;
  5951. if (routes.length === 0) {
  5952. empty?.classList.remove('hidden');
  5953. tbody.innerHTML = '';
  5954. return;
  5955. }
  5956. empty?.classList.add('hidden');
  5957. 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(';');
  5958. if (tbody.dataset.sig === sig) {
  5959. return; // Routes table unchanged! Do not wipe DOM or flicker!
  5960. }
  5961. tbody.dataset.sig = sig;
  5962. tbody.innerHTML = '';
  5963. routes.forEach(r => {
  5964. const tr = document.createElement('tr');
  5965. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5966. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5967. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5968. let flags = '';
  5969. if (r.dynamic) flags += 'D';
  5970. if (r.active) flags += 'A';
  5971. if (r.connect) flags += 'C';
  5972. if (r.static) flags += 'S';
  5973. if (r.ecmp) flags += 'E';
  5974. if (r.multicast) flags += 'M';
  5975. if (r.disabled) flags += 'X';
  5976. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5977. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5978. if (r.check_gateway === 'internet') {
  5979. if (r.health_status === 'online') {
  5980. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5981. healthCell = `
  5982. <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)">
  5983. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5984. <span>Internet OK (${ms}ms)</span>
  5985. </span>
  5986. `;
  5987. } else if (r.health_status === 'offline') {
  5988. healthCell = `
  5989. <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.">
  5990. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5991. <span>Internet Down</span>
  5992. </span>
  5993. `;
  5994. } else {
  5995. healthCell = `
  5996. <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">
  5997. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5998. <span>Checking...</span>
  5999. </span>
  6000. `;
  6001. }
  6002. } else if (r.check_gateway === 'ping') {
  6003. if (r.health_status === 'online') {
  6004. healthCell = `
  6005. <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">
  6006. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6007. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6008. </span>
  6009. `;
  6010. } else if (r.health_status === 'offline') {
  6011. healthCell = `
  6012. <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">
  6013. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6014. <span>Gateway Dead</span>
  6015. </span>
  6016. `;
  6017. }
  6018. }
  6019. const flagDescriptions = [];
  6020. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6021. if (r.active) flagDescriptions.push('Active (A)');
  6022. if (r.connect) flagDescriptions.push('Connected (C)');
  6023. if (r.static) flagDescriptions.push('Static (S)');
  6024. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6025. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6026. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6027. tr.innerHTML = `
  6028. <td class="py-2.5 px-3 text-center">
  6029. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6030. 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')
  6031. }" title="Flags: ${flagDescriptions.join(', ')}">
  6032. ${flags || '-'}
  6033. </span>
  6034. </td>
  6035. <td class="py-2.5 px-3">
  6036. <div class="flex items-center gap-1.5 flex-wrap">
  6037. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6038. ${r.ecmp ? `
  6039. <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)">
  6040. <span>⚡ ECMP</span>
  6041. </span>
  6042. ` : ''}
  6043. ${r.multicast ? `
  6044. <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">
  6045. <span>IGMP</span>
  6046. </span>
  6047. ` : ''}
  6048. </div>
  6049. </td>
  6050. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6051. <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>
  6052. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6053. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6054. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6055. <td class="py-2.5 px-3">${healthCell}</td>
  6056. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6057. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6058. ${r.static ? `
  6059. <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>
  6060. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6061. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6062. ` : `
  6063. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6064. `}
  6065. </td>
  6066. `;
  6067. tbody.appendChild(tr);
  6068. });
  6069. }
  6070. function openAddRouteModal() {
  6071. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6072. document.getElementById('route-modal-id').value = '';
  6073. document.getElementById('route-modal-old-dst').value = '';
  6074. document.getElementById('route-modal-old-gw').value = '';
  6075. document.getElementById('route-modal-old-distance').value = '';
  6076. document.getElementById('route-modal-old-table').value = '';
  6077. document.getElementById('route-modal-old-iface').value = '';
  6078. const dstInput = document.getElementById('route-modal-dst');
  6079. const gwInput = document.getElementById('route-modal-gw');
  6080. const distInput = document.getElementById('route-modal-distance');
  6081. const ifaceSelect = document.getElementById('route-modal-iface');
  6082. const tableSelect = document.getElementById('route-modal-table');
  6083. const commentInput = document.getElementById('route-modal-comment');
  6084. const disCheck = document.getElementById('route-modal-disabled');
  6085. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6086. dstInput.disabled = false;
  6087. dstInput.value = '0.0.0.0/0';
  6088. gwInput.disabled = false;
  6089. gwInput.value = '';
  6090. distInput.disabled = false;
  6091. distInput.value = '1';
  6092. ifaceSelect.disabled = false;
  6093. tableSelect.disabled = false;
  6094. commentInput.disabled = false;
  6095. commentInput.value = '';
  6096. disCheck.disabled = false;
  6097. disCheck.checked = false;
  6098. if (saveBtn) saveBtn.classList.remove('hidden');
  6099. const checkGw = document.getElementById('route-modal-check-gw');
  6100. if (checkGw) checkGw.value = 'internet';
  6101. const checkTarget = document.getElementById('route-modal-check-target');
  6102. if (checkTarget) checkTarget.value = '1.1.1.1';
  6103. const checkInterval = document.getElementById('route-modal-check-interval');
  6104. if (checkInterval) checkInterval.value = '5';
  6105. const checkThresh = document.getElementById('route-modal-check-threshold');
  6106. if (checkThresh) checkThresh.value = '3';
  6107. toggleRouteCheckModeUI();
  6108. populateInterfaceSelect('route-modal-iface');
  6109. // Populate tables
  6110. tableSelect.innerHTML = '';
  6111. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6112. const opt = document.createElement('option');
  6113. opt.value = t.name;
  6114. opt.innerText = t.name;
  6115. if (t.name === 'main') opt.selected = true;
  6116. tableSelect.appendChild(opt);
  6117. });
  6118. document.getElementById('route-modal').classList.remove('hidden');
  6119. }
  6120. function openEditRouteModal(id) {
  6121. const r = (state.routes || []).find(route => route.id === id);
  6122. if (!r) return;
  6123. const isStatic = !!r.static;
  6124. document.getElementById('route-modal-title').innerText = isStatic
  6125. ? `Edit Route: ${r.dst_address}`
  6126. : `Route Properties (Read Only): ${r.dst_address}`;
  6127. document.getElementById('route-modal-id').value = r.id;
  6128. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6129. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6130. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6131. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6132. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6133. const dstInput = document.getElementById('route-modal-dst');
  6134. const gwInput = document.getElementById('route-modal-gw');
  6135. const distInput = document.getElementById('route-modal-distance');
  6136. const ifaceSelect = document.getElementById('route-modal-iface');
  6137. const tableSelect = document.getElementById('route-modal-table');
  6138. const commentInput = document.getElementById('route-modal-comment');
  6139. const disCheck = document.getElementById('route-modal-disabled');
  6140. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6141. dstInput.value = r.dst_address;
  6142. gwInput.value = r.gateway || '';
  6143. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6144. commentInput.value = r.comment || '';
  6145. disCheck.checked = !!r.disabled;
  6146. const checkGw = document.getElementById('route-modal-check-gw');
  6147. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6148. const checkTarget = document.getElementById('route-modal-check-target');
  6149. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6150. const checkInterval = document.getElementById('route-modal-check-interval');
  6151. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6152. const checkThresh = document.getElementById('route-modal-check-threshold');
  6153. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6154. toggleRouteCheckModeUI();
  6155. dstInput.disabled = !isStatic;
  6156. gwInput.disabled = !isStatic;
  6157. distInput.disabled = !isStatic;
  6158. ifaceSelect.disabled = !isStatic;
  6159. tableSelect.disabled = !isStatic;
  6160. commentInput.disabled = !isStatic;
  6161. disCheck.disabled = !isStatic;
  6162. if (checkGw) checkGw.disabled = !isStatic;
  6163. if (checkTarget) checkTarget.disabled = !isStatic;
  6164. if (checkInterval) checkInterval.disabled = !isStatic;
  6165. if (checkThresh) checkThresh.disabled = !isStatic;
  6166. if (saveBtn) {
  6167. if (isStatic) {
  6168. saveBtn.classList.remove('hidden');
  6169. } else {
  6170. saveBtn.classList.add('hidden');
  6171. }
  6172. }
  6173. populateInterfaceSelect('route-modal-iface', r.interface);
  6174. tableSelect.innerHTML = '';
  6175. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6176. const opt = document.createElement('option');
  6177. opt.value = t.name;
  6178. opt.innerText = t.name;
  6179. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6180. tableSelect.appendChild(opt);
  6181. });
  6182. document.getElementById('route-modal').classList.remove('hidden');
  6183. }
  6184. function closeRouteModal() {
  6185. document.getElementById('route-modal').classList.add('hidden');
  6186. }
  6187. function setRouteCheckTarget(ip) {
  6188. const inp = document.getElementById('route-modal-check-target');
  6189. if (inp) inp.value = ip;
  6190. }
  6191. function toggleRouteCheckModeUI() {
  6192. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6193. const targetRow = document.getElementById('route-row-check-target');
  6194. const paramsRow = document.getElementById('route-row-check-params');
  6195. if (mode === 'none') {
  6196. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6197. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6198. } else if (mode === 'ping') {
  6199. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6200. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6201. } else { // internet
  6202. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6203. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6204. }
  6205. }
  6206. async function submitSaveRoute(e) {
  6207. e.preventDefault();
  6208. const id = document.getElementById('route-modal-id').value;
  6209. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6210. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6211. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6212. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6213. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6214. const dst = document.getElementById('route-modal-dst').value.trim();
  6215. const gw = document.getElementById('route-modal-gw').value.trim();
  6216. const table = document.getElementById('route-modal-table').value;
  6217. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6218. const iface = document.getElementById('route-modal-iface').value;
  6219. const comment = document.getElementById('route-modal-comment').value.trim();
  6220. const disabled = document.getElementById('route-modal-disabled').checked;
  6221. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6222. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6223. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6224. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6225. if (!dst) {
  6226. showToast('Error', 'Destination address is required', 'error');
  6227. return;
  6228. }
  6229. if (!gw && !iface) {
  6230. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6231. return;
  6232. }
  6233. const payload = {
  6234. id,
  6235. old_dst_address: oldDst,
  6236. old_gateway: oldGw,
  6237. old_routing_table: oldTable,
  6238. old_interface: oldIface,
  6239. dst_address: dst,
  6240. gateway: gw || iface,
  6241. routing_table: table,
  6242. distance,
  6243. interface: iface,
  6244. comment,
  6245. disabled,
  6246. check_gateway,
  6247. check_target,
  6248. check_interval,
  6249. check_threshold
  6250. };
  6251. if (oldDistStr !== undefined && oldDistStr !== '') {
  6252. payload.old_distance = parseInt(oldDistStr, 10);
  6253. }
  6254. try {
  6255. const res = await fetch(`${API_BASE}/routes`, {
  6256. method: 'POST',
  6257. headers: { 'Content-Type': 'application/json' },
  6258. body: JSON.stringify(payload)
  6259. });
  6260. if (res.ok) {
  6261. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6262. closeRouteModal();
  6263. loadRoutes();
  6264. } else {
  6265. const err = await res.json();
  6266. showToast('Error', err.message || 'Failed to save route', 'error');
  6267. }
  6268. } catch (err) {
  6269. showToast('Error', err.message, 'error');
  6270. }
  6271. }
  6272. async function toggleRouteState(id, disabled) {
  6273. try {
  6274. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6275. method: 'POST',
  6276. headers: { 'Content-Type': 'application/json' },
  6277. body: JSON.stringify({ disabled })
  6278. });
  6279. if (res.ok) loadRoutes();
  6280. } catch (err) {
  6281. showToast('Error', err.message, 'error');
  6282. }
  6283. }
  6284. async function deleteRoute(id) {
  6285. if (!confirm('Are you sure you want to delete this route?')) return;
  6286. try {
  6287. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6288. if (res.ok) {
  6289. showToast('Deleted', 'Route removed', 'success');
  6290. loadRoutes();
  6291. }
  6292. } catch (err) {
  6293. showToast('Error', err.message, 'error');
  6294. }
  6295. }
  6296. // ----------------- Policy Rules (/ip route rule) -----------------
  6297. function renderPolicyRules() {
  6298. const tbody = document.getElementById('rules-table-body');
  6299. const empty = document.getElementById('rules-empty');
  6300. if (!tbody) return;
  6301. const showSystem = document.getElementById('prule-show-system')?.checked;
  6302. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6303. const countBadge = document.getElementById('rules-count-badge');
  6304. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6305. const bRules = document.getElementById('routes-badge-rules');
  6306. if (bRules) bRules.innerText = filtered.length;
  6307. if (filtered.length === 0) {
  6308. empty?.classList.remove('hidden');
  6309. tbody.innerHTML = '';
  6310. return;
  6311. }
  6312. empty?.classList.add('hidden');
  6313. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6314. if (tbody.dataset.sig === sig) return;
  6315. tbody.dataset.sig = sig;
  6316. tbody.innerHTML = '';
  6317. filtered.forEach(pr => {
  6318. const isSys = pr.is_default || pr.is_system;
  6319. const tr = document.createElement('tr');
  6320. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6321. tr.innerHTML = `
  6322. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6323. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6324. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6325. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6326. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6327. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6328. <td class="py-2.5 px-3 text-right font-sans">
  6329. ${!pr.is_default ? `
  6330. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6331. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6332. </td>
  6333. `;
  6334. tbody.appendChild(tr);
  6335. });
  6336. }
  6337. function openAddPolicyRuleModal() {
  6338. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6339. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6340. document.getElementById('prule-modal-mark').value = '';
  6341. document.getElementById('prule-modal-src').value = '';
  6342. document.getElementById('prule-modal-dst').value = '';
  6343. const sel = document.getElementById('prule-modal-table');
  6344. sel.innerHTML = '';
  6345. (state.routingTables || []).forEach(t => {
  6346. const opt = document.createElement('option');
  6347. opt.value = t.name;
  6348. opt.innerText = t.name;
  6349. sel.appendChild(opt);
  6350. });
  6351. document.getElementById('prule-modal').classList.remove('hidden');
  6352. }
  6353. function closePolicyRuleModal() {
  6354. document.getElementById('prule-modal').classList.add('hidden');
  6355. }
  6356. async function submitSavePolicyRule(e) {
  6357. e.preventDefault();
  6358. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6359. const mark = document.getElementById('prule-modal-mark').value.trim();
  6360. const src = document.getElementById('prule-modal-src').value.trim();
  6361. const dst = document.getElementById('prule-modal-dst').value.trim();
  6362. const table = document.getElementById('prule-modal-table').value;
  6363. const action = document.getElementById('prule-modal-action').value;
  6364. try {
  6365. const res = await fetch(`${API_BASE}/routing/rules`, {
  6366. method: 'POST',
  6367. headers: { 'Content-Type': 'application/json' },
  6368. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6369. });
  6370. if (res.ok) {
  6371. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6372. closePolicyRuleModal();
  6373. loadRoutes();
  6374. } else {
  6375. const err = await res.json();
  6376. showToast('Error', err.message, 'error');
  6377. }
  6378. } catch (err) {
  6379. showToast('Error', err.message, 'error');
  6380. }
  6381. }
  6382. async function deletePolicyRule(id) {
  6383. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6384. try {
  6385. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6386. if (res.ok) {
  6387. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6388. loadRoutes();
  6389. }
  6390. } catch (err) {
  6391. showToast('Error', err.message, 'error');
  6392. }
  6393. }
  6394. // ----------------- Routing Tables -----------------
  6395. function renderRoutingTables() {
  6396. const tbody = document.getElementById('tables-table-body');
  6397. if (!tbody) return;
  6398. const tables = state.routingTables || [];
  6399. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6400. if (tbody.dataset.sig === sig) return;
  6401. tbody.dataset.sig = sig;
  6402. tbody.innerHTML = '';
  6403. (state.routingTables || []).forEach(t => {
  6404. const tr = document.createElement('tr');
  6405. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6406. tr.innerHTML = `
  6407. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6408. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6409. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6410. `;
  6411. tbody.appendChild(tr);
  6412. });
  6413. }
  6414. function openAddTableModal() {
  6415. document.getElementById('table-modal-name').value = '';
  6416. document.getElementById('table-modal-id').value = '';
  6417. document.getElementById('table-modal-comment').value = '';
  6418. document.getElementById('table-modal').classList.remove('hidden');
  6419. }
  6420. function closeTableModal() {
  6421. document.getElementById('table-modal').classList.add('hidden');
  6422. }
  6423. async function submitSaveTable(e) {
  6424. e.preventDefault();
  6425. const name = document.getElementById('table-modal-name').value.trim();
  6426. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6427. const comment = document.getElementById('table-modal-comment').value.trim();
  6428. try {
  6429. const res = await fetch(`${API_BASE}/routing/tables`, {
  6430. method: 'POST',
  6431. headers: { 'Content-Type': 'application/json' },
  6432. body: JSON.stringify({ name, table_id: id, comment })
  6433. });
  6434. if (res.ok) {
  6435. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6436. closeTableModal();
  6437. loadRoutes();
  6438. } else {
  6439. const err = await res.json();
  6440. showToast('Error', err.message, 'error');
  6441. }
  6442. } catch (err) {
  6443. showToast('Error', err.message, 'error');
  6444. }
  6445. }
  6446. async function loadDebianConfig() {
  6447. const view = document.getElementById('debian-config-view');
  6448. view.innerText = 'Generating live configuration...';
  6449. try {
  6450. const res = await fetch(`${API_BASE}/debian/config`);
  6451. const data = await res.json();
  6452. view.innerText = data.content || '# Empty config';
  6453. } catch (err) {
  6454. view.innerText = 'Failed to generate Debian network config.';
  6455. }
  6456. }
  6457. async function saveDebianConfig() {
  6458. try {
  6459. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6460. const data = await res.json();
  6461. if (res.ok) {
  6462. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6463. loadDebianConfig();
  6464. }
  6465. } catch (err) {
  6466. showToast('Error', err.message, 'error');
  6467. }
  6468. }
  6469. function showToast(title, message, type = 'info') {
  6470. const container = document.getElementById('toast-container');
  6471. const toast = document.createElement('div');
  6472. const borderColors = {
  6473. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6474. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6475. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6476. };
  6477. 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}`;
  6478. toast.innerHTML = `
  6479. <div class="flex-1">
  6480. <div class="font-bold text-xs text-white">${title}</div>
  6481. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6482. </div>
  6483. `;
  6484. container.appendChild(toast);
  6485. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6486. setTimeout(() => {
  6487. toast.classList.add('opacity-0', 'translate-y-2');
  6488. setTimeout(() => toast.remove(), 300);
  6489. }, 4000);
  6490. }
  6491. function formatTraffic(bytesPerSec) {
  6492. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6493. const kb = bytesPerSec / 1024;
  6494. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6495. const mb = kb / 1024;
  6496. return `${mb.toFixed(2)} MB/s`;
  6497. }
  6498. function toggleSidebar() {
  6499. const sb = document.getElementById('sidebar');
  6500. sb.classList.toggle('-translate-x-full');
  6501. }
  6502. // ======================== EoIP (Ethernet over IP) ========================
  6503. async function loadEoIP(populate = true) {
  6504. try {
  6505. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6506. const data = await res.json();
  6507. state.eoipTunnels = Array.isArray(data) ? data : [];
  6508. const badge = document.getElementById('eoip-count-badge');
  6509. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6510. const sideBadge = document.getElementById('badge-eoip-count');
  6511. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6512. renderEoIPTunnels();
  6513. } catch (err) {
  6514. console.error('Failed to load EoIP:', err);
  6515. }
  6516. }
  6517. function renderEoIPTunnels() {
  6518. const tbody = document.getElementById('eoip-table-body');
  6519. const empty = document.getElementById('eoip-empty');
  6520. if (!tbody) return;
  6521. tbody.innerHTML = '';
  6522. const tunnels = state.eoipTunnels || [];
  6523. if (tunnels.length === 0) {
  6524. empty?.classList.remove('hidden');
  6525. return;
  6526. }
  6527. empty?.classList.add('hidden');
  6528. tunnels.forEach(t => {
  6529. const tr = document.createElement('tr');
  6530. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6531. tr.innerHTML = `
  6532. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6533. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6534. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6535. <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>
  6536. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6537. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6538. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6539. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6540. <td class="py-2.5 px-3 font-mono text-[11px]">
  6541. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6542. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6543. </td>
  6544. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6545. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6546. <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>
  6547. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6548. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6549. </td>
  6550. `;
  6551. tbody.appendChild(tr);
  6552. });
  6553. }
  6554. function openAddEoIPModal() {
  6555. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6556. document.getElementById('eoip-modal-id').value = '';
  6557. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6558. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6559. document.getElementById('eoip-modal-remote').value = '';
  6560. document.getElementById('eoip-modal-ip').value = '';
  6561. document.getElementById('eoip-modal-local').value = '';
  6562. document.getElementById('eoip-modal-mac').value = '';
  6563. document.getElementById('eoip-modal-mtu').value = '1500';
  6564. document.getElementById('eoip-modal-comment').value = '';
  6565. document.getElementById('eoip-modal-clampmss').checked = true;
  6566. document.getElementById('eoip-modal-disabled').checked = false;
  6567. document.getElementById('eoip-modal').classList.remove('hidden');
  6568. }
  6569. function openEditEoIPModal(id) {
  6570. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6571. if (!t) return;
  6572. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6573. document.getElementById('eoip-modal-id').value = t.id;
  6574. document.getElementById('eoip-modal-name').value = t.name;
  6575. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6576. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6577. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6578. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6579. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6580. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6581. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6582. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6583. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6584. document.getElementById('eoip-modal').classList.remove('hidden');
  6585. }
  6586. function closeEoIPModal() {
  6587. document.getElementById('eoip-modal').classList.add('hidden');
  6588. }
  6589. async function submitSaveEoIP(e) {
  6590. e.preventDefault();
  6591. const id = document.getElementById('eoip-modal-id').value;
  6592. const name = document.getElementById('eoip-modal-name').value.trim();
  6593. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6594. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6595. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6596. const local = document.getElementById('eoip-modal-local').value.trim();
  6597. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6598. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6599. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6600. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6601. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6602. try {
  6603. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6604. method: 'POST',
  6605. headers: { 'Content-Type': 'application/json' },
  6606. body: JSON.stringify({
  6607. id,
  6608. name,
  6609. tunnel_id: tunnelId,
  6610. remote_address: remote,
  6611. ip_address: ipAddress,
  6612. local_address: local,
  6613. mac_address: mac,
  6614. mtu,
  6615. clamp_mss: clampMss,
  6616. comment,
  6617. disabled
  6618. })
  6619. });
  6620. if (res.ok) {
  6621. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6622. closeEoIPModal();
  6623. loadEoIP(false);
  6624. fetchData(false);
  6625. } else {
  6626. const err = await res.json();
  6627. showToast('Error', err.message, 'error');
  6628. }
  6629. } catch (err) {
  6630. showToast('Error', err.message, 'error');
  6631. }
  6632. }
  6633. async function toggleEoIPState(id, disabled) {
  6634. try {
  6635. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6636. method: 'POST',
  6637. headers: { 'Content-Type': 'application/json' },
  6638. body: JSON.stringify({ disabled })
  6639. });
  6640. if (res.ok) {
  6641. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6642. loadEoIP(false);
  6643. fetchData(false);
  6644. }
  6645. } catch (err) {
  6646. showToast('Error', err.message, 'error');
  6647. }
  6648. }
  6649. async function deleteEoIP(id) {
  6650. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6651. try {
  6652. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6653. if (res.ok) {
  6654. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6655. loadEoIP(false);
  6656. fetchData(false);
  6657. }
  6658. } catch (err) {
  6659. showToast('Error', err.message, 'error');
  6660. }
  6661. }
  6662. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6663. async function loadAeroTUN(populate = true) {
  6664. try {
  6665. const [tunnelsRes, statsRes] = await Promise.all([
  6666. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6667. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6668. ]);
  6669. if (tunnelsRes.ok) {
  6670. const data = await tunnelsRes.json();
  6671. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6672. }
  6673. if (statsRes.ok) {
  6674. state.aerotunStats = await statsRes.json();
  6675. }
  6676. const countBadge = document.getElementById('aerotun-count-badge');
  6677. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6678. const sideBadge = document.getElementById('badge-aerotun-count');
  6679. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6680. renderAeroTUN();
  6681. } catch (err) {
  6682. console.error('Failed to load AeroTUN:', err);
  6683. }
  6684. }
  6685. function renderAeroTUN() {
  6686. const tbody = document.getElementById('aerotun-table-body');
  6687. const empty = document.getElementById('aerotun-empty');
  6688. // Update summary cards
  6689. const stats = state.aerotunStats || {};
  6690. const tunnels = state.aerotunTunnels || [];
  6691. const statActive = document.getElementById('aerotun-stat-active');
  6692. if (statActive) {
  6693. const activeCount = tunnels.filter(t => t.running).length;
  6694. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6695. }
  6696. const statSaved = document.getElementById('aerotun-stat-saved');
  6697. if (statSaved) {
  6698. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6699. }
  6700. const statRatio = document.getElementById('aerotun-stat-ratio');
  6701. if (statRatio) {
  6702. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6703. }
  6704. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6705. if (statTraffic) {
  6706. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6707. }
  6708. if (!tbody) return;
  6709. tbody.innerHTML = '';
  6710. if (tunnels.length === 0) {
  6711. empty?.classList.remove('hidden');
  6712. return;
  6713. }
  6714. empty?.classList.add('hidden');
  6715. tunnels.forEach(t => {
  6716. const tr = document.createElement('tr');
  6717. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6718. const modeBadge = t.mode === 'server'
  6719. ? `<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>`
  6720. : `<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>`;
  6721. const endpointInfo = t.mode === 'server'
  6722. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6723. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6724. const compBadge = t.compression
  6725. ? `<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>`
  6726. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6727. const activePeer = t.active_peer_endpoint
  6728. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6729. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6730. const rawRx = formatBytes(t.rx_bytes || 0);
  6731. const rawTx = formatBytes(t.tx_bytes || 0);
  6732. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6733. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6734. tr.innerHTML = `
  6735. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6736. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6737. <span>${escapeHtml(t.name)}</span>
  6738. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6739. </td>
  6740. <td class="py-2.5 px-3">${modeBadge}</td>
  6741. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6742. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6743. <td class="py-2.5 px-3">${compBadge}</td>
  6744. <td class="py-2.5 px-3">${activePeer}</td>
  6745. <td class="py-2.5 px-3 font-mono text-[11px]">
  6746. <span class="text-emerald-400">↓ ${rawRx}</span>
  6747. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6748. </td>
  6749. <td class="py-2.5 px-3 font-mono text-[11px]">
  6750. <span class="text-slate-400">↓ ${wireRx}</span>
  6751. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6752. </td>
  6753. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6754. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6755. ${t.running
  6756. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6757. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6758. }
  6759. <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>
  6760. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6761. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6762. </td>
  6763. `;
  6764. tbody.appendChild(tr);
  6765. });
  6766. }
  6767. function onAeroTUNModeChange() {
  6768. const mode = document.getElementById('aerotun-modal-mode').value;
  6769. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6770. const portInput = document.getElementById('aerotun-modal-port');
  6771. if (mode === 'server') {
  6772. if (!portInput.value) portInput.value = '51830';
  6773. endpointInput.placeholder = 'Optional / learned roaming peer';
  6774. } else {
  6775. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6776. if (!portInput.value) portInput.value = '';
  6777. }
  6778. }
  6779. async function generateAeroTUNKey() {
  6780. try {
  6781. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6782. if (res.ok) {
  6783. const data = await res.json();
  6784. document.getElementById('aerotun-modal-psk').value = data.key;
  6785. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6786. }
  6787. } catch (err) {
  6788. const arr = new Uint8Array(32);
  6789. crypto.getRandomValues(arr);
  6790. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6791. document.getElementById('aerotun-modal-psk').value = hex;
  6792. }
  6793. }
  6794. function openAddAeroTUNModal() {
  6795. const tunnels = state.aerotunTunnels || [];
  6796. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6797. document.getElementById('aerotun-modal-id').value = '';
  6798. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6799. document.getElementById('aerotun-modal-mode').value = 'server';
  6800. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6801. document.getElementById('aerotun-modal-endpoint').value = '';
  6802. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6803. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6804. document.getElementById('aerotun-modal-psk').value = '';
  6805. document.getElementById('aerotun-modal-mtu').value = '1420';
  6806. document.getElementById('aerotun-modal-comment').value = '';
  6807. document.getElementById('aerotun-modal-compression').checked = true;
  6808. document.getElementById('aerotun-modal-defroute').checked = false;
  6809. document.getElementById('aerotun-modal-disabled').checked = false;
  6810. generateAeroTUNKey();
  6811. onAeroTUNModeChange();
  6812. document.getElementById('aerotun-modal').classList.remove('hidden');
  6813. }
  6814. function openEditAeroTUNModal(id) {
  6815. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6816. if (!t) return;
  6817. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6818. document.getElementById('aerotun-modal-id').value = t.id;
  6819. document.getElementById('aerotun-modal-name').value = t.name;
  6820. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6821. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6822. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6823. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6824. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6825. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6826. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6827. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6828. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6829. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6830. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6831. onAeroTUNModeChange();
  6832. document.getElementById('aerotun-modal').classList.remove('hidden');
  6833. }
  6834. function closeAeroTUNModal() {
  6835. document.getElementById('aerotun-modal').classList.add('hidden');
  6836. }
  6837. async function submitSaveAeroTUN(e) {
  6838. e.preventDefault();
  6839. const id = document.getElementById('aerotun-modal-id').value;
  6840. const name = document.getElementById('aerotun-modal-name').value.trim();
  6841. const mode = document.getElementById('aerotun-modal-mode').value;
  6842. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6843. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6844. const local = document.getElementById('aerotun-modal-local').value.trim();
  6845. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6846. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6847. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6848. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6849. const compression = document.getElementById('aerotun-modal-compression').checked;
  6850. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6851. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6852. if (mode === 'client' && !endpoint) {
  6853. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6854. return;
  6855. }
  6856. if (!psk) {
  6857. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6858. return;
  6859. }
  6860. try {
  6861. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6862. method: 'POST',
  6863. headers: { 'Content-Type': 'application/json' },
  6864. body: JSON.stringify({
  6865. id,
  6866. name,
  6867. mode,
  6868. listen_port: port,
  6869. remote_endpoint: endpoint,
  6870. local_address: local,
  6871. peer_address: peer,
  6872. psk,
  6873. mtu,
  6874. compression,
  6875. default_route: defaultRoute,
  6876. comment,
  6877. disabled
  6878. })
  6879. });
  6880. if (res.ok) {
  6881. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6882. closeAeroTUNModal();
  6883. loadAeroTUN(false);
  6884. fetchData(false);
  6885. } else {
  6886. const err = await res.text();
  6887. showToast('Error Saving Tunnel', err, 'error');
  6888. }
  6889. } catch (err) {
  6890. showToast('Network Error', err.message, 'error');
  6891. }
  6892. }
  6893. async function startAeroTUNTunnel(id) {
  6894. try {
  6895. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6896. if (res.ok) {
  6897. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6898. loadAeroTUN(false);
  6899. fetchData(false);
  6900. } else {
  6901. const err = await res.text();
  6902. showToast('Failed to Start', err, 'error');
  6903. }
  6904. } catch (err) {
  6905. showToast('Error', err.message, 'error');
  6906. }
  6907. }
  6908. async function stopAeroTUNTunnel(id) {
  6909. try {
  6910. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6911. if (res.ok) {
  6912. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6913. loadAeroTUN(false);
  6914. fetchData(false);
  6915. } else {
  6916. const err = await res.text();
  6917. showToast('Failed to Stop', err, 'error');
  6918. }
  6919. } catch (err) {
  6920. showToast('Error', err.message, 'error');
  6921. }
  6922. }
  6923. async function toggleAeroTUNState(id, disabled) {
  6924. try {
  6925. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6926. method: 'POST',
  6927. headers: { 'Content-Type': 'application/json' },
  6928. body: JSON.stringify({ disabled })
  6929. });
  6930. if (res.ok) {
  6931. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6932. loadAeroTUN(false);
  6933. fetchData(false);
  6934. }
  6935. } catch (err) {
  6936. showToast('Error', err.message, 'error');
  6937. }
  6938. }
  6939. async function deleteAeroTUN(id) {
  6940. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6941. try {
  6942. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6943. if (res.ok) {
  6944. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6945. loadAeroTUN(false);
  6946. fetchData(false);
  6947. }
  6948. } catch (err) {
  6949. showToast('Error', err.message, 'error');
  6950. }
  6951. }
  6952. // ======================== PPP Central Hub & Servers ========================
  6953. function switchPPPSubTab(tab) {
  6954. state.pppSubTab = tab;
  6955. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6956. tabs.forEach(t => {
  6957. const panel = document.getElementById(`ppp-subtab-${t}`);
  6958. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6959. if (panel) {
  6960. if (t === tab) panel.classList.remove('hidden');
  6961. else panel.classList.add('hidden');
  6962. }
  6963. if (btn) {
  6964. if (t === tab) {
  6965. 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';
  6966. } else {
  6967. 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';
  6968. }
  6969. }
  6970. });
  6971. const addBtn = document.getElementById('ppp-primary-add-btn');
  6972. if (addBtn) {
  6973. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6974. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6975. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6976. else addBtn.innerHTML = '<span>Save Config</span>';
  6977. }
  6978. if (tab === 'active') loadPPPSessions();
  6979. }
  6980. function openCurrentPPPModal() {
  6981. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6982. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6983. else if (state.pppSubTab === 'active') loadPPPSessions();
  6984. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6985. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6986. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6987. }
  6988. async function loadPPP(populateDropdowns = true) {
  6989. await Promise.all([
  6990. loadPPPSecrets(),
  6991. loadPPPProfiles(),
  6992. loadPPPServers(),
  6993. loadPPPSessions()
  6994. ]);
  6995. }
  6996. async function loadPPPSecrets() {
  6997. try {
  6998. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6999. const data = await res.json();
  7000. state.pppSecrets = Array.isArray(data) ? data : [];
  7001. const b = document.getElementById('ppp-badge-secrets');
  7002. if (b) b.innerText = state.pppSecrets.length;
  7003. const b2 = document.getElementById('secrets-count-badge');
  7004. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7005. renderPPPSecrets();
  7006. } catch (err) {
  7007. console.error('Failed to load PPP secrets:', err);
  7008. }
  7009. }
  7010. function renderPPPSecrets() {
  7011. const tbody = document.getElementById('secrets-table-body');
  7012. const empty = document.getElementById('secrets-empty');
  7013. if (!tbody) return;
  7014. tbody.innerHTML = '';
  7015. const secrets = state.pppSecrets || [];
  7016. if (secrets.length === 0) {
  7017. empty?.classList.remove('hidden');
  7018. return;
  7019. }
  7020. empty?.classList.add('hidden');
  7021. secrets.forEach(s => {
  7022. const tr = document.createElement('tr');
  7023. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7024. tr.innerHTML = `
  7025. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7026. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7027. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7028. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7029. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7030. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7031. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7032. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7033. <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>
  7034. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7035. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7036. </td>
  7037. `;
  7038. tbody.appendChild(tr);
  7039. });
  7040. }
  7041. async function loadPPPProfiles() {
  7042. try {
  7043. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7044. const data = await res.json();
  7045. state.pppProfiles = Array.isArray(data) ? data : [];
  7046. const b = document.getElementById('ppp-badge-profiles');
  7047. if (b) b.innerText = state.pppProfiles.length;
  7048. const b2 = document.getElementById('profiles-count-badge');
  7049. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7050. // Populate profile selects across modals
  7051. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7052. selects.forEach(sid => {
  7053. const el = document.getElementById(sid);
  7054. if (!el) return;
  7055. const cur = el.value;
  7056. el.innerHTML = '';
  7057. state.pppProfiles.forEach(p => {
  7058. const opt = document.createElement('option');
  7059. opt.value = p.name;
  7060. opt.innerText = `${p.name} (${p.remote_address})`;
  7061. if (p.name === cur) opt.selected = true;
  7062. el.appendChild(opt);
  7063. });
  7064. });
  7065. renderPPPProfiles();
  7066. } catch (err) {
  7067. console.error('Failed to load PPP profiles:', err);
  7068. }
  7069. }
  7070. function renderPPPProfiles() {
  7071. const tbody = document.getElementById('profiles-table-body');
  7072. if (!tbody) return;
  7073. tbody.innerHTML = '';
  7074. (state.pppProfiles || []).forEach(p => {
  7075. const isDefault = p.name.startsWith('default');
  7076. const tr = document.createElement('tr');
  7077. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7078. tr.innerHTML = `
  7079. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7080. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7081. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7082. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7083. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7084. <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>
  7085. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7086. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7087. ${!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>`}
  7088. </td>
  7089. `;
  7090. tbody.appendChild(tr);
  7091. });
  7092. }
  7093. async function loadPPPServers() {
  7094. try {
  7095. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7096. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7097. fetch(`${API_BASE}/vpn/servers/pptp`),
  7098. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7099. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7100. ]);
  7101. if (pppoeRes.ok) {
  7102. state.pppoeServer = await pppoeRes.json();
  7103. const s = state.pppoeServer;
  7104. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7105. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7106. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7107. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7108. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7109. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7110. const pill = document.getElementById('pppoe-server-status-pill');
  7111. if (pill) {
  7112. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7113. 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';
  7114. }
  7115. setDotBadge('ppp-badge-pppoe-state', s.running);
  7116. }
  7117. if (pptpRes.ok) {
  7118. state.pptpServer = await pptpRes.json();
  7119. const s = state.pptpServer;
  7120. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7121. document.getElementById('pptp-server-port').value = s.port || 1723;
  7122. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7123. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7124. const pill = document.getElementById('pptp-server-status-pill');
  7125. if (pill) {
  7126. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7127. 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';
  7128. }
  7129. setDotBadge('ppp-badge-pptp-state', s.running);
  7130. }
  7131. if (l2tpRes.ok) {
  7132. state.l2tpServer = await l2tpRes.json();
  7133. const s = state.l2tpServer;
  7134. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7135. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7136. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7137. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7138. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7139. const pill = document.getElementById('l2tp-server-status-pill');
  7140. if (pill) {
  7141. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7142. 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';
  7143. }
  7144. setDotBadge('ppp-badge-l2tp-state', s.running);
  7145. }
  7146. if (ipsecRes.ok) {
  7147. state.ipsecServer = await ipsecRes.json();
  7148. const s = state.ipsecServer;
  7149. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7150. if (modalEn) modalEn.checked = !!s.enabled;
  7151. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7152. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7153. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7154. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7155. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7156. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7157. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7158. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7159. const pill = document.getElementById('modal-ipsec-server-status');
  7160. if (pill) {
  7161. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7162. 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';
  7163. }
  7164. }
  7165. } catch (err) {
  7166. console.error('Failed to load VPN servers:', err);
  7167. }
  7168. }
  7169. async function loadPPPSessions() {
  7170. try {
  7171. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7172. const data = await res.json();
  7173. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7174. const b = document.getElementById('ppp-badge-active');
  7175. if (b) b.innerText = state.pppActiveSessions.length;
  7176. const sideB = document.getElementById('badge-ppp-sessions');
  7177. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7178. renderPPPSessions();
  7179. } catch (err) {
  7180. console.error('Failed to load active PPP sessions:', err);
  7181. }
  7182. }
  7183. function renderPPPSessions() {
  7184. const tbody = document.getElementById('active-ppp-table-body');
  7185. const empty = document.getElementById('active-ppp-empty');
  7186. if (!tbody) return;
  7187. tbody.innerHTML = '';
  7188. const list = state.pppActiveSessions || [];
  7189. if (list.length === 0) {
  7190. empty?.classList.remove('hidden');
  7191. return;
  7192. }
  7193. empty?.classList.add('hidden');
  7194. list.forEach(s => {
  7195. const tr = document.createElement('tr');
  7196. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7197. tr.innerHTML = `
  7198. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7199. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7200. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7201. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7202. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7203. <td class="py-2.5 px-3 text-[11px]">
  7204. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7205. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7206. </td>
  7207. <td class="py-2.5 px-3 text-right font-sans">
  7208. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7209. </td>
  7210. `;
  7211. tbody.appendChild(tr);
  7212. });
  7213. }
  7214. async function disconnectPPPSession(iface) {
  7215. if (!confirm(`Disconnect session ${iface}?`)) return;
  7216. try {
  7217. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7218. if (res.ok) {
  7219. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7220. loadPPPSessions();
  7221. }
  7222. } catch (err) {
  7223. showToast('Error', err.message, 'error');
  7224. }
  7225. }
  7226. // PPP Secret Modal handlers
  7227. function openAddPPPSecretModal() {
  7228. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7229. document.getElementById('secret-modal-id').value = '';
  7230. document.getElementById('secret-modal-name').value = '';
  7231. document.getElementById('secret-modal-password').value = '';
  7232. document.getElementById('secret-modal-service').value = 'any';
  7233. document.getElementById('secret-modal-profile').value = 'default';
  7234. document.getElementById('secret-modal-local').value = '';
  7235. document.getElementById('secret-modal-remote').value = '';
  7236. document.getElementById('secret-modal-comment').value = '';
  7237. document.getElementById('secret-modal-disabled').checked = false;
  7238. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7239. }
  7240. function openEditPPPSecretModal(id) {
  7241. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7242. if (!s) return;
  7243. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7244. document.getElementById('secret-modal-id').value = s.id;
  7245. document.getElementById('secret-modal-name').value = s.name;
  7246. document.getElementById('secret-modal-password').value = s.password;
  7247. document.getElementById('secret-modal-service').value = s.service || 'any';
  7248. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7249. document.getElementById('secret-modal-local').value = s.local_address || '';
  7250. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7251. document.getElementById('secret-modal-comment').value = s.comment || '';
  7252. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7253. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7254. }
  7255. function closePPPSecretModal() {
  7256. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7257. }
  7258. async function submitSavePPPSecret(e) {
  7259. e.preventDefault();
  7260. const id = document.getElementById('secret-modal-id').value;
  7261. const name = document.getElementById('secret-modal-name').value.trim();
  7262. const password = document.getElementById('secret-modal-password').value.trim();
  7263. const service = document.getElementById('secret-modal-service').value;
  7264. const profile = document.getElementById('secret-modal-profile').value;
  7265. const local = document.getElementById('secret-modal-local').value.trim();
  7266. const remote = document.getElementById('secret-modal-remote').value.trim();
  7267. const comment = document.getElementById('secret-modal-comment').value.trim();
  7268. const disabled = document.getElementById('secret-modal-disabled').checked;
  7269. try {
  7270. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7271. method: 'POST',
  7272. headers: { 'Content-Type': 'application/json' },
  7273. body: JSON.stringify({
  7274. id,
  7275. name,
  7276. password,
  7277. service,
  7278. profile,
  7279. local_address: local,
  7280. remote_address: remote,
  7281. comment,
  7282. disabled
  7283. })
  7284. });
  7285. if (res.ok) {
  7286. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7287. closePPPSecretModal();
  7288. loadPPPSecrets();
  7289. } else {
  7290. const err = await res.json();
  7291. showToast('Error', err.message, 'error');
  7292. }
  7293. } catch (err) {
  7294. showToast('Error', err.message, 'error');
  7295. }
  7296. }
  7297. async function togglePPPSecretState(id, disabled) {
  7298. try {
  7299. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7300. method: 'POST',
  7301. headers: { 'Content-Type': 'application/json' },
  7302. body: JSON.stringify({ disabled })
  7303. });
  7304. if (res.ok) {
  7305. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7306. loadPPPSecrets();
  7307. }
  7308. } catch (err) {
  7309. showToast('Error', err.message, 'error');
  7310. }
  7311. }
  7312. async function deletePPPSecret(id) {
  7313. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7314. try {
  7315. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7316. if (res.ok) {
  7317. showToast('Deleted', 'Secret account removed', 'success');
  7318. loadPPPSecrets();
  7319. }
  7320. } catch (err) {
  7321. showToast('Error', err.message, 'error');
  7322. }
  7323. }
  7324. // PPP Profile Modal handlers
  7325. function openAddPPPProfileModal() {
  7326. document.getElementById('profile-modal-name').value = '';
  7327. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7328. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7329. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7330. document.getElementById('profile-modal-encryption').value = 'required';
  7331. document.getElementById('profile-modal-onlyone').checked = true;
  7332. document.getElementById('profile-modal-comment').value = '';
  7333. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7334. }
  7335. function closePPPProfileModal() {
  7336. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7337. }
  7338. async function submitSavePPPProfile(e) {
  7339. e.preventDefault();
  7340. const name = document.getElementById('profile-modal-name').value.trim();
  7341. const local = document.getElementById('profile-modal-local').value.trim();
  7342. const remote = document.getElementById('profile-modal-remote').value.trim();
  7343. const dns = document.getElementById('profile-modal-dns').value.trim();
  7344. const enc = document.getElementById('profile-modal-encryption').value;
  7345. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7346. const comment = document.getElementById('profile-modal-comment').value.trim();
  7347. try {
  7348. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7349. method: 'POST',
  7350. headers: { 'Content-Type': 'application/json' },
  7351. body: JSON.stringify({
  7352. id: name,
  7353. name,
  7354. local_address: local,
  7355. remote_address: remote,
  7356. dns_servers: dns,
  7357. use_encryption: enc,
  7358. only_one: onlyone,
  7359. comment
  7360. })
  7361. });
  7362. if (res.ok) {
  7363. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7364. closePPPProfileModal();
  7365. loadPPPProfiles();
  7366. } else {
  7367. const err = await res.json();
  7368. showToast('Error', err.message, 'error');
  7369. }
  7370. } catch (err) {
  7371. showToast('Error', err.message, 'error');
  7372. }
  7373. }
  7374. async function deletePPPProfile(name) {
  7375. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7376. try {
  7377. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7378. if (res.ok) {
  7379. showToast('Deleted', 'Profile removed', 'success');
  7380. loadPPPProfiles();
  7381. } else {
  7382. const err = await res.json();
  7383. showToast('Error', err.message, 'error');
  7384. }
  7385. } catch (err) {
  7386. showToast('Error', err.message, 'error');
  7387. }
  7388. }
  7389. // Server Config submissions
  7390. async function savePPPoEServerConfig(e) {
  7391. e.preventDefault();
  7392. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7393. const name = document.getElementById('pppoe-server-name').value.trim();
  7394. const iface = document.getElementById('pppoe-server-iface').value;
  7395. const profile = document.getElementById('pppoe-server-profile').value;
  7396. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7397. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7398. try {
  7399. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7400. method: 'POST',
  7401. headers: { 'Content-Type': 'application/json' },
  7402. body: JSON.stringify({
  7403. enabled,
  7404. service_name: name,
  7405. interface: iface,
  7406. default_profile: profile,
  7407. max_mtu: mtu,
  7408. max_mru: mtu,
  7409. one_session_per_host: onesession
  7410. })
  7411. });
  7412. if (res.ok) {
  7413. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7414. loadPPPServers();
  7415. fetchData(false);
  7416. } else {
  7417. const err = await res.json();
  7418. showToast('Error', err.message, 'error');
  7419. }
  7420. } catch (err) {
  7421. showToast('Error', err.message, 'error');
  7422. }
  7423. }
  7424. async function savePPTPServerConfig(e) {
  7425. e.preventDefault();
  7426. const enabled = document.getElementById('pptp-server-enabled').checked;
  7427. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7428. const profile = document.getElementById('pptp-server-profile').value;
  7429. const mppe = document.getElementById('pptp-server-mppe').checked;
  7430. try {
  7431. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7432. method: 'POST',
  7433. headers: { 'Content-Type': 'application/json' },
  7434. body: JSON.stringify({
  7435. enabled,
  7436. port,
  7437. default_profile: profile,
  7438. require_mppe: mppe
  7439. })
  7440. });
  7441. if (res.ok) {
  7442. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7443. loadPPPServers();
  7444. fetchData(false);
  7445. } else {
  7446. const err = await res.json();
  7447. showToast('Error', err.message, 'error');
  7448. }
  7449. } catch (err) {
  7450. showToast('Error', err.message, 'error');
  7451. }
  7452. }
  7453. async function saveL2TPServerConfig(e) {
  7454. e.preventDefault();
  7455. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7456. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7457. const profile = document.getElementById('l2tp-server-profile').value;
  7458. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7459. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7460. try {
  7461. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7462. method: 'POST',
  7463. headers: { 'Content-Type': 'application/json' },
  7464. body: JSON.stringify({
  7465. enabled,
  7466. port,
  7467. default_profile: profile,
  7468. use_ipsec: useipsec,
  7469. ipsec_secret: psk
  7470. })
  7471. });
  7472. if (res.ok) {
  7473. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7474. loadPPPServers();
  7475. fetchData(false);
  7476. } else {
  7477. const err = await res.json();
  7478. showToast('Error', err.message, 'error');
  7479. }
  7480. } catch (err) {
  7481. showToast('Error', err.message, 'error');
  7482. }
  7483. }
  7484. // IPSec Server Modal
  7485. function openIPSecServerModal() {
  7486. loadPPPServers();
  7487. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7488. }
  7489. function closeIPSecServerModal() {
  7490. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7491. }
  7492. async function submitSaveIPSecServer(e) {
  7493. e.preventDefault();
  7494. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7495. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7496. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7497. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7498. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7499. try {
  7500. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7501. method: 'POST',
  7502. headers: { 'Content-Type': 'application/json' },
  7503. body: JSON.stringify({
  7504. enabled,
  7505. preshared_key: psk,
  7506. pool_address: pool,
  7507. dns_servers: dns,
  7508. local_subnet: subnet
  7509. })
  7510. });
  7511. if (res.ok) {
  7512. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7513. closeIPSecServerModal();
  7514. loadPPPServers();
  7515. fetchData(false);
  7516. } else {
  7517. const err = await res.json();
  7518. showToast('Error', err.message, 'error');
  7519. }
  7520. } catch (err) {
  7521. showToast('Error', err.message, 'error');
  7522. }
  7523. }
  7524. // WireGuard Client Config Viewer
  7525. let currentWGClientConf = '';
  7526. async function openWGClientConfModal(iface, clientIP) {
  7527. try {
  7528. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7529. method: 'POST',
  7530. headers: { 'Content-Type': 'application/json' },
  7531. body: JSON.stringify({
  7532. interface: iface,
  7533. address: clientIP || '10.10.0.2/32',
  7534. dns: '1.1.1.1, 8.8.8.8'
  7535. })
  7536. });
  7537. if (res.ok) {
  7538. const data = await res.json();
  7539. currentWGClientConf = data.config;
  7540. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7541. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7542. } else {
  7543. const err = await res.json();
  7544. showToast('Error', err.message, 'error');
  7545. }
  7546. } catch (err) {
  7547. showToast('Error', err.message, 'error');
  7548. }
  7549. }
  7550. function closeWGClientConfModal() {
  7551. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7552. }
  7553. function copyWGClientConf() {
  7554. if (!currentWGClientConf) return;
  7555. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7556. }
  7557. function downloadWGClientConf() {
  7558. if (!currentWGClientConf) return;
  7559. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7560. const a = document.createElement('a');
  7561. a.href = URL.createObjectURL(blob);
  7562. a.download = 'wireguard-client.conf';
  7563. document.body.appendChild(a);
  7564. a.click();
  7565. document.body.removeChild(a);
  7566. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7567. }
  7568. // =========================================================================
  7569. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7570. // =========================================================================
  7571. state.activeDynSubTab = 'bgp-peers';
  7572. state.activeBgpSubTab = 'bgp-peers';
  7573. state.activeOspfTab = 'instances';
  7574. state.bgpInstance = null;
  7575. state.bgpPeers = [];
  7576. state.bgpNets = [];
  7577. state.bgpRoutes = [];
  7578. state.ospfInstance = null;
  7579. state.ospfInstances = [];
  7580. state.ospfAreas = [];
  7581. state.ospfAreaRanges = [];
  7582. state.ospfTemplates = [];
  7583. state.ospfLiveInterfaces = [];
  7584. state.ospfStaticNbrs = [];
  7585. state.ospfNeighbors = [];
  7586. state.ospfLSA = [];
  7587. state.ospfRoutes = [];
  7588. state.selectedOspfRow = {
  7589. instances: null,
  7590. areas: null,
  7591. 'area-ranges': null,
  7592. templates: null,
  7593. interfaces: null,
  7594. 'static-nbrs': null,
  7595. neighbors: null,
  7596. lsa: null,
  7597. };
  7598. state.ospfSort = {
  7599. instances: { col: 'name', asc: true },
  7600. areas: { col: 'name', asc: true },
  7601. ranges: { col: 'area', asc: true },
  7602. templates: { col: 'interfaces', asc: true },
  7603. live_ifaces: { col: 'interface', asc: true },
  7604. snbrs: { col: 'address', asc: true },
  7605. neighbors: { col: 'address', asc: true },
  7606. lsa: { col: 'instance', asc: true },
  7607. };
  7608. function switchBgpSubTab(subTab) {
  7609. state.activeBgpSubTab = subTab;
  7610. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7611. tabs.forEach(t => {
  7612. const el = document.getElementById(`dyn-subtab-${t}`);
  7613. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7614. if (el) el.classList.toggle('hidden', t !== subTab);
  7615. if (btn) {
  7616. if (t === subTab) {
  7617. 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';
  7618. } else {
  7619. 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';
  7620. }
  7621. }
  7622. });
  7623. }
  7624. function switchOspfTab(tabName) {
  7625. state.activeOspfTab = tabName;
  7626. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7627. tabs.forEach(t => {
  7628. const pane = document.getElementById(`ospf-pane-${t}`);
  7629. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7630. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7631. if (btn) {
  7632. if (t === tabName) {
  7633. 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';
  7634. } else {
  7635. 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';
  7636. }
  7637. }
  7638. });
  7639. }
  7640. function switchOspfSubTab(tab) {
  7641. // Legacy alias
  7642. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7643. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7644. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7645. else switchOspfTab('instances');
  7646. }
  7647. function switchDynSubTab(subTab) {
  7648. if (subTab.startsWith('bgp')) {
  7649. if (state.activeTab !== 'bgp') navigate('bgp');
  7650. switchBgpSubTab(subTab);
  7651. } else if (subTab.startsWith('ospf')) {
  7652. if (state.activeTab !== 'ospf') navigate('ospf');
  7653. switchOspfTab('instances');
  7654. }
  7655. }
  7656. async function loadDynamicRouting(showToastMsg = false) {
  7657. try {
  7658. const fetchSafeJson = async (url) => {
  7659. try {
  7660. const r = await fetch(url);
  7661. return r.ok ? await r.json() : null;
  7662. } catch (e) {
  7663. return null;
  7664. }
  7665. };
  7666. const [
  7667. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7668. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7669. selectRules, commLists, asLists
  7670. ] = await Promise.all([
  7671. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7672. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7673. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7674. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7675. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7676. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7677. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7678. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7679. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7680. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7681. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7682. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7683. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7684. fetchSafeJson(`${API_BASE}/routing/filters`),
  7685. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7686. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7687. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7688. ]);
  7689. if (sum) state.dynSummary = sum;
  7690. if (bgpInst) state.bgpInstance = bgpInst;
  7691. if (bgpPeers) state.bgpPeers = bgpPeers;
  7692. if (bgpNets) state.bgpNets = bgpNets;
  7693. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7694. if (ospfInsts) state.ospfInstances = ospfInsts;
  7695. if (ospfAreas) state.ospfAreas = ospfAreas;
  7696. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7697. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7698. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7699. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7700. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7701. if (ospfLsa) state.ospfLSA = ospfLsa;
  7702. if (filters) state.routingFilters = filters;
  7703. if (selectRules) state.routingSelectRules = selectRules;
  7704. if (commLists) state.routingCommunityLists = commLists;
  7705. if (asLists) state.routingASLists = asLists;
  7706. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7707. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7708. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7709. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7710. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7711. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7712. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7713. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7714. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7715. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7716. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7717. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7718. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7719. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7720. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7721. } catch (err) {
  7722. console.error('Failed to load dynamic routing:', err);
  7723. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7724. }
  7725. }
  7726. async function loadOspfAll() {
  7727. await loadDynamicRouting(true);
  7728. }
  7729. function renderBgpStatusPill() {
  7730. const pill = document.getElementById('bgp-live-status-pill');
  7731. if (!pill) return;
  7732. const inst = state.bgpInstance;
  7733. if (!inst || !inst.enabled) {
  7734. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7735. pill.innerText = 'BGP DISABLED';
  7736. } else if (inst.running) {
  7737. 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';
  7738. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7739. } else {
  7740. 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';
  7741. pill.innerText = 'BGP STARTING...';
  7742. }
  7743. }
  7744. function renderBgpPeers() {
  7745. const tbody = document.getElementById('bgp-peers-table-body');
  7746. if (!tbody) return;
  7747. const empty = document.getElementById('bgp-peers-empty');
  7748. const countBadge = document.getElementById('bgp-peers-count-badge');
  7749. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7750. const peers = state.bgpPeers || [];
  7751. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7752. if (navBadge) navBadge.innerText = peers.length;
  7753. if (peers.length === 0) {
  7754. tbody.innerHTML = '';
  7755. if (empty) empty.classList.remove('hidden');
  7756. return;
  7757. }
  7758. if (empty) empty.classList.add('hidden');
  7759. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7760. if (tbody.dataset.sig === sig) return;
  7761. tbody.dataset.sig = sig;
  7762. tbody.innerHTML = peers.map(p => {
  7763. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7764. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7765. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7766. let stateBadge = '';
  7767. if (p.disabled) {
  7768. 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>';
  7769. } else if (p.state === 'Established') {
  7770. 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>';
  7771. } else if (p.state === 'Connect' || p.state === 'Active') {
  7772. 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>`;
  7773. } else {
  7774. 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>`;
  7775. }
  7776. return `
  7777. <tr class="hover:bg-slate-800/40 transition">
  7778. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7779. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7780. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7781. <td class="py-2.5 px-3">
  7782. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7783. ${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>`}
  7784. </td>
  7785. <td class="py-2.5 px-3">${stateBadge}</td>
  7786. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7787. <td class="py-2.5 px-3 text-slate-300">
  7788. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7789. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7790. </td>
  7791. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7792. ${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> ` : ''}
  7793. ${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>` : ''}
  7794. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7795. </td>
  7796. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7797. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7798. <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'}">
  7799. ${p.disabled ? 'Enable' : 'Disable'}
  7800. </button>
  7801. <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">
  7802. Edit
  7803. </button>
  7804. <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">
  7805. Delete
  7806. </button>
  7807. </td>
  7808. </tr>
  7809. `;
  7810. }).join('');
  7811. }
  7812. function renderBgpNetworks() {
  7813. const tbody = document.getElementById('bgp-nets-table-body');
  7814. if (!tbody) return;
  7815. const empty = document.getElementById('bgp-nets-empty');
  7816. const countBadge = document.getElementById('bgp-nets-count-badge');
  7817. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7818. const nets = state.bgpNets || [];
  7819. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7820. if (navBadge) navBadge.innerText = nets.length;
  7821. if (nets.length === 0) {
  7822. tbody.innerHTML = '';
  7823. if (empty) empty.classList.remove('hidden');
  7824. return;
  7825. }
  7826. if (empty) empty.classList.add('hidden');
  7827. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7828. if (tbody.dataset.sig === sig) return;
  7829. tbody.dataset.sig = sig;
  7830. tbody.innerHTML = nets.map(n => `
  7831. <tr class="hover:bg-slate-800/40 transition">
  7832. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7833. <td class="py-2.5 px-3">
  7834. ${n.disabled
  7835. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7836. : '<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>'}
  7837. </td>
  7838. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7839. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7840. <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">
  7841. Delete
  7842. </button>
  7843. </td>
  7844. </tr>
  7845. `).join('');
  7846. }
  7847. function renderBgpRoutes() {
  7848. const tbody = document.getElementById('bgp-routes-table-body');
  7849. if (!tbody) return;
  7850. const empty = document.getElementById('bgp-routes-empty');
  7851. const countBadge = document.getElementById('bgp-routes-count-badge');
  7852. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7853. const routes = state.bgpRoutes || [];
  7854. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7855. if (navBadge) navBadge.innerText = routes.length;
  7856. if (routes.length === 0) {
  7857. tbody.innerHTML = '';
  7858. if (empty) empty.classList.remove('hidden');
  7859. return;
  7860. }
  7861. if (empty) empty.classList.add('hidden');
  7862. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7863. if (tbody.dataset.sig === sig) return;
  7864. tbody.dataset.sig = sig;
  7865. tbody.innerHTML = routes.map(r => `
  7866. <tr class="hover:bg-slate-800/40 transition">
  7867. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7868. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7869. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7870. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7871. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7872. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7873. </tr>
  7874. `).join('');
  7875. }
  7876. // =========================================================================
  7877. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7878. // =========================================================================
  7879. function sortOspfTable(tab, col) {
  7880. if (!state.ospfSort) state.ospfSort = {};
  7881. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7882. if (state.ospfSort[tab].col === col) {
  7883. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7884. } else {
  7885. state.ospfSort[tab].col = col;
  7886. state.ospfSort[tab].asc = true;
  7887. }
  7888. const asc = state.ospfSort[tab].asc;
  7889. let list = [];
  7890. if (tab === 'instances') list = state.ospfInstances || [];
  7891. else if (tab === 'areas') list = state.ospfAreas || [];
  7892. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7893. else if (tab === 'templates') list = state.ospfTemplates || [];
  7894. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7895. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7896. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7897. else if (tab === 'lsa') list = state.ospfLSA || [];
  7898. list.sort((a, b) => {
  7899. let valA = a[col] ?? '';
  7900. let valB = b[col] ?? '';
  7901. if (typeof valA === 'number' && typeof valB === 'number') {
  7902. return asc ? valA - valB : valB - valA;
  7903. }
  7904. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7905. });
  7906. if (tab === 'instances') renderOspfInstances();
  7907. else if (tab === 'areas') renderOspfAreas();
  7908. else if (tab === 'ranges') renderOspfAreaRanges();
  7909. else if (tab === 'templates') renderOspfTemplates();
  7910. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7911. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7912. else if (tab === 'neighbors') renderOspfNeighbors();
  7913. else if (tab === 'lsa') renderOspfLSA();
  7914. }
  7915. function selectOspfRow(tab, id) {
  7916. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7917. state.selectedOspfRow[tab] = id;
  7918. if (tab === 'instances') {
  7919. renderOspfInstances();
  7920. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7921. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7922. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7923. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7924. if (btnEn) btnEn.disabled = false;
  7925. if (btnDis) btnDis.disabled = false;
  7926. if (btnRem) btnRem.disabled = false;
  7927. if (btnCom) btnCom.disabled = false;
  7928. } else if (tab === 'areas') {
  7929. renderOspfAreas();
  7930. const btnEn = document.getElementById('btn-ospf-area-enable');
  7931. const btnDis = document.getElementById('btn-ospf-area-disable');
  7932. const btnRem = document.getElementById('btn-ospf-area-remove');
  7933. const btnCom = document.getElementById('btn-ospf-area-comment');
  7934. if (btnEn) btnEn.disabled = false;
  7935. if (btnDis) btnDis.disabled = false;
  7936. if (btnRem) btnRem.disabled = false;
  7937. if (btnCom) btnCom.disabled = false;
  7938. } else if (tab === 'ranges') {
  7939. renderOspfAreaRanges();
  7940. const btnEn = document.getElementById('btn-ospf-range-enable');
  7941. const btnDis = document.getElementById('btn-ospf-range-disable');
  7942. const btnRem = document.getElementById('btn-ospf-range-remove');
  7943. const btnCom = document.getElementById('btn-ospf-range-comment');
  7944. if (btnEn) btnEn.disabled = false;
  7945. if (btnDis) btnDis.disabled = false;
  7946. if (btnRem) btnRem.disabled = false;
  7947. if (btnCom) btnCom.disabled = false;
  7948. } else if (tab === 'templates') {
  7949. renderOspfTemplates();
  7950. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7951. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7952. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7953. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7954. if (btnEn) btnEn.disabled = false;
  7955. if (btnDis) btnDis.disabled = false;
  7956. if (btnRem) btnRem.disabled = false;
  7957. if (btnCom) btnCom.disabled = false;
  7958. } else if (tab === 'snbrs') {
  7959. renderOspfStaticNbrs();
  7960. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7961. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7962. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7963. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7964. if (btnEn) btnEn.disabled = false;
  7965. if (btnDis) btnDis.disabled = false;
  7966. if (btnRem) btnRem.disabled = false;
  7967. if (btnCom) btnCom.disabled = false;
  7968. }
  7969. }
  7970. // TAB 1: INSTANCES
  7971. function renderOspfInstances() {
  7972. const tbody = document.getElementById('ospf-instances-table-body');
  7973. if (!tbody) return;
  7974. const countEl = document.getElementById('ospf-instances-footer-count');
  7975. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7976. let list = state.ospfInstances || [];
  7977. if (filter) {
  7978. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7979. }
  7980. if (countEl) countEl.innerText = list.length;
  7981. const selId = state.selectedOspfRow?.instances;
  7982. tbody.innerHTML = list.map((inst, idx) => {
  7983. const isSel = inst.id === selId;
  7984. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7985. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7986. return `
  7987. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7988. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7989. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7990. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7991. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7992. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7993. </td>
  7994. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7995. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7996. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7997. </tr>
  7998. `;
  7999. }).join('');
  8000. }
  8001. // TAB 2: AREAS
  8002. function renderOspfAreas() {
  8003. const tbody = document.getElementById('ospf-areas-table-body');
  8004. if (!tbody) return;
  8005. const countEl = document.getElementById('ospf-areas-footer-count');
  8006. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8007. let list = state.ospfAreas || [];
  8008. if (filter) {
  8009. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8010. }
  8011. if (countEl) countEl.innerText = list.length;
  8012. const selId = state.selectedOspfRow?.areas;
  8013. tbody.innerHTML = list.map((a, idx) => {
  8014. const isSel = a.id === selId;
  8015. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8016. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8017. return `
  8018. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8019. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8020. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8021. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8022. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8023. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8024. </td>
  8025. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8026. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8027. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8028. </tr>
  8029. `;
  8030. }).join('');
  8031. }
  8032. // TAB 3: AREA RANGES
  8033. function renderOspfAreaRanges() {
  8034. const tbody = document.getElementById('ospf-ranges-table-body');
  8035. if (!tbody) return;
  8036. const countEl = document.getElementById('ospf-ranges-footer-count');
  8037. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8038. let list = state.ospfAreaRanges || [];
  8039. if (filter) {
  8040. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8041. }
  8042. if (countEl) countEl.innerText = list.length;
  8043. const selId = state.selectedOspfRow?.['area-ranges'];
  8044. tbody.innerHTML = list.map((r, idx) => {
  8045. const isSel = r.id === selId;
  8046. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8047. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8048. return `
  8049. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8050. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8051. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8052. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8053. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8054. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8055. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8056. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8057. </tr>
  8058. `;
  8059. }).join('');
  8060. }
  8061. // TAB 4: INTERFACE TEMPLATES
  8062. function renderOspfTemplates() {
  8063. const tbody = document.getElementById('ospf-templates-table-body');
  8064. if (!tbody) return;
  8065. const countEl = document.getElementById('ospf-templates-footer-count');
  8066. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8067. let list = state.ospfTemplates || [];
  8068. if (filter) {
  8069. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8070. }
  8071. if (countEl) countEl.innerText = list.length;
  8072. const selId = state.selectedOspfRow?.templates;
  8073. tbody.innerHTML = list.map((t, idx) => {
  8074. const isSel = t.id === selId;
  8075. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8076. const ifaces = t.interfaces || t.interface || 'all';
  8077. const nets = t.networks || t.network || '';
  8078. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8079. return `
  8080. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8081. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8082. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8083. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8084. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8085. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8086. </td>
  8087. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8088. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8089. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8090. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8091. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8092. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8093. </tr>
  8094. `;
  8095. }).join('');
  8096. }
  8097. // TAB 5: LIVE INTERFACES
  8098. function renderOspfLiveInterfaces() {
  8099. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8100. if (!tbody) return;
  8101. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8102. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8103. let list = state.ospfLiveInterfaces || [];
  8104. if (filter) {
  8105. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8106. }
  8107. if (countEl) countEl.innerText = list.length;
  8108. tbody.innerHTML = list.map(i => `
  8109. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8110. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8111. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8112. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8113. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8114. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8115. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8116. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8117. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8118. </tr>
  8119. `).join('');
  8120. }
  8121. // TAB 6: STATIC NEIGHBORS
  8122. function renderOspfStaticNbrs() {
  8123. const tbody = document.getElementById('ospf-snbrs-table-body');
  8124. if (!tbody) return;
  8125. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8126. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8127. let list = state.ospfStaticNbrs || [];
  8128. if (filter) {
  8129. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8130. }
  8131. if (countEl) countEl.innerText = list.length;
  8132. const selId = state.selectedOspfRow?.['static-nbrs'];
  8133. tbody.innerHTML = list.map((n, idx) => {
  8134. const isSel = n.id === selId;
  8135. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8136. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8137. return `
  8138. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8139. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8140. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8141. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8142. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8143. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8144. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8145. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8146. </tr>
  8147. `;
  8148. }).join('');
  8149. }
  8150. // TAB 7: LIVE NEIGHBORS
  8151. function renderOspfNeighbors() {
  8152. const tbody = document.getElementById('ospf-neighbors-table-body');
  8153. if (!tbody) return;
  8154. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8155. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8156. let list = state.ospfNeighbors || [];
  8157. if (filter) {
  8158. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8159. }
  8160. if (countEl) countEl.innerText = list.length;
  8161. tbody.innerHTML = list.map(n => `
  8162. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8163. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8164. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8165. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8166. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8167. </td>
  8168. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8169. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8170. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8171. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8172. </tr>
  8173. `).join('');
  8174. }
  8175. // TAB 8: LINK-STATE DATABASE (LSA)
  8176. function renderOspfLSA() {
  8177. const tbody = document.getElementById('ospf-lsa-table-body');
  8178. if (!tbody) return;
  8179. const countEl = document.getElementById('ospf-lsa-footer-count');
  8180. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8181. let list = state.ospfLSA || [];
  8182. if (filter) {
  8183. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8184. }
  8185. if (countEl) countEl.innerText = list.length;
  8186. tbody.innerHTML = list.map(l => `
  8187. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8188. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8189. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8190. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8191. </td>
  8192. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8193. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8194. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8195. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8196. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8197. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8198. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8199. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8200. </tr>
  8201. `).join('');
  8202. }
  8203. function renderOspfStatusPill() {
  8204. // Maintained for backward compatibility
  8205. const pill = document.getElementById('ospf-live-status-pill');
  8206. if (!pill) return;
  8207. 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';
  8208. pill.innerText = 'OSPF ACTIVE';
  8209. }
  8210. function renderOspfInterfaces() {
  8211. renderOspfTemplates();
  8212. }
  8213. function renderOspfRoutes() {
  8214. // Routes retained in background
  8215. }
  8216. // BGP Modals & Actions
  8217. function openBgpInstanceModal() {
  8218. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8219. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8220. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8221. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8222. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8223. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8224. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8225. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8226. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8227. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8228. }
  8229. function closeBgpInstanceModal() {
  8230. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8231. }
  8232. async function submitBgpInstance(e) {
  8233. e.preventDefault();
  8234. const payload = {
  8235. enabled: document.getElementById('modal-bgp-enabled').checked,
  8236. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8237. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8238. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8239. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8240. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8241. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8242. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8243. };
  8244. try {
  8245. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8246. method: 'POST',
  8247. headers: { 'Content-Type': 'application/json' },
  8248. body: JSON.stringify(payload)
  8249. });
  8250. if (res.ok) {
  8251. closeBgpInstanceModal();
  8252. showToast('Success', 'BGP instance configuration updated', 'success');
  8253. loadDynamicRouting();
  8254. } else {
  8255. const err = await res.json();
  8256. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8257. }
  8258. } catch (err) {
  8259. showToast('Error', err.message, 'error');
  8260. }
  8261. }
  8262. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8263. function switchBgpPeerModalTab(tab) {
  8264. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8265. tabs.forEach(t => {
  8266. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8267. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8268. if (t === tab) {
  8269. if (pane) pane.classList.remove('hidden');
  8270. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8271. } else {
  8272. if (pane) pane.classList.add('hidden');
  8273. 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';
  8274. }
  8275. });
  8276. }
  8277. function addOutputNetworkRow(val = '') {
  8278. const container = document.getElementById('modal-bgp-output-networks-container');
  8279. if (!container) return;
  8280. const row = document.createElement('div');
  8281. row.className = 'flex items-center gap-2 output-net-row';
  8282. row.innerHTML = `
  8283. <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">
  8284. <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>
  8285. `;
  8286. container.appendChild(row);
  8287. }
  8288. function parseBgpTime(val) {
  8289. if (!val) return 0;
  8290. val = String(val).trim();
  8291. if (val.includes(':')) {
  8292. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8293. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8294. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8295. }
  8296. return parseInt(val, 10) || 0;
  8297. }
  8298. function formatBgpTime(secs) {
  8299. if (!secs || secs <= 0) return '00:00:00';
  8300. const h = Math.floor(secs / 3600);
  8301. const m = Math.floor((secs % 3600) / 60);
  8302. const s = secs % 60;
  8303. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8304. }
  8305. function populateBgpRoutingTables() {
  8306. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8307. if (!sel) return;
  8308. const cur = sel.value || 'main';
  8309. sel.innerHTML = '<option value="main">main</option>';
  8310. (state.routingTables || []).forEach(t => {
  8311. if (t.name !== 'main') {
  8312. const opt = document.createElement('option');
  8313. opt.value = t.name;
  8314. opt.innerText = t.name;
  8315. sel.appendChild(opt);
  8316. }
  8317. });
  8318. sel.value = cur;
  8319. }
  8320. function openAddBgpPeerModal() {
  8321. document.getElementById('bgp-peer-form').reset();
  8322. document.getElementById('modal-bgp-peer-id').value = '';
  8323. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8324. // General Tab
  8325. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8326. document.getElementById('modal-bgp-peer-comment').value = '';
  8327. document.getElementById('modal-bgp-peer-name').value = '';
  8328. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8329. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8330. document.getElementById('modal-bgp-peer-local-as').value = '';
  8331. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8332. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8333. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8334. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8335. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8336. document.getElementById('modal-bgp-peer-router-id').value = '';
  8337. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8338. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8339. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8340. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8341. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8342. document.getElementById('modal-bgp-peer-local-port').value = '';
  8343. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8344. document.getElementById('modal-bgp-peer-password').value = '';
  8345. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8346. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8347. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8348. document.getElementById('modal-bgp-peer-connect').checked = true;
  8349. document.getElementById('modal-bgp-peer-listen').checked = true;
  8350. // Extra Tab
  8351. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8352. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8353. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8354. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8355. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8356. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8357. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8358. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8359. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8360. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8361. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8362. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8363. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8364. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8365. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8366. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8367. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8368. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8369. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8370. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8371. // Attributes Tab
  8372. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8373. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8374. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8375. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8376. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8377. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8378. // Filter Tab
  8379. populateFilterChainsDatalist();
  8380. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8381. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8382. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8383. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8384. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8385. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8386. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8387. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8388. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8389. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8390. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8391. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8392. populateBgpRoutingTables();
  8393. const container = document.getElementById('modal-bgp-output-networks-container');
  8394. if (container) {
  8395. container.innerHTML = '';
  8396. addOutputNetworkRow('');
  8397. }
  8398. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8399. if (removeBtn) removeBtn.classList.add('hidden');
  8400. switchBgpPeerModalTab('general');
  8401. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8402. }
  8403. function populateFilterChainsDatalist() {
  8404. const dl = document.getElementById('filter-chains-list');
  8405. if (!dl) return;
  8406. const chains = new Set();
  8407. (state.routingFilters || []).forEach(f => {
  8408. if (f.chain) chains.add(f.chain);
  8409. });
  8410. if (chains.size === 0) {
  8411. chains.add('awmn');
  8412. chains.add('bgp-in');
  8413. chains.add('bgp-out');
  8414. }
  8415. dl.innerHTML = '';
  8416. chains.forEach(c => {
  8417. const opt = document.createElement('option');
  8418. opt.value = c;
  8419. dl.appendChild(opt);
  8420. });
  8421. }
  8422. function openEditBgpPeerModal(id) {
  8423. const p = (state.bgpPeers || []).find(item => item.id === id);
  8424. if (!p) return;
  8425. populateBgpRoutingTables();
  8426. populateFilterChainsDatalist();
  8427. document.getElementById('modal-bgp-peer-id').value = p.id;
  8428. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8429. // General Tab
  8430. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8431. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8432. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8433. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8434. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8435. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8436. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8437. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8438. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8439. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8440. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8441. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8442. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8443. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8444. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8445. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8446. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8447. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8448. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8449. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8450. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8451. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8452. // Extra Tab
  8453. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8454. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8455. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8456. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8457. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8458. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8459. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8460. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8461. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8462. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8463. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8464. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8465. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8466. 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;
  8467. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8468. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8469. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8470. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8471. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8472. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8473. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8474. // Attributes Tab
  8475. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8476. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8477. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8478. 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;
  8479. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8480. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8481. // Filter Tab
  8482. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8483. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8484. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8485. 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 || '';
  8486. 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 || '';
  8487. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8488. 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 || '';
  8489. 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 || '';
  8490. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8491. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8492. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8493. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8494. // Output Networks
  8495. const container = document.getElementById('modal-bgp-output-networks-container');
  8496. if (container) {
  8497. container.innerHTML = '';
  8498. if (p.output_networks && p.output_networks.length > 0) {
  8499. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8500. } else {
  8501. addOutputNetworkRow('');
  8502. }
  8503. }
  8504. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8505. if (removeBtn) removeBtn.classList.remove('hidden');
  8506. switchBgpPeerModalTab('general');
  8507. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8508. }
  8509. function copyCurrentBgpPeer() {
  8510. document.getElementById('modal-bgp-peer-id').value = '';
  8511. const nameEl = document.getElementById('modal-bgp-peer-name');
  8512. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8513. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8514. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8515. if (removeBtn) removeBtn.classList.add('hidden');
  8516. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8517. }
  8518. function removeCurrentBgpPeer() {
  8519. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8520. if (!id) return;
  8521. deleteBgpPeer(id);
  8522. closeBgpPeerModal();
  8523. }
  8524. function closeBgpPeerModal() {
  8525. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8526. }
  8527. function getBgpPeerFormData() {
  8528. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8529. const outputNetworks = [];
  8530. netInputs.forEach(inp => {
  8531. const v = inp.value.trim();
  8532. if (v) outputNetworks.push(v);
  8533. });
  8534. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8535. return {
  8536. id: document.getElementById('modal-bgp-peer-id').value,
  8537. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8538. enabled: enabled,
  8539. disabled: !enabled,
  8540. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8541. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8542. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8543. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8544. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8545. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8546. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8547. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8548. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8549. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8550. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8551. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8552. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8553. password: document.getElementById('modal-bgp-peer-password').value,
  8554. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8555. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8556. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8557. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8558. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8559. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8560. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8561. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8562. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8563. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8564. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8565. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8566. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8567. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8568. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8569. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8570. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8571. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8572. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8573. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8574. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8575. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8576. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8577. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8578. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8579. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8580. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8581. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8582. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8583. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8584. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8585. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8586. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8587. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8588. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8589. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8590. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8591. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8592. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8593. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8594. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8595. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8596. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8597. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8598. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8599. output_networks: outputNetworks
  8600. };
  8601. }
  8602. async function submitBgpPeer(e) {
  8603. if (e) e.preventDefault();
  8604. const payload = getBgpPeerFormData();
  8605. try {
  8606. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8607. method: 'POST',
  8608. headers: { 'Content-Type': 'application/json' },
  8609. body: JSON.stringify(payload)
  8610. });
  8611. if (res.ok) {
  8612. closeBgpPeerModal();
  8613. showToast('Success', 'BGP Connection saved', 'success');
  8614. loadDynamicRouting();
  8615. } else {
  8616. const err = await res.json();
  8617. showToast('Error', err.error || 'Failed to save peer', 'error');
  8618. }
  8619. } catch (err) {
  8620. showToast('Error', err.message, 'error');
  8621. }
  8622. }
  8623. async function applyBgpPeerModal(e) {
  8624. if (e) e.preventDefault();
  8625. const payload = getBgpPeerFormData();
  8626. try {
  8627. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8628. method: 'POST',
  8629. headers: { 'Content-Type': 'application/json' },
  8630. body: JSON.stringify(payload)
  8631. });
  8632. if (res.ok) {
  8633. const data = await res.json();
  8634. if (data.peer && data.peer.id) {
  8635. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8636. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8637. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8638. }
  8639. showToast('Applied', 'BGP Connection applied', 'success');
  8640. loadDynamicRouting();
  8641. } else {
  8642. const err = await res.json();
  8643. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8644. }
  8645. } catch (err) {
  8646. showToast('Error', err.message, 'error');
  8647. }
  8648. }
  8649. async function deleteBgpPeer(id) {
  8650. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8651. try {
  8652. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8653. if (res.ok) {
  8654. showToast('Deleted', 'BGP peer removed', 'success');
  8655. loadDynamicRouting();
  8656. }
  8657. } catch (err) {
  8658. showToast('Error', err.message, 'error');
  8659. }
  8660. }
  8661. async function toggleBgpPeerState(id, disabled) {
  8662. try {
  8663. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8664. method: 'POST',
  8665. headers: { 'Content-Type': 'application/json' },
  8666. body: JSON.stringify({ disabled })
  8667. });
  8668. if (res.ok) {
  8669. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8670. loadDynamicRouting();
  8671. }
  8672. } catch (err) {
  8673. showToast('Error', err.message, 'error');
  8674. }
  8675. }
  8676. function openAddBgpNetworkModal() {
  8677. document.getElementById('bgp-network-form').reset();
  8678. document.getElementById('modal-bgp-net-id').value = '';
  8679. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8680. }
  8681. function closeBgpNetworkModal() {
  8682. document.getElementById('bgp-network-modal').classList.add('hidden');
  8683. }
  8684. async function submitBgpNetwork(e) {
  8685. e.preventDefault();
  8686. const payload = {
  8687. id: document.getElementById('modal-bgp-net-id').value,
  8688. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8689. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8690. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8691. };
  8692. try {
  8693. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8694. method: 'POST',
  8695. headers: { 'Content-Type': 'application/json' },
  8696. body: JSON.stringify(payload)
  8697. });
  8698. if (res.ok) {
  8699. closeBgpNetworkModal();
  8700. showToast('Success', 'BGP network advertisement saved', 'success');
  8701. loadDynamicRouting();
  8702. } else {
  8703. const err = await res.json();
  8704. showToast('Error', err.error || 'Failed to save network', 'error');
  8705. }
  8706. } catch (err) {
  8707. showToast('Error', err.message, 'error');
  8708. }
  8709. }
  8710. async function deleteBgpNetwork(id) {
  8711. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8712. try {
  8713. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8714. if (res.ok) {
  8715. showToast('Deleted', 'Network advertisement removed', 'success');
  8716. loadDynamicRouting();
  8717. }
  8718. } catch (err) {
  8719. showToast('Error', err.message, 'error');
  8720. }
  8721. }
  8722. // =========================================================================
  8723. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8724. // =========================================================================
  8725. // --- 1. OSPF INSTANCE ---
  8726. function openOspfInstanceModal(id = null) {
  8727. const isEdit = !!id;
  8728. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8729. id: '',
  8730. name: 'Default',
  8731. version: 2,
  8732. vrf: 'main',
  8733. router_id: '192.168.131.56',
  8734. routing_table: 'main',
  8735. enabled: true,
  8736. redistribute_connected: false,
  8737. redistribute_static: true,
  8738. redistribute_bgp: false,
  8739. comment: ''
  8740. };
  8741. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8742. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8743. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8744. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8745. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8746. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8747. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8748. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8749. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8750. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8751. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8752. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8753. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8754. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8755. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8756. }
  8757. function openEditOspfInstanceModal(id) {
  8758. openOspfInstanceModal(id);
  8759. }
  8760. function closeOspfInstanceModal() {
  8761. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8762. }
  8763. async function submitOspfInstance(e) {
  8764. if (e) e.preventDefault();
  8765. const payload = {
  8766. id: document.getElementById('modal-ospf-inst-id').value,
  8767. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8768. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8769. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8770. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8771. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8772. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8773. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8774. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8775. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8776. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8777. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8778. };
  8779. try {
  8780. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8781. method: 'POST',
  8782. headers: { 'Content-Type': 'application/json' },
  8783. body: JSON.stringify(payload)
  8784. });
  8785. if (res.ok) {
  8786. closeOspfInstanceModal();
  8787. showToast('Saved', 'OSPF instance updated', 'success');
  8788. loadDynamicRouting();
  8789. } else {
  8790. const err = await res.json();
  8791. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8792. }
  8793. } catch (err) {
  8794. showToast('Error', err.message, 'error');
  8795. }
  8796. }
  8797. function applyOspfInstanceForm() {
  8798. submitOspfInstance(null);
  8799. }
  8800. function copyOspfInstance() {
  8801. document.getElementById('modal-ospf-inst-id').value = '';
  8802. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8803. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8804. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8805. }
  8806. async function deleteCurrentOspfInstance() {
  8807. const id = document.getElementById('modal-ospf-inst-id').value;
  8808. if (!id) return;
  8809. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8810. try {
  8811. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8812. if (res.ok) {
  8813. closeOspfInstanceModal();
  8814. showToast('Removed', 'OSPF instance deleted', 'success');
  8815. loadDynamicRouting();
  8816. }
  8817. } catch (err) {
  8818. showToast('Error', err.message, 'error');
  8819. }
  8820. }
  8821. async function enableSelectedOspfInstance() {
  8822. const id = state.selectedOspfRow?.instances;
  8823. if (!id) return;
  8824. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8825. method: 'POST',
  8826. headers: { 'Content-Type': 'application/json' },
  8827. body: JSON.stringify({ disabled: false })
  8828. });
  8829. loadDynamicRouting();
  8830. }
  8831. async function disableSelectedOspfInstance() {
  8832. const id = state.selectedOspfRow?.instances;
  8833. if (!id) return;
  8834. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8835. method: 'POST',
  8836. headers: { 'Content-Type': 'application/json' },
  8837. body: JSON.stringify({ disabled: true })
  8838. });
  8839. loadDynamicRouting();
  8840. }
  8841. async function removeSelectedOspfInstance() {
  8842. const id = state.selectedOspfRow?.instances;
  8843. if (!id) return;
  8844. if (!confirm('Delete selected OSPF instance?')) return;
  8845. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8846. loadDynamicRouting();
  8847. }
  8848. async function promptCommentOspfInstance() {
  8849. const id = state.selectedOspfRow?.instances;
  8850. if (!id) return;
  8851. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8852. if (!inst) return;
  8853. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8854. if (comment === null) return;
  8855. inst.comment = comment;
  8856. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8857. method: 'POST',
  8858. headers: { 'Content-Type': 'application/json' },
  8859. body: JSON.stringify(inst)
  8860. });
  8861. loadDynamicRouting();
  8862. }
  8863. // --- 2. OSPF AREA ---
  8864. function populateOspfAreaDropdowns() {
  8865. const instSelect = document.getElementById('modal-ospf-area-instance');
  8866. if (instSelect) {
  8867. const cur = instSelect.value;
  8868. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8869. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8870. if (cur) instSelect.value = cur;
  8871. }
  8872. }
  8873. function openOspfAreaModal(id = null) {
  8874. const isEdit = !!id;
  8875. populateOspfAreaDropdowns();
  8876. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8877. id: '',
  8878. name: 'Default',
  8879. instance: 'Default',
  8880. area_id: '0.0.0.0',
  8881. area_type: 'default',
  8882. default_cost: 1,
  8883. no_summaries: false,
  8884. disabled: false,
  8885. comment: ''
  8886. };
  8887. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8888. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8889. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8890. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8891. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8892. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8893. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8894. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8895. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8896. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8897. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8898. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8899. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8900. }
  8901. function openEditOspfAreaModal(id) {
  8902. openOspfAreaModal(id);
  8903. }
  8904. function closeOspfAreaModal() {
  8905. document.getElementById('ospf-area-modal').classList.add('hidden');
  8906. }
  8907. async function submitOspfArea(e) {
  8908. if (e) e.preventDefault();
  8909. const payload = {
  8910. id: document.getElementById('modal-ospf-area-id').value,
  8911. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8912. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8913. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8914. area_type: document.getElementById('modal-ospf-area-type').value,
  8915. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8916. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8917. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8918. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8919. };
  8920. try {
  8921. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8922. method: 'POST',
  8923. headers: { 'Content-Type': 'application/json' },
  8924. body: JSON.stringify(payload)
  8925. });
  8926. if (res.ok) {
  8927. closeOspfAreaModal();
  8928. showToast('Saved', 'OSPF area saved', 'success');
  8929. loadDynamicRouting();
  8930. } else {
  8931. const err = await res.json();
  8932. showToast('Error', err.error || 'Failed to save area', 'error');
  8933. }
  8934. } catch (err) {
  8935. showToast('Error', err.message, 'error');
  8936. }
  8937. }
  8938. function applyOspfAreaForm() {
  8939. submitOspfArea(null);
  8940. }
  8941. function copyOspfArea() {
  8942. document.getElementById('modal-ospf-area-id').value = '';
  8943. document.getElementById('modal-ospf-area-name').value += '-copy';
  8944. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8945. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8946. }
  8947. async function deleteCurrentOspfArea() {
  8948. const id = document.getElementById('modal-ospf-area-id').value;
  8949. if (!id) return;
  8950. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8951. try {
  8952. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8953. if (res.ok) {
  8954. closeOspfAreaModal();
  8955. showToast('Removed', 'OSPF area deleted', 'success');
  8956. loadDynamicRouting();
  8957. }
  8958. } catch (err) {
  8959. showToast('Error', err.message, 'error');
  8960. }
  8961. }
  8962. async function enableSelectedOspfArea() {
  8963. const id = state.selectedOspfRow?.areas;
  8964. if (!id) return;
  8965. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8966. method: 'POST',
  8967. headers: { 'Content-Type': 'application/json' },
  8968. body: JSON.stringify({ disabled: false })
  8969. });
  8970. loadDynamicRouting();
  8971. }
  8972. async function disableSelectedOspfArea() {
  8973. const id = state.selectedOspfRow?.areas;
  8974. if (!id) return;
  8975. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8976. method: 'POST',
  8977. headers: { 'Content-Type': 'application/json' },
  8978. body: JSON.stringify({ disabled: true })
  8979. });
  8980. loadDynamicRouting();
  8981. }
  8982. async function removeSelectedOspfArea() {
  8983. const id = state.selectedOspfRow?.areas;
  8984. if (!id) return;
  8985. if (!confirm('Delete selected OSPF area?')) return;
  8986. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8987. loadDynamicRouting();
  8988. }
  8989. async function promptCommentOspfArea() {
  8990. const id = state.selectedOspfRow?.areas;
  8991. if (!id) return;
  8992. const area = (state.ospfAreas || []).find(a => a.id === id);
  8993. if (!area) return;
  8994. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8995. if (comment === null) return;
  8996. area.comment = comment;
  8997. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8998. method: 'POST',
  8999. headers: { 'Content-Type': 'application/json' },
  9000. body: JSON.stringify(area)
  9001. });
  9002. loadDynamicRouting();
  9003. }
  9004. // --- 3. OSPF AREA RANGE ---
  9005. function populateAreaRangeDropdowns() {
  9006. const select = document.getElementById('modal-ospf-range-area');
  9007. if (select) {
  9008. const cur = select.value;
  9009. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9010. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9011. if (cur) select.value = cur;
  9012. }
  9013. }
  9014. function openOspfAreaRangeModal(id = null) {
  9015. const isEdit = !!id;
  9016. populateAreaRangeDropdowns();
  9017. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9018. id: '',
  9019. area: 'Default',
  9020. prefix: '',
  9021. cost: 1,
  9022. advertise: true,
  9023. disabled: false,
  9024. comment: ''
  9025. };
  9026. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9027. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9028. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9029. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9030. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9031. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9032. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9033. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9034. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9035. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9036. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9037. }
  9038. function openEditOspfAreaRangeModal(id) {
  9039. openOspfAreaRangeModal(id);
  9040. }
  9041. function closeOspfAreaRangeModal() {
  9042. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9043. }
  9044. async function submitOspfAreaRange(e) {
  9045. if (e) e.preventDefault();
  9046. const payload = {
  9047. id: document.getElementById('modal-ospf-range-id').value,
  9048. area: document.getElementById('modal-ospf-range-area').value,
  9049. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9050. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9051. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9052. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9053. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9054. };
  9055. try {
  9056. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9057. method: 'POST',
  9058. headers: { 'Content-Type': 'application/json' },
  9059. body: JSON.stringify(payload)
  9060. });
  9061. if (res.ok) {
  9062. closeOspfAreaRangeModal();
  9063. showToast('Saved', 'Area range saved', 'success');
  9064. loadDynamicRouting();
  9065. } else {
  9066. const err = await res.json();
  9067. showToast('Error', err.error || 'Failed to save area range', 'error');
  9068. }
  9069. } catch (err) {
  9070. showToast('Error', err.message, 'error');
  9071. }
  9072. }
  9073. function applyOspfAreaRangeForm() {
  9074. submitOspfAreaRange(null);
  9075. }
  9076. async function deleteCurrentOspfAreaRange() {
  9077. const id = document.getElementById('modal-ospf-range-id').value;
  9078. if (!id) return;
  9079. if (!confirm('Delete this area range?')) return;
  9080. try {
  9081. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9082. closeOspfAreaRangeModal();
  9083. showToast('Removed', 'Area range removed', 'success');
  9084. loadDynamicRouting();
  9085. } catch (err) {
  9086. showToast('Error', err.message, 'error');
  9087. }
  9088. }
  9089. async function enableSelectedOspfAreaRange() {
  9090. const id = state.selectedOspfRow?.['area-ranges'];
  9091. if (!id) return;
  9092. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9093. if (!r) return;
  9094. r.disabled = false;
  9095. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9096. loadDynamicRouting();
  9097. }
  9098. async function disableSelectedOspfAreaRange() {
  9099. const id = state.selectedOspfRow?.['area-ranges'];
  9100. if (!id) return;
  9101. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9102. if (!r) return;
  9103. r.disabled = true;
  9104. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9105. loadDynamicRouting();
  9106. }
  9107. async function removeSelectedOspfAreaRange() {
  9108. const id = state.selectedOspfRow?.['area-ranges'];
  9109. if (!id) return;
  9110. if (!confirm('Delete selected area range?')) return;
  9111. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9112. loadDynamicRouting();
  9113. }
  9114. async function promptCommentOspfAreaRange() {
  9115. const id = state.selectedOspfRow?.['area-ranges'];
  9116. if (!id) return;
  9117. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9118. if (!r) return;
  9119. const comment = prompt('Enter comment for area range:', r.comment || '');
  9120. if (comment === null) return;
  9121. r.comment = comment;
  9122. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9123. loadDynamicRouting();
  9124. }
  9125. // --- 4. OSPF INTERFACE TEMPLATE ---
  9126. function switchOspfTemplateTab(tab) {
  9127. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9128. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9129. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9130. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9131. if (tab === 'general') {
  9132. if (tabGen) tabGen.classList.remove('hidden');
  9133. if (tabAuth) tabAuth.classList.add('hidden');
  9134. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9135. 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';
  9136. } else {
  9137. if (tabGen) tabGen.classList.add('hidden');
  9138. if (tabAuth) tabAuth.classList.remove('hidden');
  9139. 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';
  9140. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9141. }
  9142. }
  9143. function populateTemplateAreaDropdowns() {
  9144. const select = document.getElementById('modal-ospf-tmpl-area');
  9145. if (select) {
  9146. const cur = select.value;
  9147. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9148. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9149. if (cur) select.value = cur;
  9150. }
  9151. }
  9152. function openOspfTemplateModal(id = null) {
  9153. const isEdit = !!id;
  9154. populateTemplateAreaDropdowns();
  9155. switchOspfTemplateTab('general');
  9156. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9157. id: '',
  9158. interfaces: '',
  9159. area: 'Default',
  9160. networks: '',
  9161. network_type: 'broadcast',
  9162. cost: 1,
  9163. priority: 128,
  9164. passive: false,
  9165. hello_interval: 10,
  9166. dead_interval: 40,
  9167. auth: 'none',
  9168. auth_key: '',
  9169. disabled: false,
  9170. comment: ''
  9171. };
  9172. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9173. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9174. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9175. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9176. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9177. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9178. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9179. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9180. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9181. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9182. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9183. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9184. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9185. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9186. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9187. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9188. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9189. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9190. }
  9191. function openEditOspfTemplateModal(id) {
  9192. openOspfTemplateModal(id);
  9193. }
  9194. function closeOspfTemplateModal() {
  9195. document.getElementById('ospf-template-modal').classList.add('hidden');
  9196. }
  9197. async function submitOspfTemplate(e) {
  9198. if (e) e.preventDefault();
  9199. const payload = {
  9200. id: document.getElementById('modal-ospf-tmpl-id').value,
  9201. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9202. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9203. area: document.getElementById('modal-ospf-tmpl-area').value,
  9204. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9205. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9206. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9207. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9208. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9209. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9210. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9211. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9212. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9213. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9214. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9215. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9216. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9217. };
  9218. try {
  9219. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9220. method: 'POST',
  9221. headers: { 'Content-Type': 'application/json' },
  9222. body: JSON.stringify(payload)
  9223. });
  9224. if (res.ok) {
  9225. closeOspfTemplateModal();
  9226. showToast('Saved', 'Interface template saved', 'success');
  9227. loadDynamicRouting();
  9228. } else {
  9229. const err = await res.json();
  9230. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9231. }
  9232. } catch (err) {
  9233. showToast('Error', err.message, 'error');
  9234. }
  9235. }
  9236. function applyOspfTemplateForm() {
  9237. submitOspfTemplate(null);
  9238. }
  9239. function copyOspfTemplate() {
  9240. document.getElementById('modal-ospf-tmpl-id').value = '';
  9241. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9242. showToast('Copied', 'Duplicated as new template', 'info');
  9243. }
  9244. async function deleteCurrentOspfTemplate() {
  9245. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9246. if (!id) return;
  9247. if (!confirm('Delete this interface template?')) return;
  9248. try {
  9249. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9250. closeOspfTemplateModal();
  9251. showToast('Removed', 'Interface template deleted', 'success');
  9252. loadDynamicRouting();
  9253. } catch (err) {
  9254. showToast('Error', err.message, 'error');
  9255. }
  9256. }
  9257. async function enableSelectedOspfTemplate() {
  9258. const id = state.selectedOspfRow?.templates;
  9259. if (!id) return;
  9260. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9261. method: 'POST',
  9262. headers: { 'Content-Type': 'application/json' },
  9263. body: JSON.stringify({ disabled: false })
  9264. });
  9265. loadDynamicRouting();
  9266. }
  9267. async function disableSelectedOspfTemplate() {
  9268. const id = state.selectedOspfRow?.templates;
  9269. if (!id) return;
  9270. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9271. method: 'POST',
  9272. headers: { 'Content-Type': 'application/json' },
  9273. body: JSON.stringify({ disabled: true })
  9274. });
  9275. loadDynamicRouting();
  9276. }
  9277. async function removeSelectedOspfTemplate() {
  9278. const id = state.selectedOspfRow?.templates;
  9279. if (!id) return;
  9280. if (!confirm('Delete selected interface template?')) return;
  9281. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9282. loadDynamicRouting();
  9283. }
  9284. async function promptCommentOspfTemplate() {
  9285. const id = state.selectedOspfRow?.templates;
  9286. if (!id) return;
  9287. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9288. if (!tmpl) return;
  9289. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9290. if (comment === null) return;
  9291. tmpl.comment = comment;
  9292. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9293. method: 'POST',
  9294. headers: { 'Content-Type': 'application/json' },
  9295. body: JSON.stringify(tmpl)
  9296. });
  9297. loadDynamicRouting();
  9298. }
  9299. // --- 5. OSPF STATIC NEIGHBOR ---
  9300. function populateStaticNbrAreaDropdowns() {
  9301. const select = document.getElementById('modal-ospf-snbr-area');
  9302. if (select) {
  9303. const cur = select.value;
  9304. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9305. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9306. if (cur) select.value = cur;
  9307. }
  9308. }
  9309. function openOspfStaticNbrModal(id = null) {
  9310. const isEdit = !!id;
  9311. populateStaticNbrAreaDropdowns();
  9312. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9313. id: '',
  9314. address: '',
  9315. area: 'Default',
  9316. poll_interval: 120,
  9317. cost: 1,
  9318. disabled: false,
  9319. comment: ''
  9320. };
  9321. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9322. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9323. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9324. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9325. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9326. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9327. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9328. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9329. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9330. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9331. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9332. }
  9333. function openEditOspfStaticNbrModal(id) {
  9334. openOspfStaticNbrModal(id);
  9335. }
  9336. function closeOspfStaticNbrModal() {
  9337. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9338. }
  9339. async function submitOspfStaticNbr(e) {
  9340. if (e) e.preventDefault();
  9341. const payload = {
  9342. id: document.getElementById('modal-ospf-snbr-id').value,
  9343. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9344. area: document.getElementById('modal-ospf-snbr-area').value,
  9345. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9346. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9347. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9348. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9349. };
  9350. try {
  9351. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9352. method: 'POST',
  9353. headers: { 'Content-Type': 'application/json' },
  9354. body: JSON.stringify(payload)
  9355. });
  9356. if (res.ok) {
  9357. closeOspfStaticNbrModal();
  9358. showToast('Saved', 'Static neighbor saved', 'success');
  9359. loadDynamicRouting();
  9360. } else {
  9361. const err = await res.json();
  9362. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9363. }
  9364. } catch (err) {
  9365. showToast('Error', err.message, 'error');
  9366. }
  9367. }
  9368. function applyOspfStaticNbrForm() {
  9369. submitOspfStaticNbr(null);
  9370. }
  9371. async function deleteCurrentOspfStaticNbr() {
  9372. const id = document.getElementById('modal-ospf-snbr-id').value;
  9373. if (!id) return;
  9374. if (!confirm('Delete this static neighbor?')) return;
  9375. try {
  9376. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9377. closeOspfStaticNbrModal();
  9378. showToast('Removed', 'Static neighbor removed', 'success');
  9379. loadDynamicRouting();
  9380. } catch (err) {
  9381. showToast('Error', err.message, 'error');
  9382. }
  9383. }
  9384. async function enableSelectedOspfStaticNbr() {
  9385. const id = state.selectedOspfRow?.['static-nbrs'];
  9386. if (!id) return;
  9387. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9388. if (!n) return;
  9389. n.disabled = false;
  9390. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9391. loadDynamicRouting();
  9392. }
  9393. async function disableSelectedOspfStaticNbr() {
  9394. const id = state.selectedOspfRow?.['static-nbrs'];
  9395. if (!id) return;
  9396. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9397. if (!n) return;
  9398. n.disabled = true;
  9399. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9400. loadDynamicRouting();
  9401. }
  9402. async function removeSelectedOspfStaticNbr() {
  9403. const id = state.selectedOspfRow?.['static-nbrs'];
  9404. if (!id) return;
  9405. if (!confirm('Delete selected static neighbor?')) return;
  9406. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9407. loadDynamicRouting();
  9408. }
  9409. async function promptCommentOspfStaticNbr() {
  9410. const id = state.selectedOspfRow?.['static-nbrs'];
  9411. if (!id) return;
  9412. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9413. if (!n) return;
  9414. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9415. if (comment === null) return;
  9416. n.comment = comment;
  9417. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9418. loadDynamicRouting();
  9419. }
  9420. // Backward-compat aliases
  9421. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9422. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9423. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9424. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9425. function deleteOspfInterface(id) {
  9426. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9427. }
  9428. function toggleOspfInterfaceState(id, disabled) {
  9429. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9430. method: 'POST',
  9431. headers: { 'Content-Type': 'application/json' },
  9432. body: JSON.stringify({ disabled })
  9433. }).then(() => loadDynamicRouting());
  9434. }
  9435. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9436. function deleteOspfArea(id) {
  9437. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9438. }
  9439. // ============================================================================
  9440. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9441. // ============================================================================
  9442. function switchBridgeSubTab(tab) {
  9443. state.bridgeSubTab = tab;
  9444. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9445. tabs.forEach(t => {
  9446. const panel = document.getElementById(`bridge-subtab-${t}`);
  9447. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9448. if (panel) {
  9449. if (t === tab) panel.classList.remove('hidden');
  9450. else panel.classList.add('hidden');
  9451. }
  9452. if (btn) {
  9453. if (t === tab) {
  9454. 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';
  9455. } else {
  9456. 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';
  9457. }
  9458. }
  9459. });
  9460. const addBtn = document.getElementById('bridge-top-action-btn');
  9461. if (addBtn) {
  9462. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9463. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9464. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9465. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9466. }
  9467. if (tab === 'hosts') loadBridgeHosts();
  9468. setTimeout(initTableSorting, 50);
  9469. }
  9470. function openCurrentBridgeModal() {
  9471. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9472. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9473. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9474. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9475. }
  9476. async function loadBridge() {
  9477. try {
  9478. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9479. fetch(`${API_BASE}/bridge/bridges`),
  9480. fetch(`${API_BASE}/bridge/ports`),
  9481. fetch(`${API_BASE}/bridge/vlans`),
  9482. fetch(`${API_BASE}/bridge/summary`),
  9483. fetch(`${API_BASE}/vpn/eoip`),
  9484. fetch(`${API_BASE}/vlans`)
  9485. ]);
  9486. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9487. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9488. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9489. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9490. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9491. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9492. // Badges & Stats
  9493. const bBridges = document.getElementById('bridge-badge-bridges');
  9494. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9495. const bPorts = document.getElementById('bridge-badge-ports');
  9496. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9497. const bVlans = document.getElementById('bridge-badge-vlans');
  9498. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9499. const bHosts = document.getElementById('bridge-badge-hosts');
  9500. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9501. const sBr = document.getElementById('bridge-stat-bridges');
  9502. if (sBr) sBr.innerText = (state.bridges || []).length;
  9503. const sPorts = document.getElementById('bridge-stat-ports');
  9504. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9505. const sHosts = document.getElementById('bridge-stat-hosts');
  9506. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9507. renderBridges();
  9508. renderBridgePorts();
  9509. renderBridgeVLANs();
  9510. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9511. } catch (err) {
  9512. console.error('Failed to load bridge subsystem:', err);
  9513. }
  9514. }
  9515. // ----------------- Bridges -----------------
  9516. function renderBridges() {
  9517. const tbody = document.getElementById('bridge-table-body');
  9518. const empty = document.getElementById('bridge-empty-bridges');
  9519. const countBadge = document.getElementById('bridge-count-badge');
  9520. if (!tbody) return;
  9521. tbody.innerHTML = '';
  9522. const bridges = state.bridges || [];
  9523. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9524. if (bridges.length === 0) {
  9525. empty?.classList.remove('hidden');
  9526. return;
  9527. }
  9528. empty?.classList.add('hidden');
  9529. bridges.forEach((b, idx) => {
  9530. const tr = document.createElement('tr');
  9531. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9532. // Format IP addresses pill list
  9533. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9534. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9535. ipsHtml = b.ip_addresses.map(ip => `
  9536. <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">
  9537. <span>${ip}</span>
  9538. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9539. </span>
  9540. `).join(' ');
  9541. }
  9542. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9543. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9544. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9545. tr.innerHTML = `
  9546. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9547. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9548. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9549. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9550. </td>
  9551. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9552. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9553. <td class="py-2.5 px-3">
  9554. <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>
  9555. </td>
  9556. <td class="py-2.5 px-3 text-center">
  9557. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9558. </td>
  9559. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9560. <td class="py-2.5 px-3">
  9561. <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>
  9562. </td>
  9563. <td class="py-2.5 px-3">
  9564. <div class="flex items-center gap-1.5 flex-wrap">
  9565. ${ipsHtml}
  9566. <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>
  9567. </div>
  9568. </td>
  9569. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9570. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9571. </td>
  9572. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9573. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9574. <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>
  9575. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9576. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9577. </td>
  9578. `;
  9579. tbody.appendChild(tr);
  9580. });
  9581. }
  9582. function openAddBridgeModal() {
  9583. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9584. document.getElementById('bridge-modal-id').value = '';
  9585. document.getElementById('bridge-modal-name').value = 'bridge1';
  9586. document.getElementById('bridge-modal-name').disabled = false;
  9587. document.getElementById('bridge-modal-mtu').value = '1500';
  9588. document.getElementById('bridge-modal-mac').value = '';
  9589. document.getElementById('bridge-modal-stp').value = 'rstp';
  9590. document.getElementById('bridge-modal-priority').value = '32768';
  9591. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9592. document.getElementById('bridge-modal-pvid').value = '1';
  9593. document.getElementById('bridge-modal-fastforward').checked = true;
  9594. document.getElementById('bridge-modal-comment').value = '';
  9595. document.getElementById('bridge-modal-disabled').checked = false;
  9596. toggleBridgeModalVlanFiltering();
  9597. document.getElementById('bridge-modal').classList.remove('hidden');
  9598. }
  9599. function openEditBridgeModal(id) {
  9600. const b = (state.bridges || []).find(x => x.id === id);
  9601. if (!b) return;
  9602. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9603. document.getElementById('bridge-modal-id').value = b.id;
  9604. document.getElementById('bridge-modal-name').value = b.name;
  9605. document.getElementById('bridge-modal-name').disabled = true;
  9606. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9607. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9608. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9609. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9610. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9611. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9612. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9613. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9614. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9615. toggleBridgeModalVlanFiltering();
  9616. document.getElementById('bridge-modal').classList.remove('hidden');
  9617. }
  9618. function closeBridgeModal() {
  9619. document.getElementById('bridge-modal').classList.add('hidden');
  9620. }
  9621. function toggleBridgeModalVlanFiltering() {
  9622. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9623. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9624. if (pvidBox) {
  9625. if (chk) pvidBox.classList.remove('opacity-40');
  9626. else pvidBox.classList.add('opacity-40');
  9627. }
  9628. }
  9629. async function submitSaveBridge(e) {
  9630. e.preventDefault();
  9631. const id = document.getElementById('bridge-modal-id').value;
  9632. const name = document.getElementById('bridge-modal-name').value.trim();
  9633. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9634. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9635. const stp = document.getElementById('bridge-modal-stp').value;
  9636. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9637. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9638. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9639. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9640. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9641. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9642. try {
  9643. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9644. method: 'POST',
  9645. headers: { 'Content-Type': 'application/json' },
  9646. body: JSON.stringify({
  9647. id,
  9648. name,
  9649. mtu,
  9650. mac_address: mac,
  9651. stp,
  9652. priority,
  9653. vlan_filtering: vlanFiltering,
  9654. pvid,
  9655. fast_forward: fastForward,
  9656. comment,
  9657. disabled
  9658. })
  9659. });
  9660. if (res.ok) {
  9661. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9662. closeBridgeModal();
  9663. loadBridge();
  9664. fetchData(false);
  9665. } else {
  9666. const err = await res.json();
  9667. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9668. }
  9669. } catch (err) {
  9670. showToast('Error', err.message, 'error');
  9671. }
  9672. }
  9673. async function toggleBridgeState(id, disabled) {
  9674. try {
  9675. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9676. method: 'POST',
  9677. headers: { 'Content-Type': 'application/json' },
  9678. body: JSON.stringify({ disabled })
  9679. });
  9680. if (res.ok) {
  9681. loadBridge();
  9682. fetchData(false);
  9683. }
  9684. } catch (err) {
  9685. showToast('Error', err.message, 'error');
  9686. }
  9687. }
  9688. async function deleteBridge(id) {
  9689. const b = (state.bridges || []).find(x => x.id === id);
  9690. const name = b ? b.name : id;
  9691. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9692. try {
  9693. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9694. if (res.ok) {
  9695. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9696. loadBridge();
  9697. fetchData(false);
  9698. } else {
  9699. const err = await res.json();
  9700. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9701. }
  9702. } catch (err) {
  9703. showToast('Error', err.message, 'error');
  9704. }
  9705. }
  9706. // ----------------- Bridge IP Assignments -----------------
  9707. function openAddBridgeIPModal(id, name) {
  9708. document.getElementById('bridge-ip-modal-id').value = id;
  9709. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9710. document.getElementById('bridge-ip-modal-cidr').value = '';
  9711. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9712. }
  9713. function closeBridgeIPModal() {
  9714. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9715. }
  9716. async function submitAddBridgeIP(e) {
  9717. e.preventDefault();
  9718. const id = document.getElementById('bridge-ip-modal-id').value;
  9719. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9720. try {
  9721. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9722. method: 'POST',
  9723. headers: { 'Content-Type': 'application/json' },
  9724. body: JSON.stringify({ ip })
  9725. });
  9726. if (res.ok) {
  9727. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9728. closeBridgeIPModal();
  9729. loadBridge();
  9730. fetchData(false);
  9731. } else {
  9732. const err = await res.json();
  9733. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9734. }
  9735. } catch (err) {
  9736. showToast('Error', err.message, 'error');
  9737. }
  9738. }
  9739. async function deleteBridgeIP(id, ip) {
  9740. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9741. try {
  9742. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9743. method: 'DELETE',
  9744. headers: { 'Content-Type': 'application/json' },
  9745. body: JSON.stringify({ ip })
  9746. });
  9747. if (res.ok) {
  9748. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9749. loadBridge();
  9750. fetchData(false);
  9751. }
  9752. } catch (err) {
  9753. showToast('Error', err.message, 'error');
  9754. }
  9755. }
  9756. // ----------------- Bridge Ports -----------------
  9757. function renderBridgePorts() {
  9758. const tbody = document.getElementById('bridge-ports-table-body');
  9759. const empty = document.getElementById('bridge-empty-ports');
  9760. const countBadge = document.getElementById('bridge-ports-count-badge');
  9761. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9762. if (!tbody) return;
  9763. tbody.innerHTML = '';
  9764. // Update filter select
  9765. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9766. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9767. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9768. if (ports.length === 0) {
  9769. empty?.classList.remove('hidden');
  9770. return;
  9771. }
  9772. empty?.classList.add('hidden');
  9773. ports.forEach((p, idx) => {
  9774. const tr = document.createElement('tr');
  9775. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9776. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9777. tr.innerHTML = `
  9778. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9779. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9780. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9781. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9782. </td>
  9783. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9784. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9785. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9786. <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>
  9787. <td class="py-2.5 px-3">
  9788. ${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>'}
  9789. </td>
  9790. <td class="py-2.5 px-3">
  9791. <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>
  9792. </td>
  9793. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9794. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9795. <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>
  9796. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9797. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9798. </td>
  9799. `;
  9800. tbody.appendChild(tr);
  9801. });
  9802. }
  9803. function openAddBridgePortModal() {
  9804. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9805. document.getElementById('bridge-port-modal-id').value = '';
  9806. populateBridgeSelect('bridge-port-modal-bridge');
  9807. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9808. document.getElementById('bridge-port-modal-pvid').value = '1';
  9809. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9810. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9811. document.getElementById('bridge-port-modal-horizon').value = '0';
  9812. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9813. document.getElementById('bridge-port-modal-priority').value = '128';
  9814. document.getElementById('bridge-port-modal-learn').checked = true;
  9815. document.getElementById('bridge-port-modal-comment').value = '';
  9816. document.getElementById('bridge-port-modal-disabled').checked = false;
  9817. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9818. }
  9819. function openEditBridgePortModal(id) {
  9820. const p = (state.bridgePorts || []).find(x => x.id === id);
  9821. if (!p) return;
  9822. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9823. document.getElementById('bridge-port-modal-id').value = p.id;
  9824. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9825. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9826. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9827. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9828. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9829. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9830. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9831. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9832. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9833. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9834. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9835. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9836. }
  9837. function closeBridgePortModal() {
  9838. document.getElementById('bridge-port-modal').classList.add('hidden');
  9839. }
  9840. async function submitSaveBridgePort(e) {
  9841. e.preventDefault();
  9842. const id = document.getElementById('bridge-port-modal-id').value;
  9843. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9844. const iface = document.getElementById('bridge-port-modal-interface').value;
  9845. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9846. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9847. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9848. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9849. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9850. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9851. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9852. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9853. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9854. try {
  9855. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9856. method: 'POST',
  9857. headers: { 'Content-Type': 'application/json' },
  9858. body: JSON.stringify({
  9859. id,
  9860. bridge,
  9861. interface: iface,
  9862. pvid,
  9863. frame_types: frameTypes,
  9864. ingress_filtering: ingressFiltering,
  9865. horizon,
  9866. path_cost: pathCost,
  9867. priority,
  9868. learn,
  9869. comment,
  9870. disabled
  9871. })
  9872. });
  9873. if (res.ok) {
  9874. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9875. closeBridgePortModal();
  9876. loadBridge();
  9877. fetchData(false);
  9878. } else {
  9879. const err = await res.json();
  9880. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9881. }
  9882. } catch (err) {
  9883. showToast('Error', err.message, 'error');
  9884. }
  9885. }
  9886. async function toggleBridgePortState(id, disabled) {
  9887. try {
  9888. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9889. method: 'POST',
  9890. headers: { 'Content-Type': 'application/json' },
  9891. body: JSON.stringify({ disabled })
  9892. });
  9893. if (res.ok) {
  9894. loadBridge();
  9895. fetchData(false);
  9896. }
  9897. } catch (err) {
  9898. showToast('Error', err.message, 'error');
  9899. }
  9900. }
  9901. async function deleteBridgePort(id) {
  9902. const p = (state.bridgePorts || []).find(x => x.id === id);
  9903. const iface = p ? p.interface : id;
  9904. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9905. try {
  9906. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9907. if (res.ok) {
  9908. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9909. loadBridge();
  9910. fetchData(false);
  9911. }
  9912. } catch (err) {
  9913. showToast('Error', err.message, 'error');
  9914. }
  9915. }
  9916. // ----------------- Bridge VLANs -----------------
  9917. function renderBridgeVLANs() {
  9918. const tbody = document.getElementById('bridge-vlans-table-body');
  9919. const empty = document.getElementById('bridge-empty-vlans');
  9920. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9921. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9922. if (!tbody) return;
  9923. tbody.innerHTML = '';
  9924. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9925. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9926. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9927. if (vlans.length === 0) {
  9928. empty?.classList.remove('hidden');
  9929. return;
  9930. }
  9931. empty?.classList.add('hidden');
  9932. vlans.forEach((v, idx) => {
  9933. const tr = document.createElement('tr');
  9934. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9935. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9936. ? 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(' ')
  9937. : '<span class="text-slate-600">none</span>';
  9938. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9939. ? 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(' ')
  9940. : '<span class="text-slate-600">none</span>';
  9941. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9942. tr.innerHTML = `
  9943. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9944. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9945. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9946. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9947. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9948. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9949. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9950. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9951. <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>
  9952. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9953. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9954. </td>
  9955. `;
  9956. tbody.appendChild(tr);
  9957. });
  9958. }
  9959. function openAddBridgeVLANModal() {
  9960. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9961. document.getElementById('bridge-vlan-modal-id').value = '';
  9962. populateBridgeSelect('bridge-vlan-modal-bridge');
  9963. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9964. document.getElementById('bridge-vlan-modal-comment').value = '';
  9965. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9966. updateBridgeVlanPortCheckboxes();
  9967. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9968. }
  9969. function openEditBridgeVLANModal(id) {
  9970. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9971. if (!v) return;
  9972. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9973. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9974. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9975. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9976. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9977. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9978. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9979. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9980. }
  9981. function closeBridgeVlanModal() {
  9982. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9983. }
  9984. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9985. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9986. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9987. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9988. if (!taggedBox || !untaggedBox) return;
  9989. // Ports belonging to the selected bridge
  9990. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9991. if (memberPorts.length === 0) {
  9992. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9993. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9994. return;
  9995. }
  9996. taggedBox.innerHTML = memberPorts.map(p => `
  9997. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9998. <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">
  9999. <span>${p.interface}</span>
  10000. </label>
  10001. `).join('');
  10002. untaggedBox.innerHTML = memberPorts.map(p => `
  10003. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10004. <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">
  10005. <span>${p.interface}</span>
  10006. </label>
  10007. `).join('');
  10008. }
  10009. async function submitSaveBridgeVLAN(e) {
  10010. e.preventDefault();
  10011. const id = document.getElementById('bridge-vlan-modal-id').value;
  10012. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10013. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10014. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10015. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10016. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10017. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10018. try {
  10019. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10020. method: 'POST',
  10021. headers: { 'Content-Type': 'application/json' },
  10022. body: JSON.stringify({
  10023. id,
  10024. bridge,
  10025. vlan_ids: vlanIDs,
  10026. tagged,
  10027. untagged,
  10028. comment,
  10029. disabled
  10030. })
  10031. });
  10032. if (res.ok) {
  10033. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10034. closeBridgeVlanModal();
  10035. loadBridge();
  10036. } else {
  10037. const err = await res.json();
  10038. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10039. }
  10040. } catch (err) {
  10041. showToast('Error', err.message, 'error');
  10042. }
  10043. }
  10044. async function toggleBridgeVLANState(id, disabled) {
  10045. try {
  10046. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10047. method: 'POST',
  10048. headers: { 'Content-Type': 'application/json' },
  10049. body: JSON.stringify({ disabled })
  10050. });
  10051. if (res.ok) loadBridge();
  10052. } catch (err) {
  10053. showToast('Error', err.message, 'error');
  10054. }
  10055. }
  10056. async function deleteBridgeVLAN(id) {
  10057. if (!confirm('Delete this bridge VLAN entry?')) return;
  10058. try {
  10059. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10060. if (res.ok) {
  10061. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10062. loadBridge();
  10063. }
  10064. } catch (err) {
  10065. showToast('Error', err.message, 'error');
  10066. }
  10067. }
  10068. // ----------------- Hosts / MAC Table -----------------
  10069. async function loadBridgeHosts() {
  10070. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10071. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10072. try {
  10073. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10074. const res = await fetch(url);
  10075. if (res.ok) {
  10076. state.bridgeHosts = await res.json();
  10077. renderBridgeHosts();
  10078. }
  10079. } catch (err) {
  10080. console.error('Failed to load bridge hosts:', err);
  10081. }
  10082. }
  10083. function renderBridgeHosts() {
  10084. const tbody = document.getElementById('bridge-hosts-table-body');
  10085. const empty = document.getElementById('bridge-empty-hosts');
  10086. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10087. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10088. if (!tbody) return;
  10089. tbody.innerHTML = '';
  10090. const hosts = (state.bridgeHosts || []).filter(h => {
  10091. if (!search) return true;
  10092. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10093. });
  10094. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10095. if (hosts.length === 0) {
  10096. empty?.classList.remove('hidden');
  10097. return;
  10098. }
  10099. empty?.classList.add('hidden');
  10100. hosts.forEach(h => {
  10101. const tr = document.createElement('tr');
  10102. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10103. let flagBadges = '';
  10104. 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>';
  10105. 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>';
  10106. 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>';
  10107. tr.innerHTML = `
  10108. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10109. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10110. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10111. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10112. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10113. <td class="py-2.5 px-3">${flagBadges}</td>
  10114. `;
  10115. tbody.appendChild(tr);
  10116. });
  10117. }
  10118. async function flushBridgeHosts() {
  10119. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10120. if (!selBridge) {
  10121. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10122. return;
  10123. }
  10124. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10125. try {
  10126. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10127. method: 'POST',
  10128. headers: { 'Content-Type': 'application/json' },
  10129. body: JSON.stringify({ bridge: selBridge })
  10130. });
  10131. if (res.ok) {
  10132. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10133. loadBridgeHosts();
  10134. }
  10135. } catch (err) {
  10136. showToast('Error', err.message, 'error');
  10137. }
  10138. }
  10139. // ----------------- Helpers -----------------
  10140. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10141. const sel = document.getElementById(selectId);
  10142. if (!sel) return;
  10143. const prevVal = currentVal || sel.value;
  10144. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10145. (state.bridges || []).forEach(b => {
  10146. const opt = document.createElement('option');
  10147. opt.value = b.name;
  10148. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10149. if (b.name === prevVal) opt.selected = true;
  10150. sel.appendChild(opt);
  10151. });
  10152. }
  10153. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10154. const sel = document.getElementById(selectId);
  10155. if (!sel) return;
  10156. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10157. // 1. Physical Interfaces
  10158. const grpPhys = document.createElement('optgroup');
  10159. grpPhys.label = 'Physical Interfaces';
  10160. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10161. const opt = document.createElement('option');
  10162. opt.value = i.name;
  10163. opt.innerText = `${i.name} (${i.role || i.type})`;
  10164. if (i.name === currentVal) opt.selected = true;
  10165. grpPhys.appendChild(opt);
  10166. });
  10167. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10168. // 2. VLAN Sub-interfaces
  10169. const grpVlans = document.createElement('optgroup');
  10170. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10171. (state.vlans || []).forEach(v => {
  10172. const opt = document.createElement('option');
  10173. opt.value = v.name;
  10174. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10175. if (v.name === currentVal) opt.selected = true;
  10176. grpVlans.appendChild(opt);
  10177. });
  10178. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10179. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10180. const grpEoip = document.createElement('optgroup');
  10181. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10182. (state.eoipTunnels || []).forEach(t => {
  10183. const opt = document.createElement('option');
  10184. opt.value = t.name;
  10185. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10186. if (t.name === currentVal) opt.selected = true;
  10187. grpEoip.appendChild(opt);
  10188. });
  10189. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10190. }
  10191. // -------------------------------------------------------------
  10192. // RouterOS v7 Routing Filters Management (/routing filter)
  10193. // -------------------------------------------------------------
  10194. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10195. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10196. if (!state.rfSort) state.rfSort = {};
  10197. function switchRoutingFilterTab(tab) {
  10198. state.activeRoutingFilterTab = tab;
  10199. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10200. tabs.forEach(t => {
  10201. const btn = document.getElementById(`tab-rf-${t}`);
  10202. const content = document.getElementById(`tab-content-rf-${t}`);
  10203. if (btn) {
  10204. if (t === tab) {
  10205. 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';
  10206. } else {
  10207. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10208. }
  10209. }
  10210. if (content) {
  10211. if (t === tab) content.classList.remove('hidden');
  10212. else content.classList.add('hidden');
  10213. }
  10214. });
  10215. const chainContainer = document.getElementById('rf-chain-filter-container');
  10216. if (chainContainer) {
  10217. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10218. else chainContainer.classList.add('hidden');
  10219. }
  10220. renderRoutingFilters();
  10221. }
  10222. function selectFilterRow(tab, id) {
  10223. if (state.selectedFilterRow[tab] === id) {
  10224. delete state.selectedFilterRow[tab];
  10225. } else {
  10226. state.selectedFilterRow[tab] = id;
  10227. }
  10228. if (tab === 'rules') renderRoutingFilterRules();
  10229. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10230. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10231. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10232. }
  10233. function openRoutingFilterNewModal() {
  10234. const tab = state.activeRoutingFilterTab || 'rules';
  10235. if (tab === 'rules') openAddRoutingFilterModal();
  10236. else if (tab === 'select-rules') openAddSelectRuleModal();
  10237. else if (tab === 'community-lists') openAddCommunityListModal();
  10238. else if (tab === 'as-lists') openAddASListModal();
  10239. }
  10240. function toggleSelectedRoutingFilter(disabled) {
  10241. const tab = state.activeRoutingFilterTab || 'rules';
  10242. const id = state.selectedFilterRow[tab];
  10243. if (!id) {
  10244. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10245. return;
  10246. }
  10247. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10248. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10249. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10250. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10251. }
  10252. function removeSelectedRoutingFilter() {
  10253. const tab = state.activeRoutingFilterTab || 'rules';
  10254. const id = state.selectedFilterRow[tab];
  10255. if (!id) {
  10256. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10257. return;
  10258. }
  10259. if (tab === 'rules') deleteRoutingFilter(id);
  10260. else if (tab === 'select-rules') deleteSelectRule(id);
  10261. else if (tab === 'community-lists') deleteCommunityList(id);
  10262. else if (tab === 'as-lists') deleteASList(id);
  10263. }
  10264. function searchRoutingFilters(q) {
  10265. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10266. renderRoutingFilters();
  10267. }
  10268. function sortFilterTable(tab, col) {
  10269. if (!state.rfSort) state.rfSort = {};
  10270. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10271. if (state.rfSort[tab].col === col) {
  10272. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10273. } else {
  10274. state.rfSort[tab].col = col;
  10275. state.rfSort[tab].asc = true;
  10276. }
  10277. const asc = state.rfSort[tab].asc;
  10278. let list = [];
  10279. if (tab === 'rules') list = state.routingFilters || [];
  10280. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10281. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10282. else if (tab === 'as-lists') list = state.routingASLists || [];
  10283. list.sort((a, b) => {
  10284. let valA = a[col] ?? '';
  10285. let valB = b[col] ?? '';
  10286. if (col === 'flags') {
  10287. valA = a.disabled ? 'X' : 'A';
  10288. valB = b.disabled ? 'X' : 'A';
  10289. }
  10290. if (typeof valA === 'number' && typeof valB === 'number') {
  10291. return asc ? valA - valB : valB - valA;
  10292. }
  10293. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10294. });
  10295. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10296. allCols.forEach(c => {
  10297. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10298. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10299. });
  10300. if (tab === 'rules') renderRoutingFilterRules();
  10301. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10302. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10303. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10304. }
  10305. function renderRoutingFilters() {
  10306. const navBadge = document.getElementById('badge-filters-count');
  10307. const allRules = state.routingFilters || [];
  10308. if (navBadge) navBadge.innerText = allRules.length;
  10309. // Populate chain filter select options and datalist
  10310. const chainSelect = document.getElementById('routing-filter-chain-select');
  10311. const chainDatalist = document.getElementById('dl-routing-chains');
  10312. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10313. if (chainSelect) {
  10314. const currentVal = state.filterChainSelected || 'all';
  10315. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10316. uniqueChains.map(ch => {
  10317. const count = allRules.filter(r => r.chain === ch).length;
  10318. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10319. }).join('');
  10320. chainSelect.value = currentVal;
  10321. }
  10322. if (chainDatalist) {
  10323. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10324. }
  10325. renderRoutingFilterRules();
  10326. renderRoutingFilterSelectRules();
  10327. renderRoutingFilterCommunityLists();
  10328. renderRoutingFilterASLists();
  10329. }
  10330. function filterRoutingFiltersByChain(chain) {
  10331. state.filterChainSelected = chain;
  10332. renderRoutingFilters();
  10333. }
  10334. // -------------------------------------------------------------
  10335. // TAB 1: RULES (/routing filter rule)
  10336. // -------------------------------------------------------------
  10337. function renderRoutingFilterRules() {
  10338. const tbody = document.getElementById('routing-filter-rules-tbody');
  10339. if (!tbody) return;
  10340. const empty = document.getElementById('rf-rules-empty');
  10341. const statusCount = document.getElementById('rf-status-count');
  10342. let list = (state.routingFilters || []).slice();
  10343. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10344. list = list.filter(r => r.chain === state.filterChainSelected);
  10345. }
  10346. const q = state.rfSearchQuery;
  10347. if (q) {
  10348. list = list.filter(r =>
  10349. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10350. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10351. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10352. (r.comment && r.comment.toLowerCase().includes(q))
  10353. );
  10354. }
  10355. if (!state.rfSort?.['rules']) {
  10356. list.sort((a, b) => {
  10357. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10358. return (a.rule_order || 0) - (b.rule_order || 0);
  10359. });
  10360. }
  10361. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10362. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10363. }
  10364. if (list.length === 0) {
  10365. tbody.innerHTML = '';
  10366. if (empty) empty.classList.remove('hidden');
  10367. return;
  10368. }
  10369. if (empty) empty.classList.add('hidden');
  10370. tbody.innerHTML = list.map(r => {
  10371. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10372. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10373. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10374. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10375. let ruleDisplay = '';
  10376. if (r.rule && r.rule.trim() !== '') {
  10377. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10378. } else {
  10379. let conds = [];
  10380. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10381. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10382. let act = r.action || 'accept';
  10383. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10384. }
  10385. return `
  10386. <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'}">
  10387. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10388. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10389. <td class="py-2 px-3">
  10390. <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>
  10391. </td>
  10392. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10393. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10394. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10395. <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>
  10396. <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>
  10397. <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'}">
  10398. ${r.disabled ? 'Enable' : 'Disable'}
  10399. </button>
  10400. <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">
  10401. Edit
  10402. </button>
  10403. <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">
  10404. ✕
  10405. </button>
  10406. </td>
  10407. </tr>
  10408. `;
  10409. }).join('');
  10410. }
  10411. // -------------------------------------------------------------
  10412. // TAB 2: SELECT RULES (/routing filter select-rule)
  10413. // -------------------------------------------------------------
  10414. function renderRoutingFilterSelectRules() {
  10415. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10416. if (!tbody) return;
  10417. const empty = document.getElementById('rf-select-rules-empty');
  10418. const statusCount = document.getElementById('rf-status-count');
  10419. let list = (state.routingSelectRules || []).slice();
  10420. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10421. list = list.filter(r => r.chain === state.filterChainSelected);
  10422. }
  10423. const q = state.rfSearchQuery;
  10424. if (q) {
  10425. list = list.filter(r =>
  10426. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10427. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10428. (r.comment && r.comment.toLowerCase().includes(q))
  10429. );
  10430. }
  10431. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10432. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10433. }
  10434. if (list.length === 0) {
  10435. tbody.innerHTML = '';
  10436. if (empty) empty.classList.remove('hidden');
  10437. return;
  10438. }
  10439. if (empty) empty.classList.add('hidden');
  10440. tbody.innerHTML = list.map(r => {
  10441. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10442. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10443. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10444. return `
  10445. <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'}">
  10446. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10447. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10448. <td class="py-2 px-3">
  10449. <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>
  10450. </td>
  10451. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10452. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10453. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10454. <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'}">
  10455. ${r.disabled ? 'Enable' : 'Disable'}
  10456. </button>
  10457. <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">
  10458. Edit
  10459. </button>
  10460. <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">
  10461. ✕
  10462. </button>
  10463. </td>
  10464. </tr>
  10465. `;
  10466. }).join('');
  10467. }
  10468. // -------------------------------------------------------------
  10469. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10470. // -------------------------------------------------------------
  10471. function renderRoutingFilterCommunityLists() {
  10472. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10473. if (!tbody) return;
  10474. const empty = document.getElementById('rf-comm-lists-empty');
  10475. const statusCount = document.getElementById('rf-status-count');
  10476. let list = (state.routingCommunityLists || []).slice();
  10477. const q = state.rfSearchQuery;
  10478. if (q) {
  10479. list = list.filter(cl =>
  10480. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10481. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10482. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10483. );
  10484. }
  10485. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10486. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10487. }
  10488. if (list.length === 0) {
  10489. tbody.innerHTML = '';
  10490. if (empty) empty.classList.remove('hidden');
  10491. return;
  10492. }
  10493. if (empty) empty.classList.add('hidden');
  10494. tbody.innerHTML = list.map(cl => {
  10495. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10496. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10497. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10498. const commBadges = (cl.communities || []).map(c =>
  10499. `<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>`
  10500. ).join(' ');
  10501. return `
  10502. <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'}">
  10503. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10504. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10505. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10506. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10507. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10508. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10509. <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'}">
  10510. ${cl.disabled ? 'Enable' : 'Disable'}
  10511. </button>
  10512. <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">
  10513. Edit
  10514. </button>
  10515. <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">
  10516. ✕
  10517. </button>
  10518. </td>
  10519. </tr>
  10520. `;
  10521. }).join('');
  10522. }
  10523. // -------------------------------------------------------------
  10524. // TAB 4: AS LISTS (/routing filter num-list)
  10525. // -------------------------------------------------------------
  10526. function renderRoutingFilterASLists() {
  10527. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10528. if (!tbody) return;
  10529. const empty = document.getElementById('rf-as-lists-empty');
  10530. const statusCount = document.getElementById('rf-status-count');
  10531. let list = (state.routingASLists || []).slice();
  10532. const q = state.rfSearchQuery;
  10533. if (q) {
  10534. list = list.filter(al =>
  10535. (al.name && al.name.toLowerCase().includes(q)) ||
  10536. (al.range && al.range.toLowerCase().includes(q)) ||
  10537. (al.comment && al.comment.toLowerCase().includes(q))
  10538. );
  10539. }
  10540. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10541. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10542. }
  10543. if (list.length === 0) {
  10544. tbody.innerHTML = '';
  10545. if (empty) empty.classList.remove('hidden');
  10546. return;
  10547. }
  10548. if (empty) empty.classList.add('hidden');
  10549. tbody.innerHTML = list.map(al => {
  10550. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10551. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10552. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10553. return `
  10554. <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'}">
  10555. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10556. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10557. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10558. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10559. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10560. <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'}">
  10561. ${al.disabled ? 'Enable' : 'Disable'}
  10562. </button>
  10563. <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">
  10564. Edit
  10565. </button>
  10566. <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">
  10567. ✕
  10568. </button>
  10569. </td>
  10570. </tr>
  10571. `;
  10572. }).join('');
  10573. }
  10574. // -------------------------------------------------------------
  10575. // SNIPPETS & WIZARD HELPERS
  10576. // -------------------------------------------------------------
  10577. function insertRuleSnippet(type) {
  10578. const textarea = document.getElementById('modal-rf-rule');
  10579. if (!textarea) return;
  10580. let snippet = '';
  10581. switch (type) {
  10582. case 'accept-default':
  10583. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10584. break;
  10585. case 'drop-rfc1918':
  10586. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10587. break;
  10588. case 'len-24':
  10589. snippet = 'if (dst-len > 24) { reject; }';
  10590. break;
  10591. case 'local-pref-150':
  10592. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10593. break;
  10594. case 'as-prepend-2':
  10595. snippet = 'set bgp-path-prepend 2; accept;';
  10596. break;
  10597. case 'set-comm':
  10598. snippet = 'set bgp-communities.add 65000:100; accept;';
  10599. break;
  10600. case 'match-comm':
  10601. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10602. break;
  10603. case 'reject-all':
  10604. snippet = 'reject;';
  10605. break;
  10606. }
  10607. if (!snippet) return;
  10608. if (!textarea.value.trim()) {
  10609. textarea.value = snippet;
  10610. } else {
  10611. textarea.value = textarea.value.trim() + '\n' + snippet;
  10612. }
  10613. }
  10614. function generateScriptFromWizard() {
  10615. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10616. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10617. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10618. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10619. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10620. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10621. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10622. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10623. const conds = [];
  10624. if (pfx) {
  10625. if (pfxLen) {
  10626. if (pfxLen.includes('-')) {
  10627. const parts = pfxLen.split('-');
  10628. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10629. } else {
  10630. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10631. }
  10632. } else {
  10633. conds.push(`dst in ${pfx}`);
  10634. }
  10635. }
  10636. if (proto && proto !== 'any') {
  10637. conds.push(`protocol ${proto}`);
  10638. }
  10639. if (asp) {
  10640. conds.push(`bgp-as-path "${asp}"`);
  10641. }
  10642. if (comm) {
  10643. conds.push(`bgp-communities includes ${comm}`);
  10644. }
  10645. const actions = [];
  10646. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10647. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10648. actions.push(`${act};`);
  10649. let code = '';
  10650. if (conds.length > 0) {
  10651. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10652. } else {
  10653. code = actions.join(' ');
  10654. }
  10655. const textarea = document.getElementById('modal-rf-rule');
  10656. if (textarea) textarea.value = code;
  10657. }
  10658. // -------------------------------------------------------------
  10659. // MODAL CRUD: RULES (/routing filter rule)
  10660. // -------------------------------------------------------------
  10661. function openAddRoutingFilterModal(defaultChain = '') {
  10662. const form = document.getElementById('routing-filter-form');
  10663. if (form) form.reset();
  10664. const idEl = document.getElementById('modal-rf-id');
  10665. if (idEl) idEl.value = '';
  10666. const titleEl = document.getElementById('modal-rf-title');
  10667. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10668. const chainEl = document.getElementById('modal-rf-chain');
  10669. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10670. const orderEl = document.getElementById('modal-rf-order');
  10671. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10672. const ruleEl = document.getElementById('modal-rf-rule');
  10673. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10674. const disEl = document.getElementById('modal-rf-disabled');
  10675. if (disEl) disEl.checked = false;
  10676. const modal = document.getElementById('modal-routing-filter');
  10677. if (modal) modal.classList.remove('hidden');
  10678. }
  10679. function openEditRoutingFilterModal(id) {
  10680. const r = (state.routingFilters || []).find(item => item.id === id);
  10681. if (!r) return;
  10682. const idEl = document.getElementById('modal-rf-id');
  10683. if (idEl) idEl.value = r.id;
  10684. const titleEl = document.getElementById('modal-rf-title');
  10685. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10686. const chainEl = document.getElementById('modal-rf-chain');
  10687. if (chainEl) chainEl.value = r.chain || '';
  10688. const orderEl = document.getElementById('modal-rf-order');
  10689. if (orderEl) orderEl.value = r.rule_order || 10;
  10690. const ruleEl = document.getElementById('modal-rf-rule');
  10691. if (ruleEl) {
  10692. if (r.rule) {
  10693. ruleEl.value = r.rule;
  10694. } else {
  10695. let conds = [];
  10696. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10697. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10698. let act = r.action || 'accept';
  10699. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10700. }
  10701. }
  10702. const comEl = document.getElementById('modal-rf-comment');
  10703. if (comEl) comEl.value = r.comment || '';
  10704. const disEl = document.getElementById('modal-rf-disabled');
  10705. if (disEl) disEl.checked = !!r.disabled;
  10706. const modal = document.getElementById('modal-routing-filter');
  10707. if (modal) modal.classList.remove('hidden');
  10708. }
  10709. function closeRoutingFilterModal() {
  10710. const modal = document.getElementById('modal-routing-filter');
  10711. if (modal) modal.classList.add('hidden');
  10712. }
  10713. async function submitRoutingFilter(e) {
  10714. if (e) e.preventDefault();
  10715. const payload = {
  10716. id: document.getElementById('modal-rf-id').value,
  10717. chain: document.getElementById('modal-rf-chain').value.trim(),
  10718. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10719. rule: document.getElementById('modal-rf-rule').value.trim(),
  10720. comment: document.getElementById('modal-rf-comment').value.trim(),
  10721. disabled: document.getElementById('modal-rf-disabled').checked
  10722. };
  10723. try {
  10724. const res = await fetch(`${API_BASE}/routing/filters`, {
  10725. method: 'POST',
  10726. headers: { 'Content-Type': 'application/json' },
  10727. body: JSON.stringify(payload)
  10728. });
  10729. if (res.ok) {
  10730. closeRoutingFilterModal();
  10731. showToast('Success', 'Routing filter rule saved', 'success');
  10732. loadDynamicRouting();
  10733. } else {
  10734. const err = await res.json();
  10735. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10736. }
  10737. } catch (err) {
  10738. showToast('Error', err.message, 'error');
  10739. }
  10740. }
  10741. async function applyRoutingFilterForm() {
  10742. const payload = {
  10743. id: document.getElementById('modal-rf-id').value,
  10744. chain: document.getElementById('modal-rf-chain').value.trim(),
  10745. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10746. rule: document.getElementById('modal-rf-rule').value.trim(),
  10747. comment: document.getElementById('modal-rf-comment').value.trim(),
  10748. disabled: document.getElementById('modal-rf-disabled').checked
  10749. };
  10750. try {
  10751. const res = await fetch(`${API_BASE}/routing/filters`, {
  10752. method: 'POST',
  10753. headers: { 'Content-Type': 'application/json' },
  10754. body: JSON.stringify(payload)
  10755. });
  10756. if (res.ok) {
  10757. const data = await res.json();
  10758. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10759. showToast('Applied', 'Routing filter configuration applied', 'success');
  10760. loadDynamicRouting();
  10761. } else {
  10762. const err = await res.json();
  10763. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10764. }
  10765. } catch (err) {
  10766. showToast('Error', err.message, 'error');
  10767. }
  10768. }
  10769. async function moveRoutingFilterOrder(id, delta) {
  10770. const list = state.routingFilters || [];
  10771. const idx = list.findIndex(r => r.id === id);
  10772. if (idx < 0) return;
  10773. const targetIdx = idx + delta;
  10774. if (targetIdx < 0 || targetIdx >= list.length) return;
  10775. const currentOrder = list[idx].rule_order || 10;
  10776. const targetOrder = list[targetIdx].rule_order || 20;
  10777. list[idx].rule_order = targetOrder;
  10778. list[targetIdx].rule_order = currentOrder;
  10779. try {
  10780. await fetch(`${API_BASE}/routing/filters`, {
  10781. method: 'POST',
  10782. headers: { 'Content-Type': 'application/json' },
  10783. body: JSON.stringify(list[idx])
  10784. });
  10785. await fetch(`${API_BASE}/routing/filters`, {
  10786. method: 'POST',
  10787. headers: { 'Content-Type': 'application/json' },
  10788. body: JSON.stringify(list[targetIdx])
  10789. });
  10790. loadDynamicRouting();
  10791. } catch (e) {
  10792. console.error('Reorder error:', e);
  10793. }
  10794. }
  10795. async function deleteRoutingFilter(id) {
  10796. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10797. try {
  10798. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10799. if (res.ok) {
  10800. showToast('Deleted', 'Routing filter rule removed', 'info');
  10801. loadDynamicRouting();
  10802. } else {
  10803. const err = await res.json();
  10804. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10805. }
  10806. } catch (err) {
  10807. showToast('Error', err.message, 'error');
  10808. }
  10809. }
  10810. async function toggleRoutingFilterState(id, disabled) {
  10811. try {
  10812. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10813. method: 'POST',
  10814. headers: { 'Content-Type': 'application/json' },
  10815. body: JSON.stringify({ disabled })
  10816. });
  10817. if (res.ok) {
  10818. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10819. loadDynamicRouting();
  10820. } else {
  10821. const err = await res.json();
  10822. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10823. }
  10824. } catch (err) {
  10825. showToast('Error', err.message, 'error');
  10826. }
  10827. }
  10828. // -------------------------------------------------------------
  10829. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10830. // -------------------------------------------------------------
  10831. function openAddSelectRuleModal() {
  10832. document.getElementById('modal-rf-sr-id').value = '';
  10833. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10834. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10835. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10836. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10837. document.getElementById('modal-rf-sr-comment').value = '';
  10838. document.getElementById('modal-rf-sr-disabled').checked = false;
  10839. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10840. }
  10841. function openEditSelectRuleModal(id) {
  10842. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10843. if (!r) return;
  10844. document.getElementById('modal-rf-sr-id').value = r.id;
  10845. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10846. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10847. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10848. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10849. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10850. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10851. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10852. }
  10853. function closeSelectRuleModal() {
  10854. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10855. }
  10856. async function submitSelectRule(e) {
  10857. e.preventDefault();
  10858. const payload = {
  10859. id: document.getElementById('modal-rf-sr-id').value,
  10860. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10861. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10862. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10863. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10864. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10865. };
  10866. try {
  10867. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10868. method: 'POST',
  10869. headers: { 'Content-Type': 'application/json' },
  10870. body: JSON.stringify(payload)
  10871. });
  10872. if (res.ok) {
  10873. closeSelectRuleModal();
  10874. showToast('Success', 'Select rule saved', 'success');
  10875. loadDynamicRouting();
  10876. } else {
  10877. const err = await res.json();
  10878. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10879. }
  10880. } catch (err) {
  10881. showToast('Error', err.message, 'error');
  10882. }
  10883. }
  10884. async function deleteSelectRule(id) {
  10885. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10886. try {
  10887. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10888. if (res.ok) {
  10889. showToast('Deleted', 'Select rule removed', 'info');
  10890. loadDynamicRouting();
  10891. } else {
  10892. const err = await res.json();
  10893. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10894. }
  10895. } catch (err) {
  10896. showToast('Error', err.message, 'error');
  10897. }
  10898. }
  10899. async function toggleSelectRuleState(id, disabled) {
  10900. try {
  10901. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10902. method: 'POST',
  10903. headers: { 'Content-Type': 'application/json' },
  10904. body: JSON.stringify({ disabled })
  10905. });
  10906. if (res.ok) {
  10907. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10908. loadDynamicRouting();
  10909. } else {
  10910. const err = await res.json();
  10911. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10912. }
  10913. } catch (err) {
  10914. showToast('Error', err.message, 'error');
  10915. }
  10916. }
  10917. // -------------------------------------------------------------
  10918. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10919. // -------------------------------------------------------------
  10920. function openAddCommunityListModal() {
  10921. document.getElementById('modal-rf-cl-id').value = '';
  10922. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10923. document.getElementById('modal-rf-cl-name').value = '';
  10924. document.getElementById('modal-rf-cl-communities').value = '';
  10925. document.getElementById('modal-rf-cl-regexp').value = '';
  10926. document.getElementById('modal-rf-cl-comment').value = '';
  10927. document.getElementById('modal-rf-cl-disabled').checked = false;
  10928. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10929. }
  10930. function openEditCommunityListModal(id) {
  10931. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10932. if (!cl) return;
  10933. document.getElementById('modal-rf-cl-id').value = cl.id;
  10934. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10935. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10936. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10937. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10938. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10939. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10940. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10941. }
  10942. function closeCommunityListModal() {
  10943. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10944. }
  10945. async function submitCommunityList(e) {
  10946. e.preventDefault();
  10947. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10948. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10949. const payload = {
  10950. id: document.getElementById('modal-rf-cl-id').value,
  10951. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10952. communities: comms,
  10953. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10954. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10955. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10956. };
  10957. try {
  10958. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10959. method: 'POST',
  10960. headers: { 'Content-Type': 'application/json' },
  10961. body: JSON.stringify(payload)
  10962. });
  10963. if (res.ok) {
  10964. closeCommunityListModal();
  10965. showToast('Success', 'Community list saved', 'success');
  10966. loadDynamicRouting();
  10967. } else {
  10968. const err = await res.json();
  10969. showToast('Error', err.error || 'Failed to save community list', 'error');
  10970. }
  10971. } catch (err) {
  10972. showToast('Error', err.message, 'error');
  10973. }
  10974. }
  10975. async function deleteCommunityList(id) {
  10976. if (!confirm('Are you sure you want to delete this community list?')) return;
  10977. try {
  10978. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10979. if (res.ok) {
  10980. showToast('Deleted', 'Community list removed', 'info');
  10981. loadDynamicRouting();
  10982. } else {
  10983. const err = await res.json();
  10984. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10985. }
  10986. } catch (err) {
  10987. showToast('Error', err.message, 'error');
  10988. }
  10989. }
  10990. async function toggleCommunityListState(id, disabled) {
  10991. try {
  10992. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10993. method: 'POST',
  10994. headers: { 'Content-Type': 'application/json' },
  10995. body: JSON.stringify({ disabled })
  10996. });
  10997. if (res.ok) {
  10998. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10999. loadDynamicRouting();
  11000. } else {
  11001. const err = await res.json();
  11002. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11003. }
  11004. } catch (err) {
  11005. showToast('Error', err.message, 'error');
  11006. }
  11007. }
  11008. // -------------------------------------------------------------
  11009. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11010. // -------------------------------------------------------------
  11011. function openAddASListModal() {
  11012. document.getElementById('modal-rf-al-id').value = '';
  11013. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11014. document.getElementById('modal-rf-al-name').value = '';
  11015. document.getElementById('modal-rf-al-range').value = '';
  11016. document.getElementById('modal-rf-al-comment').value = '';
  11017. document.getElementById('modal-rf-al-disabled').checked = false;
  11018. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11019. }
  11020. function openEditASListModal(id) {
  11021. const al = (state.routingASLists || []).find(item => item.id === id);
  11022. if (!al) return;
  11023. document.getElementById('modal-rf-al-id').value = al.id;
  11024. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11025. document.getElementById('modal-rf-al-name').value = al.name || '';
  11026. document.getElementById('modal-rf-al-range').value = al.range || '';
  11027. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11028. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11029. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11030. }
  11031. function closeASListModal() {
  11032. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11033. }
  11034. async function submitASList(e) {
  11035. e.preventDefault();
  11036. const payload = {
  11037. id: document.getElementById('modal-rf-al-id').value,
  11038. name: document.getElementById('modal-rf-al-name').value.trim(),
  11039. range: document.getElementById('modal-rf-al-range').value.trim(),
  11040. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11041. disabled: document.getElementById('modal-rf-al-disabled').checked
  11042. };
  11043. try {
  11044. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11045. method: 'POST',
  11046. headers: { 'Content-Type': 'application/json' },
  11047. body: JSON.stringify(payload)
  11048. });
  11049. if (res.ok) {
  11050. closeASListModal();
  11051. showToast('Success', 'AS number list saved', 'success');
  11052. loadDynamicRouting();
  11053. } else {
  11054. const err = await res.json();
  11055. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11056. }
  11057. } catch (err) {
  11058. showToast('Error', err.message, 'error');
  11059. }
  11060. }
  11061. async function deleteASList(id) {
  11062. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11063. try {
  11064. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11065. if (res.ok) {
  11066. showToast('Deleted', 'AS list removed', 'info');
  11067. loadDynamicRouting();
  11068. } else {
  11069. const err = await res.json();
  11070. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11071. }
  11072. } catch (err) {
  11073. showToast('Error', err.message, 'error');
  11074. }
  11075. }
  11076. async function toggleASListState(id, disabled) {
  11077. try {
  11078. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11079. method: 'POST',
  11080. headers: { 'Content-Type': 'application/json' },
  11081. body: JSON.stringify({ disabled })
  11082. });
  11083. if (res.ok) {
  11084. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11085. loadDynamicRouting();
  11086. } else {
  11087. const err = await res.json();
  11088. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11089. }
  11090. } catch (err) {
  11091. showToast('Error', err.message, 'error');
  11092. }
  11093. }
  11094. // ==========================================
  11095. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11096. // ==========================================
  11097. function loadToolsView() {
  11098. populateToolsInterfaces();
  11099. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11100. }
  11101. function populateToolsInterfaces() {
  11102. const pingSel = document.getElementById('tools-ping-iface');
  11103. const traceSel = document.getElementById('tools-tr-iface');
  11104. let opts = '<option value="">Auto (Default Route)</option>';
  11105. if (Array.isArray(state.interfaces)) {
  11106. state.interfaces.forEach(iface => {
  11107. if (iface.name) {
  11108. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11109. }
  11110. });
  11111. }
  11112. if (pingSel) {
  11113. const cur = pingSel.value;
  11114. pingSel.innerHTML = opts;
  11115. if (cur) pingSel.value = cur;
  11116. }
  11117. if (traceSel) {
  11118. const cur = traceSel.value;
  11119. traceSel.innerHTML = opts;
  11120. if (cur) traceSel.value = cur;
  11121. }
  11122. }
  11123. function switchToolsSubTab(subTab) {
  11124. state.activeToolsSubTab = subTab;
  11125. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11126. tabs.forEach(t => {
  11127. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11128. const view = document.getElementById(`tools-view-${t}`);
  11129. if (btn) {
  11130. if (t === subTab) {
  11131. 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';
  11132. } else {
  11133. 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';
  11134. }
  11135. }
  11136. if (view) {
  11137. if (t === subTab) {
  11138. view.classList.remove('hidden');
  11139. } else {
  11140. view.classList.add('hidden');
  11141. }
  11142. }
  11143. });
  11144. }
  11145. function setPortPreset(port) {
  11146. const input = document.getElementById('tools-port-num');
  11147. if (input) input.value = port;
  11148. }
  11149. let pingAbortController = null;
  11150. let tracerouteAbortController = null;
  11151. function clearPingTable() {
  11152. const tbody = document.getElementById('tools-ping-tbody');
  11153. if (tbody) tbody.innerHTML = '';
  11154. const rawEl = document.getElementById('tools-ping-raw');
  11155. if (rawEl) rawEl.innerText = '';
  11156. const sentEl = document.getElementById('tools-ping-stat-sent');
  11157. if (sentEl) sentEl.innerText = '0';
  11158. const recvEl = document.getElementById('tools-ping-stat-recv');
  11159. if (recvEl) recvEl.innerText = '0';
  11160. const lossEl = document.getElementById('tools-ping-stat-loss');
  11161. if (lossEl) lossEl.innerText = '0%';
  11162. const avgEl = document.getElementById('tools-ping-stat-avg');
  11163. if (avgEl) avgEl.innerText = '0 ms';
  11164. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11165. if (minMaxEl) minMaxEl.innerText = '-';
  11166. const badge = document.getElementById('tools-ping-status-badge');
  11167. if (badge) {
  11168. badge.className = '';
  11169. badge.innerText = '';
  11170. }
  11171. }
  11172. function clearTracerouteTable() {
  11173. const tbody = document.getElementById('tools-tr-tbody');
  11174. if (tbody) tbody.innerHTML = '';
  11175. const rawEl = document.getElementById('tools-tr-raw');
  11176. if (rawEl) rawEl.innerText = '';
  11177. const statHops = document.getElementById('tools-tr-hops-count');
  11178. if (statHops) statHops.innerText = '0 Hops';
  11179. }
  11180. function resetPingButton() {
  11181. const btn = document.getElementById('tools-ping-btn');
  11182. const btnText = document.getElementById('tools-ping-btn-text');
  11183. const spinner = document.getElementById('tools-ping-spinner');
  11184. if (btn) {
  11185. btn.disabled = false;
  11186. 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';
  11187. }
  11188. if (btnText) btnText.innerText = 'Start Ping';
  11189. if (spinner) spinner.classList.add('hidden');
  11190. }
  11191. function setPingRunningButton() {
  11192. const btn = document.getElementById('tools-ping-btn');
  11193. const btnText = document.getElementById('tools-ping-btn-text');
  11194. const spinner = document.getElementById('tools-ping-spinner');
  11195. if (btn) {
  11196. btn.disabled = false;
  11197. 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';
  11198. }
  11199. if (btnText) btnText.innerText = 'Stop Ping';
  11200. if (spinner) spinner.classList.remove('hidden');
  11201. }
  11202. function resetTracerouteButton() {
  11203. const btn = document.getElementById('tools-tr-btn');
  11204. const btnText = document.getElementById('tools-tr-btn-text');
  11205. const spinner = document.getElementById('tools-tr-spinner');
  11206. if (btn) {
  11207. btn.disabled = false;
  11208. 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';
  11209. }
  11210. if (btnText) btnText.innerText = 'Start Traceroute';
  11211. if (spinner) spinner.classList.add('hidden');
  11212. }
  11213. function setTracerouteRunningButton() {
  11214. const btn = document.getElementById('tools-tr-btn');
  11215. const btnText = document.getElementById('tools-tr-btn-text');
  11216. const spinner = document.getElementById('tools-tr-spinner');
  11217. if (btn) {
  11218. btn.disabled = false;
  11219. 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';
  11220. }
  11221. if (btnText) btnText.innerText = 'Stop Traceroute';
  11222. if (spinner) spinner.classList.remove('hidden');
  11223. }
  11224. async function executePing(e) {
  11225. if (e) e.preventDefault();
  11226. // If already running, clicking the button stops the stream!
  11227. if (pingAbortController) {
  11228. pingAbortController.abort();
  11229. pingAbortController = null;
  11230. resetPingButton();
  11231. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11232. return;
  11233. }
  11234. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11235. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11236. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11237. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11238. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11239. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11240. if (!target) {
  11241. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11242. return;
  11243. }
  11244. clearPingTable();
  11245. const resCard = document.getElementById('tools-ping-results');
  11246. if (resCard) resCard.classList.remove('hidden');
  11247. pingAbortController = new AbortController();
  11248. setPingRunningButton();
  11249. try {
  11250. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11251. method: 'POST',
  11252. headers: { 'Content-Type': 'application/json' },
  11253. body: JSON.stringify({
  11254. target,
  11255. count,
  11256. size,
  11257. timeout,
  11258. interface: iface,
  11259. dont_frag: dontFrag
  11260. }),
  11261. signal: pingAbortController.signal
  11262. });
  11263. if (!res.ok) {
  11264. const errText = await res.text();
  11265. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11266. resetPingButton();
  11267. pingAbortController = null;
  11268. return;
  11269. }
  11270. const reader = res.body.getReader();
  11271. const decoder = new TextDecoder('utf-8');
  11272. let buffer = '';
  11273. while (true) {
  11274. const { done, value } = await reader.read();
  11275. if (done) break;
  11276. buffer += decoder.decode(value, { stream: true });
  11277. const blocks = buffer.split('\n\n');
  11278. buffer = blocks.pop() || '';
  11279. for (const block of blocks) {
  11280. const trimmed = block.trim();
  11281. if (!trimmed) continue;
  11282. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11283. try {
  11284. const evt = JSON.parse(line);
  11285. handleLivePingEvent(evt);
  11286. } catch (parseErr) {
  11287. console.warn('Ping SSE parse error:', parseErr, line);
  11288. }
  11289. }
  11290. }
  11291. } catch (err) {
  11292. if (err.name === 'AbortError') {
  11293. // User aborted normally
  11294. } else {
  11295. showToast('Ping Error', err.message, 'error');
  11296. }
  11297. } finally {
  11298. pingAbortController = null;
  11299. resetPingButton();
  11300. }
  11301. }
  11302. function handleLivePingEvent(evt) {
  11303. const sentEl = document.getElementById('tools-ping-stat-sent');
  11304. const recvEl = document.getElementById('tools-ping-stat-recv');
  11305. const lossEl = document.getElementById('tools-ping-stat-loss');
  11306. const avgEl = document.getElementById('tools-ping-stat-avg');
  11307. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11308. const badge = document.getElementById('tools-ping-status-badge');
  11309. const tbody = document.getElementById('tools-ping-tbody');
  11310. const rawEl = document.getElementById('tools-ping-raw');
  11311. if (evt.raw && rawEl) {
  11312. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11313. rawEl.scrollTop = rawEl.scrollHeight;
  11314. }
  11315. if (evt.type === 'reply') {
  11316. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11317. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11318. if (lossEl && evt.packet_loss_pct !== undefined) {
  11319. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11320. lossEl.className = evt.packet_loss_pct === 0
  11321. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11322. : (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');
  11323. }
  11324. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11325. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11326. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11327. }
  11328. if (badge) {
  11329. if (evt.packet_loss_pct === 0) {
  11330. 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';
  11331. badge.innerText = '100% OK';
  11332. } else {
  11333. 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';
  11334. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11335. }
  11336. }
  11337. if (tbody) {
  11338. const tr = document.createElement('tr');
  11339. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11340. tr.innerHTML = `
  11341. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11342. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11343. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11344. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11345. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11346. <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>
  11347. `;
  11348. tbody.appendChild(tr);
  11349. }
  11350. } else if (evt.type === 'timeout') {
  11351. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11352. if (lossEl && evt.packet_loss_pct !== undefined) {
  11353. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11354. 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';
  11355. }
  11356. if (badge) {
  11357. 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';
  11358. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11359. }
  11360. if (tbody) {
  11361. const tr = document.createElement('tr');
  11362. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11363. tr.innerHTML = `
  11364. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11365. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11366. <td class="py-2 px-3 text-slate-600">--</td>
  11367. <td class="py-2 px-3 text-slate-600">--</td>
  11368. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11369. <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>
  11370. `;
  11371. tbody.appendChild(tr);
  11372. }
  11373. } else if (evt.type === 'unreach') {
  11374. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11375. if (lossEl && evt.packet_loss_pct !== undefined) {
  11376. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11377. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11378. }
  11379. if (badge) {
  11380. 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';
  11381. badge.innerText = 'UNREACHABLE';
  11382. }
  11383. if (tbody) {
  11384. const tr = document.createElement('tr');
  11385. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11386. tr.innerHTML = `
  11387. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11388. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11389. <td class="py-2 px-3 text-slate-600">--</td>
  11390. <td class="py-2 px-3 text-slate-600">--</td>
  11391. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11392. <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>
  11393. `;
  11394. tbody.appendChild(tr);
  11395. }
  11396. } else if (evt.type === 'stats') {
  11397. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11398. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11399. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11400. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11401. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11402. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11403. }
  11404. } else if (evt.type === 'done') {
  11405. 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');
  11406. }
  11407. }
  11408. async function executeTraceroute(e) {
  11409. if (e) e.preventDefault();
  11410. if (tracerouteAbortController) {
  11411. tracerouteAbortController.abort();
  11412. tracerouteAbortController = null;
  11413. resetTracerouteButton();
  11414. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11415. return;
  11416. }
  11417. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11418. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11419. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11420. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11421. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11422. if (!target) {
  11423. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11424. return;
  11425. }
  11426. clearTracerouteTable();
  11427. const resCard = document.getElementById('tools-tr-results');
  11428. if (resCard) resCard.classList.remove('hidden');
  11429. tracerouteAbortController = new AbortController();
  11430. setTracerouteRunningButton();
  11431. try {
  11432. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11433. method: 'POST',
  11434. headers: { 'Content-Type': 'application/json' },
  11435. body: JSON.stringify({
  11436. target,
  11437. max_hops: maxHops,
  11438. protocol,
  11439. interface: iface,
  11440. resolve
  11441. }),
  11442. signal: tracerouteAbortController.signal
  11443. });
  11444. if (!res.ok) {
  11445. const errText = await res.text();
  11446. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11447. resetTracerouteButton();
  11448. tracerouteAbortController = null;
  11449. return;
  11450. }
  11451. const reader = res.body.getReader();
  11452. const decoder = new TextDecoder('utf-8');
  11453. let buffer = '';
  11454. while (true) {
  11455. const { done, value } = await reader.read();
  11456. if (done) break;
  11457. buffer += decoder.decode(value, { stream: true });
  11458. const blocks = buffer.split('\n\n');
  11459. buffer = blocks.pop() || '';
  11460. for (const block of blocks) {
  11461. const trimmed = block.trim();
  11462. if (!trimmed) continue;
  11463. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11464. try {
  11465. const evt = JSON.parse(line);
  11466. handleLiveTracerouteEvent(evt);
  11467. } catch (parseErr) {
  11468. console.warn('Traceroute SSE parse error:', parseErr, line);
  11469. }
  11470. }
  11471. }
  11472. } catch (err) {
  11473. if (err.name === 'AbortError') {
  11474. // User aborted normally
  11475. } else {
  11476. showToast('Traceroute Error', err.message, 'error');
  11477. }
  11478. } finally {
  11479. tracerouteAbortController = null;
  11480. resetTracerouteButton();
  11481. }
  11482. }
  11483. function handleLiveTracerouteEvent(evt) {
  11484. const statHops = document.getElementById('tools-tr-hops-count');
  11485. const tbody = document.getElementById('tools-tr-tbody');
  11486. const rawEl = document.getElementById('tools-tr-raw');
  11487. if (evt.raw && rawEl) {
  11488. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11489. rawEl.scrollTop = rawEl.scrollHeight;
  11490. }
  11491. if (evt.hops_count !== undefined && statHops) {
  11492. statHops.innerText = `${evt.hops_count} Hops`;
  11493. }
  11494. if (evt.type === 'hop' && evt.hop && tbody) {
  11495. const h = evt.hop;
  11496. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11497. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11498. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11499. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11500. const tr = document.createElement('tr');
  11501. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11502. tr.innerHTML = `
  11503. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11504. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11505. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11506. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11507. <td class="py-2.5 px-3 text-right">
  11508. ${isTimeout
  11509. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11510. : '<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>'}
  11511. </td>
  11512. `;
  11513. tbody.appendChild(tr);
  11514. } else if (evt.type === 'done') {
  11515. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11516. }
  11517. }
  11518. async function executeMTR(e) {
  11519. if (e) e.preventDefault();
  11520. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11521. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11522. if (!target) {
  11523. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11524. return;
  11525. }
  11526. const btn = document.getElementById('tools-mtr-btn');
  11527. const spinner = document.getElementById('tools-mtr-spinner');
  11528. if (btn) btn.disabled = true;
  11529. if (spinner) spinner.classList.remove('hidden');
  11530. try {
  11531. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11532. method: 'POST',
  11533. headers: { 'Content-Type': 'application/json' },
  11534. body: JSON.stringify({ target, count: cycles })
  11535. });
  11536. const data = await res.json();
  11537. if (!res.ok) {
  11538. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11539. return;
  11540. }
  11541. const resCard = document.getElementById('tools-mtr-results');
  11542. if (resCard) resCard.classList.remove('hidden');
  11543. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11544. const statHops = document.getElementById('tools-mtr-hops-count');
  11545. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11546. const tbody = document.getElementById('tools-mtr-tbody');
  11547. if (tbody) {
  11548. if (hopsCount > 0) {
  11549. tbody.innerHTML = data.hops.map(h => {
  11550. 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');
  11551. return `
  11552. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11553. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11554. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11555. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11556. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11557. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11558. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11559. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11560. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11561. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11562. </tr>
  11563. `;
  11564. }).join('');
  11565. } else {
  11566. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11567. }
  11568. }
  11569. const rawEl = document.getElementById('tools-mtr-raw');
  11570. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11571. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11572. } catch (err) {
  11573. showToast('MTR Error', err.message, 'error');
  11574. } finally {
  11575. if (btn) btn.disabled = false;
  11576. if (spinner) spinner.classList.add('hidden');
  11577. }
  11578. }
  11579. async function executeDNS(e) {
  11580. if (e) e.preventDefault();
  11581. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11582. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11583. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11584. if (!domain) {
  11585. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11586. return;
  11587. }
  11588. const btn = document.getElementById('tools-dns-btn');
  11589. const spinner = document.getElementById('tools-dns-spinner');
  11590. if (btn) btn.disabled = true;
  11591. if (spinner) spinner.classList.remove('hidden');
  11592. try {
  11593. const res = await fetch(`${API_BASE}/tools/dns`, {
  11594. method: 'POST',
  11595. headers: { 'Content-Type': 'application/json' },
  11596. body: JSON.stringify({ domain, type, server })
  11597. });
  11598. const data = await res.json();
  11599. if (!res.ok) {
  11600. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11601. return;
  11602. }
  11603. const resCard = document.getElementById('tools-dns-results');
  11604. if (resCard) resCard.classList.remove('hidden');
  11605. const metaEl = document.getElementById('tools-dns-meta');
  11606. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11607. const tbody = document.getElementById('tools-dns-tbody');
  11608. if (tbody) {
  11609. if (Array.isArray(data.records) && data.records.length > 0) {
  11610. tbody.innerHTML = data.records.map(r => `
  11611. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11612. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11613. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11614. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11615. <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>
  11616. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11617. </tr>
  11618. `).join('');
  11619. } else {
  11620. 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>`;
  11621. }
  11622. }
  11623. const rawEl = document.getElementById('tools-dns-raw');
  11624. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11625. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11626. } catch (err) {
  11627. showToast('DNS Error', err.message, 'error');
  11628. } finally {
  11629. if (btn) btn.disabled = false;
  11630. if (spinner) spinner.classList.add('hidden');
  11631. }
  11632. }
  11633. async function executePortProbe(e) {
  11634. if (e) e.preventDefault();
  11635. const target = document.getElementById('tools-port-target')?.value?.trim();
  11636. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11637. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11638. if (!target || !port) {
  11639. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11640. return;
  11641. }
  11642. const btn = document.getElementById('tools-port-btn');
  11643. const spinner = document.getElementById('tools-port-spinner');
  11644. if (btn) btn.disabled = true;
  11645. if (spinner) spinner.classList.remove('hidden');
  11646. try {
  11647. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11648. method: 'POST',
  11649. headers: { 'Content-Type': 'application/json' },
  11650. body: JSON.stringify({ target, port, timeout })
  11651. });
  11652. const data = await res.json();
  11653. if (!res.ok) {
  11654. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11655. return;
  11656. }
  11657. const resCard = document.getElementById('tools-port-results');
  11658. if (resCard) resCard.classList.remove('hidden');
  11659. const banner = document.getElementById('tools-port-banner');
  11660. const icon = document.getElementById('tools-port-icon');
  11661. const title = document.getElementById('tools-port-title');
  11662. const sub = document.getElementById('tools-port-sub');
  11663. const latency = document.getElementById('tools-port-latency');
  11664. if (data.open) {
  11665. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11666. if (icon) {
  11667. 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';
  11668. icon.innerText = '✓';
  11669. }
  11670. if (title) {
  11671. title.className = 'text-sm font-bold text-emerald-300';
  11672. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11673. }
  11674. if (sub) {
  11675. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11676. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11677. }
  11678. if (latency) {
  11679. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11680. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11681. }
  11682. } else {
  11683. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11684. if (icon) {
  11685. 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';
  11686. icon.innerText = '✕';
  11687. }
  11688. if (title) {
  11689. title.className = 'text-sm font-bold text-rose-300';
  11690. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11691. }
  11692. if (sub) {
  11693. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11694. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11695. }
  11696. if (latency) {
  11697. latency.className = 'text-base font-bold font-mono text-slate-500';
  11698. latency.innerText = '--';
  11699. }
  11700. }
  11701. const rawEl = document.getElementById('tools-port-raw');
  11702. 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'}`);
  11703. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11704. } catch (err) {
  11705. showToast('Probe Error', err.message, 'error');
  11706. } finally {
  11707. if (btn) btn.disabled = false;
  11708. if (spinner) spinner.classList.add('hidden');
  11709. }
  11710. }
  11711. // ==========================================
  11712. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11713. // ==========================================
  11714. async function loadDHCPClients(showToastMsg = false) {
  11715. try {
  11716. const [clientsRes, sumRes] = await Promise.all([
  11717. fetch(`${API_BASE}/dhcp/clients`),
  11718. fetch(`${API_BASE}/dhcp/clients/summary`)
  11719. ]);
  11720. if (clientsRes.ok) {
  11721. state.dhcpClients = await clientsRes.json();
  11722. }
  11723. if (sumRes.ok) {
  11724. state.dhcpSummary = await sumRes.json();
  11725. }
  11726. renderDHCPClients();
  11727. updateDHCPSummaryCards();
  11728. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11729. if (bDhcp && state.dhcpSummary) {
  11730. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11731. }
  11732. if (showToastMsg) {
  11733. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11734. }
  11735. } catch (err) {
  11736. console.error('Failed to load DHCP clients:', err);
  11737. if (showToastMsg) {
  11738. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11739. }
  11740. }
  11741. }
  11742. function updateDHCPSummaryCards() {
  11743. const sum = state.dhcpSummary || {
  11744. total_clients: (state.dhcpClients || []).length,
  11745. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11746. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11747. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11748. };
  11749. const totalEl = document.getElementById('dhcp-stat-total');
  11750. const boundEl = document.getElementById('dhcp-stat-bound');
  11751. const searchEl = document.getElementById('dhcp-stat-searching');
  11752. const disEl = document.getElementById('dhcp-stat-disabled');
  11753. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11754. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11755. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11756. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11757. }
  11758. function renderDHCPClients() {
  11759. const tbody = document.getElementById('dhcp-clients-tbody');
  11760. const emptyState = document.getElementById('dhcp-clients-empty');
  11761. if (!tbody) return;
  11762. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11763. if (clients.length === 0) {
  11764. tbody.innerHTML = '';
  11765. if (emptyState) emptyState.classList.remove('hidden');
  11766. return;
  11767. }
  11768. if (emptyState) emptyState.classList.add('hidden');
  11769. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11770. if (tbody.dataset.sig === sig) return;
  11771. tbody.dataset.sig = sig;
  11772. tbody.innerHTML = clients.map(c => {
  11773. let statusBadge = '';
  11774. if (!c.enabled) {
  11775. 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>';
  11776. } else if (c.status === 'bound') {
  11777. 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>';
  11778. } else if (c.status === 'searching') {
  11779. 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>';
  11780. } else if (c.status === 'stopped') {
  11781. 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>';
  11782. } else {
  11783. 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>`;
  11784. }
  11785. 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>';
  11786. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11787. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11788. 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>';
  11789. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11790. // Option flags
  11791. const flags = [];
  11792. 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>');
  11793. 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>');
  11794. 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>');
  11795. 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>`);
  11796. return `
  11797. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11798. <td class="py-3 px-4">
  11799. <div class="flex items-center gap-2">
  11800. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11801. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11802. </div>
  11803. </td>
  11804. <td class="py-3 px-4">${statusBadge}</td>
  11805. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11806. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11807. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11808. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11809. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11810. <td class="py-3 px-4">
  11811. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11812. </td>
  11813. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11814. ${c.enabled ? `
  11815. <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>
  11816. <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>
  11817. <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>
  11818. ` : `
  11819. <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>
  11820. `}
  11821. <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>
  11822. <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>
  11823. </td>
  11824. </tr>
  11825. `;
  11826. }).join('');
  11827. }
  11828. function openDHCPClientModal(clientId = null) {
  11829. const modal = document.getElementById('modal-dhcp-client');
  11830. if (!modal) return;
  11831. const title = document.getElementById('modal-dhcp-title');
  11832. const idInput = document.getElementById('modal-dhcp-id');
  11833. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11834. const distInput = document.getElementById('modal-dhcp-distance');
  11835. const commentInput = document.getElementById('modal-dhcp-comment');
  11836. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11837. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11838. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11839. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11840. // Populate interfaces
  11841. if (ifaceSelect) {
  11842. let opts = '<option value="">Select interface...</option>';
  11843. const allIfaces = state.interfaces || [];
  11844. const allVlans = state.vlans || [];
  11845. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11846. // Group 1: Physical & Bridge Interfaces
  11847. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11848. allIfaces.forEach(i => {
  11849. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11850. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11851. });
  11852. opts += '</optgroup>';
  11853. // Group 2: VLAN Interfaces
  11854. if (allVlans.length > 0) {
  11855. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11856. allVlans.forEach(v => {
  11857. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11858. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11859. });
  11860. opts += '</optgroup>';
  11861. }
  11862. ifaceSelect.innerHTML = opts;
  11863. }
  11864. if (clientId) {
  11865. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11866. if (client) {
  11867. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11868. if (idInput) idInput.value = client.id;
  11869. if (ifaceSelect) {
  11870. ifaceSelect.value = client.interface;
  11871. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11872. }
  11873. if (distInput) distInput.value = client.default_route_distance || 1;
  11874. if (commentInput) commentInput.value = client.comment || '';
  11875. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11876. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11877. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11878. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11879. }
  11880. } else {
  11881. if (title) title.innerText = 'Add DHCP Client';
  11882. if (idInput) idInput.value = '';
  11883. if (ifaceSelect) {
  11884. ifaceSelect.value = '';
  11885. ifaceSelect.disabled = false;
  11886. }
  11887. if (distInput) distInput.value = 1;
  11888. if (commentInput) commentInput.value = '';
  11889. if (defRouteCheck) defRouteCheck.checked = true;
  11890. if (peerDnsCheck) peerDnsCheck.checked = true;
  11891. if (peerNtpCheck) peerNtpCheck.checked = true;
  11892. if (enabledCheck) enabledCheck.checked = true;
  11893. }
  11894. modal.classList.remove('hidden');
  11895. }
  11896. function openDHCPClientModalForIface(ifaceName) {
  11897. openDHCPClientModal();
  11898. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11899. if (ifaceSelect && ifaceName) {
  11900. ifaceSelect.value = ifaceName;
  11901. }
  11902. }
  11903. function closeDHCPClientModal() {
  11904. const modal = document.getElementById('modal-dhcp-client');
  11905. if (modal) modal.classList.add('hidden');
  11906. }
  11907. async function submitSaveDHCPClient(e) {
  11908. if (e) e.preventDefault();
  11909. const id = document.getElementById('modal-dhcp-id')?.value;
  11910. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11911. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11912. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11913. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11914. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11915. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11916. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11917. if (!id && !iface) {
  11918. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11919. return;
  11920. }
  11921. try {
  11922. let res;
  11923. if (id) {
  11924. // PUT update
  11925. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11926. method: 'PUT',
  11927. headers: { 'Content-Type': 'application/json' },
  11928. body: JSON.stringify({
  11929. enabled,
  11930. add_default_route: defRoute,
  11931. default_route_distance: distance,
  11932. use_peer_dns: peerDns,
  11933. use_peer_ntp: peerNtp,
  11934. comment
  11935. })
  11936. });
  11937. } else {
  11938. // POST create
  11939. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11940. method: 'POST',
  11941. headers: { 'Content-Type': 'application/json' },
  11942. body: JSON.stringify({
  11943. interface: iface,
  11944. enabled,
  11945. add_default_route: defRoute,
  11946. default_route_distance: distance,
  11947. use_peer_dns: peerDns,
  11948. use_peer_ntp: peerNtp,
  11949. comment
  11950. })
  11951. });
  11952. }
  11953. const data = await res.json();
  11954. if (!res.ok) {
  11955. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11956. return;
  11957. }
  11958. closeDHCPClientModal();
  11959. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11960. await loadDHCPClients();
  11961. fetchData(); // refresh interfaces list with new lease/status
  11962. } catch (err) {
  11963. showToast('Error', err.message, 'error');
  11964. }
  11965. }
  11966. async function toggleDHCPClientState(id, enabled) {
  11967. try {
  11968. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11969. method: 'POST',
  11970. headers: { 'Content-Type': 'application/json' },
  11971. body: JSON.stringify({ enabled })
  11972. });
  11973. const data = await res.json();
  11974. if (!res.ok) {
  11975. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11976. return;
  11977. }
  11978. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11979. await loadDHCPClients();
  11980. fetchData();
  11981. } catch (err) {
  11982. showToast('Error', err.message, 'error');
  11983. }
  11984. }
  11985. async function renewDHCPClient(id) {
  11986. try {
  11987. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11988. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11989. method: 'POST'
  11990. });
  11991. const data = await res.json();
  11992. if (!res.ok) {
  11993. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11994. return;
  11995. }
  11996. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11997. setTimeout(() => {
  11998. loadDHCPClients();
  11999. fetchData();
  12000. }, 1500);
  12001. } catch (err) {
  12002. showToast('Error', err.message, 'error');
  12003. }
  12004. }
  12005. async function releaseDHCPClient(id) {
  12006. try {
  12007. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12008. method: 'POST'
  12009. });
  12010. const data = await res.json();
  12011. if (!res.ok) {
  12012. showToast('Error', data.error || 'Failed to release lease', 'error');
  12013. return;
  12014. }
  12015. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12016. await loadDHCPClients();
  12017. fetchData();
  12018. } catch (err) {
  12019. showToast('Error', err.message, 'error');
  12020. }
  12021. }
  12022. async function deleteDHCPClient(id, ifaceName) {
  12023. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12024. return;
  12025. }
  12026. try {
  12027. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12028. method: 'DELETE'
  12029. });
  12030. const data = await res.json();
  12031. if (!res.ok) {
  12032. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12033. return;
  12034. }
  12035. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12036. await loadDHCPClients();
  12037. fetchData();
  12038. } catch (err) {
  12039. showToast('Error', err.message, 'error');
  12040. }
  12041. }
  12042. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12043. async function loadDHCPServer(populate = true) {
  12044. try {
  12045. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12046. fetch(`${API_BASE}/dhcp-server/summary`),
  12047. fetch(`${API_BASE}/dhcp-server/servers`),
  12048. fetch(`${API_BASE}/dhcp-server/networks`),
  12049. fetch(`${API_BASE}/dhcp-server/leases`),
  12050. fetch(`${API_BASE}/dhcp-server/options`)
  12051. ]);
  12052. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12053. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12054. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12055. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12056. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12057. const sum = state.dhcpServerSummary || {};
  12058. const srvs = state.dhcpServers || [];
  12059. const nets = state.dhcpNetworks || [];
  12060. const leases = state.dhcpLeases || [];
  12061. const opts = state.dhcpOptions || [];
  12062. // KPI Cards
  12063. const statActive = document.getElementById('dhcp-server-stat-active');
  12064. if (statActive) {
  12065. const activeCount = srvs.filter(s => s.running).length;
  12066. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12067. }
  12068. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12069. if (statLeases) {
  12070. statLeases.innerText = leases.length;
  12071. }
  12072. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12073. if (statLeasesSub) {
  12074. const dyn = leases.filter(l => l.dynamic).length;
  12075. const st = leases.filter(l => !l.dynamic).length;
  12076. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12077. }
  12078. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12079. if (statNetworks) {
  12080. statNetworks.innerText = nets.length;
  12081. }
  12082. // Subtab Badges
  12083. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12084. if (bSrv) bSrv.innerText = srvs.length;
  12085. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12086. if (bNet) bNet.innerText = nets.length;
  12087. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12088. if (bLease) bLease.innerText = leases.length;
  12089. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12090. if (bOpt) bOpt.innerText = opts.length;
  12091. // Sidebar Badge
  12092. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12093. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12094. renderCurrentDHCPServerTab();
  12095. } catch (err) {
  12096. console.error('Failed to load DHCP Server:', err);
  12097. }
  12098. }
  12099. function switchDHCPServerTab(tab) {
  12100. state.dhcpServerTab = tab;
  12101. const tabs = ['servers', 'networks', 'leases', 'options'];
  12102. tabs.forEach(t => {
  12103. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12104. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12105. if (panel) {
  12106. if (t === tab) panel.classList.remove('hidden');
  12107. else panel.classList.add('hidden');
  12108. }
  12109. if (btn) {
  12110. if (t === tab) {
  12111. 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';
  12112. } else {
  12113. 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';
  12114. }
  12115. }
  12116. });
  12117. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12118. if (addBtn) {
  12119. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12120. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12121. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12122. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12123. }
  12124. renderCurrentDHCPServerTab();
  12125. }
  12126. function handleDHCPServerPrimaryAdd() {
  12127. const tab = state.dhcpServerTab || 'servers';
  12128. if (tab === 'servers') openAddDHCPServerModal();
  12129. else if (tab === 'networks') openAddDHCPNetworkModal();
  12130. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12131. else if (tab === 'options') openAddDHCPOptionModal();
  12132. }
  12133. function renderCurrentDHCPServerTab() {
  12134. const tab = state.dhcpServerTab || 'servers';
  12135. if (tab === 'servers') renderDHCPServers();
  12136. else if (tab === 'networks') renderDHCPNetworks();
  12137. else if (tab === 'leases') renderDHCPLeases();
  12138. else if (tab === 'options') renderDHCPOptions();
  12139. }
  12140. function renderDHCPServers() {
  12141. const tbody = document.getElementById('dhcp-server-tbody');
  12142. const empty = document.getElementById('dhcp-server-empty');
  12143. if (!tbody) return;
  12144. const servers = state.dhcpServers || [];
  12145. if (servers.length === 0) {
  12146. tbody.innerHTML = '';
  12147. empty?.classList.remove('hidden');
  12148. return;
  12149. }
  12150. empty?.classList.add('hidden');
  12151. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12152. if (tbody.dataset.sig === sig) return;
  12153. tbody.dataset.sig = sig;
  12154. tbody.innerHTML = '';
  12155. servers.forEach(s => {
  12156. const tr = document.createElement('tr');
  12157. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12158. tr.innerHTML = `
  12159. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12160. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12161. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12162. <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>
  12163. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12164. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12165. <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>
  12166. <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>
  12167. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12168. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12169. <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>
  12170. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12171. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12172. </td>
  12173. `;
  12174. tbody.appendChild(tr);
  12175. });
  12176. }
  12177. function renderDHCPNetworks() {
  12178. const tbody = document.getElementById('dhcp-networks-tbody');
  12179. const empty = document.getElementById('dhcp-networks-empty');
  12180. if (!tbody) return;
  12181. tbody.innerHTML = '';
  12182. const networks = state.dhcpNetworks || [];
  12183. if (networks.length === 0) {
  12184. empty?.classList.remove('hidden');
  12185. return;
  12186. }
  12187. empty?.classList.add('hidden');
  12188. networks.forEach(n => {
  12189. const tr = document.createElement('tr');
  12190. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12191. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12192. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  12193. tr.innerHTML = `
  12194. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12195. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12196. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12197. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12198. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12199. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  12200. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  12201. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  12202. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12203. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12204. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12205. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12206. </td>
  12207. `;
  12208. tbody.appendChild(tr);
  12209. });
  12210. }
  12211. function renderDHCPLeases() {
  12212. const tbody = document.getElementById('dhcp-leases-tbody');
  12213. const empty = document.getElementById('dhcp-leases-empty');
  12214. if (!tbody) return;
  12215. tbody.innerHTML = '';
  12216. const leases = state.dhcpLeases || [];
  12217. if (leases.length === 0) {
  12218. empty?.classList.remove('hidden');
  12219. return;
  12220. }
  12221. empty?.classList.add('hidden');
  12222. leases.forEach(l => {
  12223. const tr = document.createElement('tr');
  12224. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12225. 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>';
  12226. const statusBadge = l.status === 'bound'
  12227. ? '<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>'
  12228. : l.status === 'static'
  12229. ? '<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>'
  12230. : '<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>';
  12231. const makeStaticBtn = l.dynamic
  12232. ? `<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>`
  12233. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12234. tr.innerHTML = `
  12235. <td class="py-2.5 px-3 text-center">${flag}</td>
  12236. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12237. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12238. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12239. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12240. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12241. <td class="py-2.5 px-3">${statusBadge}</td>
  12242. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12243. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12244. ${makeStaticBtn}
  12245. </td>
  12246. `;
  12247. tbody.appendChild(tr);
  12248. });
  12249. }
  12250. function renderDHCPOptions() {
  12251. const tbody = document.getElementById('dhcp-options-tbody');
  12252. const empty = document.getElementById('dhcp-options-empty');
  12253. if (!tbody) return;
  12254. tbody.innerHTML = '';
  12255. const options = state.dhcpOptions || [];
  12256. if (options.length === 0) {
  12257. empty?.classList.remove('hidden');
  12258. return;
  12259. }
  12260. empty?.classList.add('hidden');
  12261. options.forEach(o => {
  12262. const tr = document.createElement('tr');
  12263. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12264. tr.innerHTML = `
  12265. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12266. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12267. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12268. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12269. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12270. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12271. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12272. </td>
  12273. `;
  12274. tbody.appendChild(tr);
  12275. });
  12276. }
  12277. // ==================== MODALS & ACTIONS: SERVER ====================
  12278. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12279. const sel = document.getElementById(elemId);
  12280. if (!sel) return;
  12281. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12282. const networks = state.dhcpNetworks || [];
  12283. networks.forEach(n => {
  12284. const opt = document.createElement('option');
  12285. opt.value = n.address;
  12286. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12287. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12288. opt.selected = true;
  12289. }
  12290. sel.appendChild(opt);
  12291. });
  12292. }
  12293. function onDHCPServerNetworkChange() {
  12294. const netSel = document.getElementById('dhcp-server-modal-network');
  12295. if (!netSel) return;
  12296. const netVal = netSel.value;
  12297. if (!netVal) return;
  12298. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12299. if (!poolInput) return;
  12300. // Auto-calculate suggested address pool based on subnet CIDR
  12301. const parts = netVal.split('/');
  12302. const ip = parts[0];
  12303. const cidr = parseInt(parts[1] || '24', 10);
  12304. if (cidr === 24) {
  12305. const octets = ip.split('.');
  12306. if (octets.length === 4) {
  12307. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12308. poolInput.value = `${base}.10-${base}.254`;
  12309. }
  12310. }
  12311. }
  12312. function openAddDHCPServerModal() {
  12313. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12314. document.getElementById('dhcp-server-modal-id').value = '';
  12315. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12316. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12317. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12318. document.getElementById('dhcp-server-modal-comment').value = '';
  12319. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12320. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12321. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12322. const networks = state.dhcpNetworks || [];
  12323. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12324. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12325. if (defaultNet) {
  12326. onDHCPServerNetworkChange();
  12327. }
  12328. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12329. }
  12330. function openEditDHCPServerModal(id) {
  12331. const s = (state.dhcpServers || []).find(item => item.id === id);
  12332. if (!s) return;
  12333. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12334. document.getElementById('dhcp-server-modal-id').value = s.id;
  12335. document.getElementById('dhcp-server-modal-name').value = s.name;
  12336. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12337. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12338. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12339. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12340. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12341. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12342. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12343. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12344. }
  12345. function closeDHCPServerModal() {
  12346. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12347. }
  12348. async function submitSaveDHCPServer(e) {
  12349. e.preventDefault();
  12350. const id = document.getElementById('dhcp-server-modal-id').value;
  12351. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12352. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12353. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12354. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12355. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12356. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12357. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12358. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12359. try {
  12360. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12361. method: 'POST',
  12362. headers: { 'Content-Type': 'application/json' },
  12363. body: JSON.stringify({
  12364. id,
  12365. name,
  12366. interface: iface,
  12367. network,
  12368. address_pool: pool,
  12369. lease_time: leaseTime,
  12370. authoritative,
  12371. disabled,
  12372. comment
  12373. })
  12374. });
  12375. if (res.ok) {
  12376. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12377. closeDHCPServerModal();
  12378. loadDHCPServer(false);
  12379. fetchData(false);
  12380. } else {
  12381. const err = await res.text();
  12382. showToast('Error', err, 'error');
  12383. }
  12384. } catch (err) {
  12385. showToast('Error', err.message, 'error');
  12386. }
  12387. }
  12388. async function toggleDHCPServerState(id, disabled) {
  12389. try {
  12390. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12391. method: 'POST',
  12392. headers: { 'Content-Type': 'application/json' },
  12393. body: JSON.stringify({ disabled })
  12394. });
  12395. if (res.ok) {
  12396. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12397. loadDHCPServer(false);
  12398. fetchData(false);
  12399. }
  12400. } catch (err) {
  12401. showToast('Error', err.message, 'error');
  12402. }
  12403. }
  12404. async function deleteDHCPServer(id, name) {
  12405. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12406. try {
  12407. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12408. if (res.ok) {
  12409. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12410. loadDHCPServer(false);
  12411. fetchData(false);
  12412. }
  12413. } catch (err) {
  12414. showToast('Error', err.message, 'error');
  12415. }
  12416. }
  12417. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12418. function openAddDHCPNetworkModal() {
  12419. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12420. document.getElementById('dhcp-network-modal-id').value = '';
  12421. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12422. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12423. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12424. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12425. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  12426. document.getElementById('dhcp-network-modal-tftp').value = '';
  12427. document.getElementById('dhcp-network-modal-bootfile').value = '';
  12428. document.getElementById('dhcp-network-modal-wins').value = '';
  12429. document.getElementById('dhcp-network-modal-netmask').value = '';
  12430. document.getElementById('dhcp-network-modal-comment').value = '';
  12431. renderDHCPNetworkOptionsCheckboxes([]);
  12432. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12433. }
  12434. function openEditDHCPNetworkModal(id) {
  12435. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12436. if (!n) return;
  12437. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12438. document.getElementById('dhcp-network-modal-id').value = n.id;
  12439. document.getElementById('dhcp-network-modal-address').value = n.address;
  12440. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12441. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12442. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12443. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  12444. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  12445. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  12446. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  12447. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12448. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12449. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12450. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12451. }
  12452. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12453. const container = document.getElementById('dhcp-network-modal-options-list');
  12454. if (!container) return;
  12455. container.innerHTML = '';
  12456. const opts = state.dhcpOptions || [];
  12457. if (opts.length === 0) {
  12458. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12459. return;
  12460. }
  12461. opts.forEach(o => {
  12462. const isChecked = selectedIds.includes(o.id);
  12463. const label = document.createElement('label');
  12464. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12465. label.innerHTML = `
  12466. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12467. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12468. `;
  12469. container.appendChild(label);
  12470. });
  12471. }
  12472. function closeDHCPNetworkModal() {
  12473. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12474. }
  12475. async function submitSaveDHCPNetwork(e) {
  12476. e.preventDefault();
  12477. const id = document.getElementById('dhcp-network-modal-id').value;
  12478. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12479. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12480. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12481. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12482. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12483. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12484. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12485. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12486. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12487. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12488. const selectedOpts = [];
  12489. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12490. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12491. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12492. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12493. try {
  12494. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12495. method: 'POST',
  12496. headers: { 'Content-Type': 'application/json' },
  12497. body: JSON.stringify({
  12498. id,
  12499. address,
  12500. gateway,
  12501. netmask,
  12502. dns_servers: dnsServers,
  12503. domain,
  12504. ntp_servers: ntpServers,
  12505. next_server: tftp,
  12506. boot_file_name: bootfile,
  12507. wins_servers: winsServers,
  12508. dhcp_options: selectedOpts,
  12509. comment
  12510. })
  12511. });
  12512. if (res.ok) {
  12513. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12514. closeDHCPNetworkModal();
  12515. loadDHCPServer(false);
  12516. fetchData(false);
  12517. } else {
  12518. const err = await res.text();
  12519. showToast('Error', err, 'error');
  12520. }
  12521. } catch (err) {
  12522. showToast('Error', err.message, 'error');
  12523. }
  12524. }
  12525. async function deleteDHCPNetwork(id, addr) {
  12526. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12527. try {
  12528. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12529. if (res.ok) {
  12530. showToast('Deleted', `Network ${addr} removed`, 'success');
  12531. loadDHCPServer(false);
  12532. fetchData(false);
  12533. }
  12534. } catch (err) {
  12535. showToast('Error', err.message, 'error');
  12536. }
  12537. }
  12538. // ==================== MODALS & ACTIONS: LEASES ====================
  12539. function openAddDHCPStaticLeaseModal() {
  12540. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12541. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12542. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12543. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12544. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12545. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12546. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12547. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12548. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12549. }
  12550. function closeDHCPStaticLeaseModal() {
  12551. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12552. }
  12553. async function submitSaveDHCPStaticLease(e) {
  12554. e.preventDefault();
  12555. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12556. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12557. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12558. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12559. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12560. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12561. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12562. try {
  12563. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12564. method: 'POST',
  12565. headers: { 'Content-Type': 'application/json' },
  12566. body: JSON.stringify({
  12567. id,
  12568. mac_address: mac,
  12569. address: ip,
  12570. hostname,
  12571. server,
  12572. comment,
  12573. disabled
  12574. })
  12575. });
  12576. if (res.ok) {
  12577. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12578. closeDHCPStaticLeaseModal();
  12579. loadDHCPServer(false);
  12580. fetchData(false);
  12581. } else {
  12582. const err = await res.text();
  12583. showToast('Error', err, 'error');
  12584. }
  12585. } catch (err) {
  12586. showToast('Error', err.message, 'error');
  12587. }
  12588. }
  12589. async function deleteDHCPStaticLease(id) {
  12590. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12591. try {
  12592. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12593. if (res.ok) {
  12594. showToast('Deleted', 'Static lease removed', 'success');
  12595. loadDHCPServer(false);
  12596. fetchData(false);
  12597. }
  12598. } catch (err) {
  12599. showToast('Error', err.message, 'error');
  12600. }
  12601. }
  12602. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12603. try {
  12604. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12605. method: 'POST',
  12606. headers: { 'Content-Type': 'application/json' },
  12607. body: JSON.stringify({
  12608. mac_address: mac,
  12609. address: ip,
  12610. hostname,
  12611. comment: comment || 'Converted to static'
  12612. })
  12613. });
  12614. if (res.ok) {
  12615. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12616. loadDHCPServer(false);
  12617. fetchData(false);
  12618. } else {
  12619. const err = await res.text();
  12620. showToast('Error', err, 'error');
  12621. }
  12622. } catch (err) {
  12623. showToast('Error', err.message, 'error');
  12624. }
  12625. }
  12626. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12627. function openAddDHCPOptionModal() {
  12628. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12629. document.getElementById('dhcp-option-modal-id').value = '';
  12630. document.getElementById('dhcp-option-modal-name').value = '';
  12631. document.getElementById('dhcp-option-modal-code').value = '';
  12632. document.getElementById('dhcp-option-modal-value').value = '';
  12633. document.getElementById('dhcp-option-modal-comment').value = '';
  12634. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12635. }
  12636. function openEditDHCPOptionModal(id) {
  12637. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12638. if (!o) return;
  12639. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12640. document.getElementById('dhcp-option-modal-id').value = o.id;
  12641. document.getElementById('dhcp-option-modal-name').value = o.name;
  12642. document.getElementById('dhcp-option-modal-code').value = o.code;
  12643. document.getElementById('dhcp-option-modal-value').value = o.value;
  12644. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12645. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12646. }
  12647. function closeDHCPOptionModal() {
  12648. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12649. }
  12650. async function submitSaveDHCPOption(e) {
  12651. e.preventDefault();
  12652. const id = document.getElementById('dhcp-option-modal-id').value;
  12653. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12654. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12655. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12656. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12657. try {
  12658. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12659. method: 'POST',
  12660. headers: { 'Content-Type': 'application/json' },
  12661. body: JSON.stringify({ id, name, code, value, comment })
  12662. });
  12663. if (res.ok) {
  12664. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12665. closeDHCPOptionModal();
  12666. loadDHCPServer(false);
  12667. fetchData(false);
  12668. } else {
  12669. const err = await res.text();
  12670. showToast('Error', err, 'error');
  12671. }
  12672. } catch (err) {
  12673. showToast('Error', err.message, 'error');
  12674. }
  12675. }
  12676. async function deleteDHCPOption(id, name) {
  12677. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12678. try {
  12679. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12680. if (res.ok) {
  12681. showToast('Deleted', `Option ${name} removed`, 'success');
  12682. loadDHCPServer(false);
  12683. fetchData(false);
  12684. }
  12685. } catch (err) {
  12686. showToast('Error', err.message, 'error');
  12687. }
  12688. }
  12689. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12690. function openDHCPServerSetupModal() {
  12691. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12692. onDHCPWizardIfaceChange();
  12693. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12694. }
  12695. function closeDHCPServerSetupModal() {
  12696. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12697. }
  12698. function onDHCPWizardIfaceChange() {
  12699. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12700. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12701. let ip = '192.168.88.1';
  12702. let prefix = '24';
  12703. if (iface && iface.ip_address) {
  12704. const parts = iface.ip_address.split('/');
  12705. ip = parts[0];
  12706. if (parts.length > 1) prefix = parts[1];
  12707. }
  12708. // Calculate subnet base (e.g. 192.168.88.0/24)
  12709. const ipParts = ip.split('.');
  12710. if (ipParts.length === 4) {
  12711. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12712. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12713. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12714. document.getElementById('dhcp-wizard-gateway').value = ip;
  12715. document.getElementById('dhcp-wizard-pool').value = pool;
  12716. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12717. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12718. }
  12719. }
  12720. async function submitDHCPServerSetupWizard(e) {
  12721. e.preventDefault();
  12722. const iface = document.getElementById('dhcp-wizard-iface').value;
  12723. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12724. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12725. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12726. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12727. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12728. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12729. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12730. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12731. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12732. try {
  12733. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12734. method: 'POST',
  12735. headers: { 'Content-Type': 'application/json' },
  12736. body: JSON.stringify({
  12737. interface: iface,
  12738. address_space: space,
  12739. gateway: gw,
  12740. address_pool: pool,
  12741. dns_servers: dnsServers,
  12742. lease_time: leaseTime,
  12743. ntp_servers: ntpServers,
  12744. next_server: tftp
  12745. })
  12746. });
  12747. if (res.ok) {
  12748. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12749. closeDHCPServerSetupModal();
  12750. loadDHCPServer(false);
  12751. fetchData(false);
  12752. } else {
  12753. const err = await res.text();
  12754. showToast('Error', err, 'error');
  12755. }
  12756. } catch (err) {
  12757. showToast('Error', err.message, 'error');
  12758. }
  12759. }
  12760. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12761. const sel = document.getElementById(elemId);
  12762. if (!sel) return;
  12763. sel.innerHTML = '<option value="">Select interface...</option>';
  12764. const ifaces = state.interfaces || [];
  12765. ifaces.forEach(i => {
  12766. if (i.name === 'lo') return;
  12767. const opt = document.createElement('option');
  12768. opt.value = i.name;
  12769. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12770. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12771. if (i.name === selectedVal) opt.selected = true;
  12772. sel.appendChild(opt);
  12773. });
  12774. }
  12775. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12776. function initTableSorting() {
  12777. document.querySelectorAll('table').forEach(setupSortableTable);
  12778. }
  12779. function setupSortableTable(table) {
  12780. const thead = table.querySelector('thead');
  12781. const tbody = table.querySelector('tbody');
  12782. if (!thead || !tbody) return;
  12783. const headerRows = thead.querySelectorAll('tr');
  12784. if (headerRows.length === 0) return;
  12785. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12786. ths.forEach((th, colIdx) => {
  12787. if (th._sortBound) return;
  12788. th._sortBound = true;
  12789. const rawText = th.innerText.trim().toLowerCase();
  12790. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12791. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12792. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12793. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12794. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12795. return;
  12796. }
  12797. th.classList.add('table-sortable', 'group');
  12798. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12799. let icon = th.querySelector('.table-sort-icon');
  12800. if (!icon) {
  12801. icon = document.createElement('span');
  12802. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12803. icon.innerHTML = '⇅';
  12804. th.appendChild(icon);
  12805. }
  12806. th.addEventListener('click', (e) => {
  12807. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12808. handleHeaderClick(table, th, colIdx);
  12809. });
  12810. });
  12811. if (!tbody._sortObserved) {
  12812. tbody._sortObserved = true;
  12813. let sortDebounceTimer = null;
  12814. const observer = new MutationObserver((mutations) => {
  12815. if (tbody._isSorting) return;
  12816. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12817. if (!hasChildChanges) return;
  12818. clearTimeout(sortDebounceTimer);
  12819. sortDebounceTimer = setTimeout(() => {
  12820. if (tbody._isSorting) return;
  12821. if (table._activeSort && table._activeSort.dir !== 'none') {
  12822. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12823. } else {
  12824. tagOriginalRowOrder(tbody);
  12825. }
  12826. }, 10);
  12827. });
  12828. observer.observe(tbody, { childList: true });
  12829. }
  12830. tagOriginalRowOrder(tbody);
  12831. }
  12832. function tagOriginalRowOrder(tbody) {
  12833. let idx = 0;
  12834. Array.from(tbody.children).forEach(tr => {
  12835. if (!tr.querySelector('td[colspan]')) {
  12836. if (!tr.hasAttribute('data-orig-idx')) {
  12837. tr.setAttribute('data-orig-idx', idx++);
  12838. }
  12839. }
  12840. });
  12841. }
  12842. function handleHeaderClick(table, th, colIdx) {
  12843. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12844. let newDir = 'asc';
  12845. if (currentSort.colIdx === colIdx) {
  12846. if (currentSort.dir === 'asc') newDir = 'desc';
  12847. else if (currentSort.dir === 'desc') newDir = 'none';
  12848. else newDir = 'asc';
  12849. } else {
  12850. newDir = 'asc';
  12851. }
  12852. table._activeSort = { colIdx, dir: newDir };
  12853. updateHeaderIcons(table, colIdx, newDir);
  12854. applyTableSort(table, colIdx, newDir, true);
  12855. }
  12856. function updateHeaderIcons(table, activeColIdx, dir) {
  12857. const thead = table.querySelector('thead');
  12858. if (!thead) return;
  12859. const ths = thead.querySelectorAll('th');
  12860. ths.forEach((th, idx) => {
  12861. const icon = th.querySelector('.table-sort-icon');
  12862. if (!icon) return;
  12863. if (idx === activeColIdx && dir !== 'none') {
  12864. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12865. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12866. th.classList.add('table-sorted-active');
  12867. } else {
  12868. icon.innerHTML = '⇅';
  12869. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12870. th.classList.remove('table-sorted-active');
  12871. }
  12872. });
  12873. }
  12874. function applyTableSort(table, colIdx, dir, userInitiated) {
  12875. const tbody = table.querySelector('tbody');
  12876. if (!tbody || tbody.children.length <= 1) return;
  12877. tbody._isSorting = true;
  12878. tagOriginalRowOrder(tbody);
  12879. // Group parent rows and any attached drawer/sub-rows
  12880. const groups = [];
  12881. let currentGroup = null;
  12882. Array.from(tbody.children).forEach(tr => {
  12883. if (tr.querySelector('td[colspan]')) {
  12884. if (currentGroup) {
  12885. currentGroup.subRows.push(tr);
  12886. } else {
  12887. groups.push({ mainRow: tr, subRows: [] });
  12888. }
  12889. } else {
  12890. currentGroup = { mainRow: tr, subRows: [] };
  12891. groups.push(currentGroup);
  12892. }
  12893. });
  12894. if (dir === 'none') {
  12895. groups.sort((a, b) => {
  12896. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12897. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12898. return idxA - idxB;
  12899. });
  12900. } else {
  12901. groups.sort((a, b) => {
  12902. const cellA = a.mainRow.children[colIdx];
  12903. const cellB = b.mainRow.children[colIdx];
  12904. const res = compareTableCells(cellA, cellB);
  12905. return dir === 'asc' ? res : -res;
  12906. });
  12907. }
  12908. // Re-append rows in sorted order
  12909. groups.forEach(g => {
  12910. tbody.appendChild(g.mainRow);
  12911. g.subRows.forEach(sub => tbody.appendChild(sub));
  12912. });
  12913. tbody._isSorting = false;
  12914. }
  12915. function getCellRawText(cell) {
  12916. if (!cell) return '';
  12917. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12918. const input = cell.querySelector('input, select');
  12919. if (input) {
  12920. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12921. return input.value;
  12922. }
  12923. return cell.innerText.trim();
  12924. }
  12925. function parseTrafficToNumber(str) {
  12926. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12927. if (!m) return null;
  12928. const num = parseFloat(m[1].replace(/,/g, ''));
  12929. if (isNaN(num)) return null;
  12930. const unit = m[2].toUpperCase();
  12931. let mult = 1;
  12932. if (unit.startsWith('K')) mult = 1024;
  12933. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12934. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12935. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12936. return num * mult;
  12937. }
  12938. function parseIpToNumber(str) {
  12939. const clean = str.replace(/^[!~]/, '').trim();
  12940. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12941. if (!m) return null;
  12942. const o1 = parseInt(m[1], 10);
  12943. const o2 = parseInt(m[2], 10);
  12944. const o3 = parseInt(m[3], 10);
  12945. const o4 = parseInt(m[4], 10);
  12946. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12947. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12948. }
  12949. function parseCompoundPackets(str) {
  12950. const m = str.match(/^([\d,]+)p/);
  12951. if (!m) return null;
  12952. return parseInt(m[1].replace(/,/g, ''), 10);
  12953. }
  12954. function compareTableCells(cellA, cellB) {
  12955. const a = getCellRawText(cellA);
  12956. const b = getCellRawText(cellB);
  12957. if (a === '' && b !== '') return 1;
  12958. if (b === '' && a !== '') return -1;
  12959. if (a === b) return 0;
  12960. // 1. IP Addresses / CIDR
  12961. const ipA = parseIpToNumber(a);
  12962. const ipB = parseIpToNumber(b);
  12963. if (ipA !== null && ipB !== null) return ipA - ipB;
  12964. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12965. const pktA = parseCompoundPackets(a);
  12966. const pktB = parseCompoundPackets(b);
  12967. if (pktA !== null && pktB !== null) return pktA - pktB;
  12968. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12969. const trafA = parseTrafficToNumber(a);
  12970. const trafB = parseTrafficToNumber(b);
  12971. if (trafA !== null && trafB !== null) return trafA - trafB;
  12972. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12973. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12974. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12975. const numA = Number(cleanNumA);
  12976. const numB = Number(cleanNumB);
  12977. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12978. return numA - numB;
  12979. }
  12980. // 5. Natural case-insensitive string compare
  12981. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12982. }
  12983. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12984. async function loadVRRP(showToastNotification = false) {
  12985. try {
  12986. const [instRes, sumRes] = await Promise.all([
  12987. fetch(`${API_BASE}/vrrp/instances`),
  12988. fetch(`${API_BASE}/vrrp/summary`)
  12989. ]);
  12990. if (instRes.ok) {
  12991. state.vrrpInstances = await instRes.json();
  12992. renderVRRP();
  12993. }
  12994. if (sumRes.ok) {
  12995. state.vrrpSummary = await sumRes.json();
  12996. renderVRRPSummary();
  12997. }
  12998. if (showToastNotification) {
  12999. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13000. }
  13001. } catch (err) {
  13002. console.error('Failed to load VRRP:', err);
  13003. }
  13004. }
  13005. function renderVRRPSummary() {
  13006. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13007. const elTotal = document.getElementById('vrrp-stat-total');
  13008. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13009. const elMaster = document.getElementById('vrrp-stat-master');
  13010. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13011. const elBackup = document.getElementById('vrrp-stat-backup');
  13012. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13013. const bCount = document.getElementById('badge-vrrp-count');
  13014. if (bCount) bCount.innerText = s.total_instances || 0;
  13015. const dot = document.getElementById('badge-vrrp-dot');
  13016. if (dot) {
  13017. if (s.master_instances > 0) {
  13018. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13019. } else if (s.backup_instances > 0) {
  13020. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13021. } else {
  13022. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13023. }
  13024. }
  13025. }
  13026. function renderVRRP() {
  13027. const tbody = document.getElementById('vrrp-table-tbody');
  13028. const empty = document.getElementById('vrrp-table-empty');
  13029. if (!tbody) return;
  13030. tbody.innerHTML = '';
  13031. const instances = state.vrrpInstances || [];
  13032. if (instances.length === 0) {
  13033. empty?.classList.remove('hidden');
  13034. return;
  13035. }
  13036. empty?.classList.add('hidden');
  13037. instances.forEach(inst => {
  13038. const tr = document.createElement('tr');
  13039. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13040. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13041. 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>`;
  13042. if (inst.disabled) {
  13043. 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>`;
  13044. } else if (inst.state === 'MASTER') {
  13045. 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>`;
  13046. } else if (inst.state === 'BACKUP') {
  13047. 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>`;
  13048. } else if (inst.state === 'FAULT') {
  13049. 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>`;
  13050. }
  13051. // Render State Badge
  13052. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13053. if (!inst.disabled) {
  13054. if (inst.state === 'MASTER') {
  13055. 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>`;
  13056. } else if (inst.state === 'BACKUP') {
  13057. 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>`;
  13058. } else if (inst.state === 'FAULT') {
  13059. 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>`;
  13060. }
  13061. }
  13062. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13063. tr.innerHTML = `
  13064. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13065. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13066. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13067. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13068. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13069. <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>
  13070. <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>
  13071. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13072. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13073. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13074. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13075. <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>
  13076. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13077. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13078. </td>
  13079. `;
  13080. tbody.appendChild(tr);
  13081. });
  13082. }
  13083. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13084. const sel = document.getElementById(elemId);
  13085. if (!sel) return;
  13086. sel.innerHTML = '<option value="">Select interface...</option>';
  13087. const ifaces = state.interfaces || [];
  13088. ifaces.forEach(i => {
  13089. const opt = document.createElement('option');
  13090. opt.value = i.name;
  13091. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13092. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13093. sel.appendChild(opt);
  13094. });
  13095. }
  13096. function openAddVRRPModal() {
  13097. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13098. document.getElementById('modal-vrrp-id').value = '';
  13099. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13100. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13101. document.getElementById('modal-vrrp-priority').value = 100;
  13102. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13103. document.getElementById('modal-vrrp-version').value = '3';
  13104. document.getElementById('modal-vrrp-interval').value = 1;
  13105. document.getElementById('modal-vrrp-authtype').value = 'none';
  13106. document.getElementById('modal-vrrp-authpass').value = '';
  13107. document.getElementById('modal-vrrp-comment').value = '';
  13108. document.getElementById('modal-vrrp-preempt').checked = true;
  13109. document.getElementById('modal-vrrp-disabled').checked = false;
  13110. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13111. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13112. }
  13113. function openEditVRRPModal(id) {
  13114. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13115. if (!inst) return;
  13116. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13117. document.getElementById('modal-vrrp-id').value = inst.id;
  13118. document.getElementById('modal-vrrp-name').value = inst.name;
  13119. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13120. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13121. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13122. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13123. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13124. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13125. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13126. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13127. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13128. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13129. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13130. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13131. }
  13132. function closeVRRPModal() {
  13133. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13134. }
  13135. async function submitSaveVRRP(e) {
  13136. e.preventDefault();
  13137. const id = document.getElementById('modal-vrrp-id').value;
  13138. const name = document.getElementById('modal-vrrp-name').value.trim();
  13139. const iface = document.getElementById('modal-vrrp-iface').value;
  13140. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13141. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13142. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13143. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13144. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13145. const authType = document.getElementById('modal-vrrp-authtype').value;
  13146. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13147. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13148. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13149. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13150. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13151. try {
  13152. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13153. method: 'POST',
  13154. headers: { 'Content-Type': 'application/json' },
  13155. body: JSON.stringify({
  13156. id,
  13157. name,
  13158. interface: iface,
  13159. vrid,
  13160. priority,
  13161. virtual_ips: vips,
  13162. version,
  13163. interval,
  13164. auth_type: authType,
  13165. auth_password: authPass,
  13166. comment,
  13167. preempt,
  13168. disabled
  13169. })
  13170. });
  13171. if (res.ok) {
  13172. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13173. closeVRRPModal();
  13174. loadVRRP(false);
  13175. fetchData(false);
  13176. } else {
  13177. const err = await res.text();
  13178. showToast('Error', err, 'error');
  13179. }
  13180. } catch (err) {
  13181. showToast('Error', err.message, 'error');
  13182. }
  13183. }
  13184. async function deleteVRRP(id, name) {
  13185. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13186. try {
  13187. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13188. if (res.ok) {
  13189. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13190. loadVRRP(false);
  13191. fetchData(false);
  13192. } else {
  13193. const err = await res.text();
  13194. showToast('Error', err, 'error');
  13195. }
  13196. } catch (err) {
  13197. showToast('Error', err.message, 'error');
  13198. }
  13199. }
  13200. async function toggleVRRPState(id, disabled) {
  13201. try {
  13202. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13203. method: 'POST',
  13204. headers: { 'Content-Type': 'application/json' },
  13205. body: JSON.stringify({ disabled })
  13206. });
  13207. if (res.ok) {
  13208. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13209. loadVRRP(false);
  13210. fetchData(false);
  13211. } else {
  13212. const err = await res.text();
  13213. showToast('Error', err, 'error');
  13214. }
  13215. } catch (err) {
  13216. showToast('Error', err.message, 'error');
  13217. }
  13218. }
  13219. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13220. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13221. const docTableObserver = new MutationObserver((mutations) => {
  13222. let needsInit = false;
  13223. for (const m of mutations) {
  13224. for (const node of m.addedNodes) {
  13225. if (node.nodeType === 1) {
  13226. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  13227. needsInit = true;
  13228. break;
  13229. }
  13230. }
  13231. }
  13232. if (needsInit) break;
  13233. }
  13234. if (needsInit) {
  13235. initTableSorting();
  13236. }
  13237. });
  13238. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13239. }
  13240. // =========================================================================
  13241. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13242. // =========================================================================
  13243. const bwtestState = {
  13244. running: false,
  13245. pollTimer: null,
  13246. eventSource: null,
  13247. chartPoints: [],
  13248. maxChartPoints: 60,
  13249. serverConfig: null,
  13250. peakTx: 0,
  13251. peakRx: 0,
  13252. targetDuration: 10,
  13253. lastSampleIndex: 0
  13254. };
  13255. async function loadBwTestView() {
  13256. fetchBwTestServerStatus();
  13257. loadBwTestHistory();
  13258. resizeBwTestCanvas();
  13259. checkActiveBwTest();
  13260. }
  13261. async function fetchBwTestServerStatus() {
  13262. try {
  13263. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13264. if (!res.ok) return;
  13265. const s = await res.json();
  13266. bwtestState.serverConfig = s;
  13267. // Update indicator and badges
  13268. const indicator = document.getElementById('bwtest-server-indicator');
  13269. const badge = document.getElementById('bwtest-server-badge');
  13270. const sideBadge = document.getElementById('badge-bwtest-server');
  13271. if (s.enabled && s.running) {
  13272. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13273. if (badge) {
  13274. badge.innerText = `Port ${s.port} (Active)`;
  13275. badge.className = 'text-emerald-400 font-bold';
  13276. }
  13277. if (sideBadge) {
  13278. sideBadge.innerText = s.port;
  13279. 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';
  13280. }
  13281. } else {
  13282. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13283. if (badge) {
  13284. badge.innerText = `Disabled`;
  13285. badge.className = 'text-slate-500 font-bold';
  13286. }
  13287. if (sideBadge) {
  13288. sideBadge.innerText = 'Off';
  13289. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13290. }
  13291. }
  13292. // Modal fields
  13293. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13294. if (toggle) toggle.checked = !!s.enabled;
  13295. const portInp = document.getElementById('bwtest-server-port-input');
  13296. if (portInp) portInp.value = s.port || 2000;
  13297. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13298. if (actSess) actSess.innerText = s.active_sessions || 0;
  13299. const totServ = document.getElementById('bwtest-modal-total-served');
  13300. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13301. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13302. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13303. } catch (err) {
  13304. console.error('Failed to fetch BwTest server status:', err);
  13305. }
  13306. }
  13307. function openBwTestServerModal() {
  13308. fetchBwTestServerStatus();
  13309. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13310. }
  13311. function closeBwTestServerModal() {
  13312. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13313. }
  13314. async function submitBwTestServerSettings(e) {
  13315. e.preventDefault();
  13316. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13317. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13318. try {
  13319. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13320. method: 'POST',
  13321. headers: { 'Content-Type': 'application/json' },
  13322. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13323. });
  13324. if (!res.ok) {
  13325. const err = await res.json();
  13326. throw new Error(err.error || 'Failed to update server configuration');
  13327. }
  13328. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13329. closeBwTestServerModal();
  13330. fetchBwTestServerStatus();
  13331. } catch (err) {
  13332. showToast('Server Configuration Error', err.message, 'error');
  13333. }
  13334. }
  13335. function setBwTestTarget(target) {
  13336. const inp = document.getElementById('bwtest-input-target');
  13337. if (inp) inp.value = target;
  13338. }
  13339. function setBwTestProtocol(proto) {
  13340. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13341. if (hiddenInp) hiddenInp.value = proto;
  13342. const btnUdp = document.getElementById('bwtest-proto-udp');
  13343. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13344. const badge = document.getElementById('bwtest-proto-badge');
  13345. const pktField = document.getElementById('bwtest-field-pktsize');
  13346. 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';
  13347. 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';
  13348. 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';
  13349. if (proto === 'udp') {
  13350. if (btnUdp) {
  13351. btnUdp.className = activeUdpCls;
  13352. const dot = btnUdp.querySelector('span');
  13353. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13354. }
  13355. if (btnTcp) {
  13356. btnTcp.className = inactiveCls;
  13357. const dot = btnTcp.querySelector('span');
  13358. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13359. }
  13360. if (badge) {
  13361. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13362. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13363. }
  13364. if (pktField) pktField.classList.remove('opacity-40');
  13365. } else {
  13366. if (btnUdp) {
  13367. btnUdp.className = inactiveCls;
  13368. const dot = btnUdp.querySelector('span');
  13369. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13370. }
  13371. if (btnTcp) {
  13372. btnTcp.className = activeTcpCls;
  13373. const dot = btnTcp.querySelector('span');
  13374. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13375. }
  13376. if (badge) {
  13377. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13378. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13379. }
  13380. if (pktField) pktField.classList.add('opacity-40');
  13381. }
  13382. }
  13383. function setBwTestDirection(dir) {
  13384. const hiddenInp = document.getElementById('bwtest-input-direction');
  13385. if (hiddenInp) hiddenInp.value = dir;
  13386. const btnBoth = document.getElementById('bwtest-dir-both');
  13387. const btnTx = document.getElementById('bwtest-dir-tx');
  13388. const btnRx = document.getElementById('bwtest-dir-rx');
  13389. 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';
  13390. 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';
  13391. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13392. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13393. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13394. }
  13395. function setBwTestLimit(bps) {
  13396. const sel = document.getElementById('bwtest-input-limit');
  13397. if (sel) sel.value = String(bps);
  13398. }
  13399. async function checkActiveBwTest() {
  13400. try {
  13401. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13402. if (!res.ok) return;
  13403. const st = await res.json();
  13404. if (st.running) {
  13405. setBwTestRunningUI(true);
  13406. if (st.current_sample) handleBwTestSample(st.current_sample);
  13407. startBwTestTelemetry();
  13408. }
  13409. } catch (err) {
  13410. console.error('Failed to check active BwTest:', err);
  13411. }
  13412. }
  13413. async function startBwTest(e) {
  13414. if (e && e.preventDefault) e.preventDefault();
  13415. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13416. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13417. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13418. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13419. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13420. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13421. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13422. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13423. bwtestState.targetDuration = duration;
  13424. bwtestState.chartPoints = [];
  13425. bwtestState.peakTx = 0;
  13426. bwtestState.peakRx = 0;
  13427. bwtestState.lastSampleIndex = 0;
  13428. // Clear UI elements
  13429. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13430. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13431. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13432. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13433. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13434. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13435. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13436. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13437. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13438. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13439. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13440. const tbody = document.getElementById('bwtest-samples-tbody');
  13441. if (tbody) tbody.innerHTML = '';
  13442. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13443. setBwTestRunningUI(true);
  13444. try {
  13445. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13446. method: 'POST',
  13447. headers: { 'Content-Type': 'application/json' },
  13448. body: JSON.stringify({
  13449. target,
  13450. port,
  13451. direction,
  13452. protocol,
  13453. bandwidth_limit,
  13454. packet_size,
  13455. streams,
  13456. duration
  13457. })
  13458. });
  13459. if (!res.ok) {
  13460. const err = await res.json();
  13461. throw new Error(err.error || 'Failed to start bandwidth test');
  13462. }
  13463. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13464. startBwTestTelemetry();
  13465. } catch (err) {
  13466. setBwTestRunningUI(false);
  13467. showToast('Start Failed', err.message, 'error');
  13468. }
  13469. }
  13470. function setBwTestRunningUI(running) {
  13471. bwtestState.running = running;
  13472. const startBtn = document.getElementById('bwtest-btn-start');
  13473. const stopBtn = document.getElementById('bwtest-btn-stop');
  13474. const badge = document.getElementById('bwtest-run-status-badge');
  13475. const ph = document.getElementById('bwtest-chart-placeholder');
  13476. if (running) {
  13477. if (startBtn) {
  13478. startBtn.disabled = true;
  13479. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13480. }
  13481. if (stopBtn) {
  13482. stopBtn.disabled = false;
  13483. stopBtn.classList.remove('opacity-40');
  13484. }
  13485. if (badge) {
  13486. badge.innerText = 'TESTING...';
  13487. 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';
  13488. }
  13489. if (ph) ph.style.display = 'none';
  13490. } else {
  13491. if (startBtn) {
  13492. startBtn.disabled = false;
  13493. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13494. }
  13495. if (stopBtn) {
  13496. stopBtn.disabled = true;
  13497. stopBtn.classList.add('opacity-40');
  13498. }
  13499. if (badge) {
  13500. badge.innerText = 'IDLE';
  13501. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13502. }
  13503. }
  13504. }
  13505. async function stopBwTest() {
  13506. try {
  13507. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13508. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13509. } catch (err) {
  13510. console.error('Failed to stop test:', err);
  13511. }
  13512. }
  13513. function startBwTestTelemetry() {
  13514. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13515. bwtestState.pollTimer = setInterval(async () => {
  13516. try {
  13517. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13518. if (!res.ok) return;
  13519. const st = await res.json();
  13520. if (st.recent_samples && st.recent_samples.length > 0) {
  13521. // Process new samples
  13522. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13523. newSamples.forEach(s => handleBwTestSample(s));
  13524. bwtestState.lastSampleIndex = st.recent_samples.length;
  13525. }
  13526. if (!st.running) {
  13527. clearInterval(bwtestState.pollTimer);
  13528. bwtestState.pollTimer = null;
  13529. setBwTestRunningUI(false);
  13530. handleBwTestFinish(st.summary, st.error);
  13531. }
  13532. } catch (err) {
  13533. console.error('BwTest polling error:', err);
  13534. }
  13535. }, 400);
  13536. }
  13537. function handleBwTestSample(s) {
  13538. if (!s) return;
  13539. const txMbps = s.tx_mbps || 0;
  13540. const rxMbps = s.rx_mbps || 0;
  13541. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13542. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13543. // KPI updates
  13544. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13545. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13546. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13547. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13548. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13549. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13550. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13551. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13552. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13553. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13554. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13555. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13556. const elLoss = document.getElementById('bwtest-stat-loss');
  13557. if (elLoss) {
  13558. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13559. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13560. }
  13561. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13562. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13563. const elJitter = document.getElementById('bwtest-stat-jitter');
  13564. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13565. const elTime = document.getElementById('bwtest-stat-time');
  13566. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13567. const elData = document.getElementById('bwtest-stat-data');
  13568. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13569. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13570. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13571. // Append point to chart buffer
  13572. bwtestState.chartPoints.push({
  13573. elapsed: s.elapsed_sec || 0,
  13574. tx: txMbps,
  13575. rx: rxMbps
  13576. });
  13577. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13578. bwtestState.chartPoints.shift();
  13579. }
  13580. drawBwTestChart();
  13581. // Add row to breakdown table
  13582. const tbody = document.getElementById('bwtest-samples-tbody');
  13583. if (tbody) {
  13584. const tr = document.createElement('tr');
  13585. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13586. tr.innerHTML = `
  13587. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13588. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13589. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13590. <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>
  13591. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13592. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13593. `;
  13594. tbody.insertBefore(tr, tbody.firstChild);
  13595. const countEl = document.getElementById('bwtest-sample-count');
  13596. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13597. }
  13598. }
  13599. function handleBwTestFinish(summary, error) {
  13600. const badge = document.getElementById('bwtest-run-status-badge');
  13601. if (error) {
  13602. showToast('Benchmark Error', error, 'error');
  13603. if (badge) {
  13604. badge.innerText = 'ERROR';
  13605. 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';
  13606. }
  13607. } else if (summary) {
  13608. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13609. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13610. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13611. if (badge) {
  13612. badge.innerText = 'COMPLETED';
  13613. 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';
  13614. }
  13615. }
  13616. loadBwTestHistory();
  13617. fetchBwTestServerStatus();
  13618. }
  13619. function resizeBwTestCanvas() {
  13620. const canvas = document.getElementById('bwtest-chart');
  13621. if (!canvas || !canvas.parentElement) return;
  13622. const rect = canvas.parentElement.getBoundingClientRect();
  13623. const dpr = window.devicePixelRatio || 1;
  13624. canvas.width = rect.width * dpr;
  13625. canvas.height = rect.height * dpr;
  13626. const ctx = canvas.getContext('2d');
  13627. ctx.scale(dpr, dpr);
  13628. drawBwTestChart();
  13629. }
  13630. window.addEventListener('resize', () => {
  13631. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13632. });
  13633. function drawBwTestChart() {
  13634. const canvas = document.getElementById('bwtest-chart');
  13635. if (!canvas) return;
  13636. const ctx = canvas.getContext('2d');
  13637. const dpr = window.devicePixelRatio || 1;
  13638. const width = canvas.width / dpr;
  13639. const height = canvas.height / dpr;
  13640. ctx.clearRect(0, 0, width, height);
  13641. const points = bwtestState.chartPoints;
  13642. if (!points || points.length === 0) return;
  13643. // Determine scale ceiling
  13644. let maxRate = 10;
  13645. for (const p of points) {
  13646. if (p.tx > maxRate) maxRate = p.tx;
  13647. if (p.rx > maxRate) maxRate = p.rx;
  13648. }
  13649. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13650. const paddingLeft = 55;
  13651. const paddingBottom = 24;
  13652. const paddingTop = 12;
  13653. const paddingRight = 16;
  13654. const chartW = width - paddingLeft - paddingRight;
  13655. const chartH = height - paddingTop - paddingBottom;
  13656. // Grid Lines and Y-Axis labels
  13657. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13658. ctx.lineWidth = 1;
  13659. ctx.fillStyle = '#94a3b8';
  13660. ctx.font = '10px monospace';
  13661. ctx.textAlign = 'right';
  13662. const gridSteps = 4;
  13663. for (let i = 0; i <= gridSteps; i++) {
  13664. const val = (maxRate / gridSteps) * i;
  13665. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13666. ctx.beginPath();
  13667. ctx.moveTo(paddingLeft, y);
  13668. ctx.lineTo(width - paddingRight, y);
  13669. ctx.stroke();
  13670. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13671. }
  13672. // Draw TX Line (Cyan #22d3ee)
  13673. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13674. // Draw RX Line (Purple #a855f7)
  13675. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13676. }
  13677. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13678. if (points.length < 2) return;
  13679. const stepX = w / Math.max(points.length - 1, 1);
  13680. // Gradient area fill
  13681. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13682. grad.addColorStop(0, fillColor);
  13683. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13684. ctx.beginPath();
  13685. points.forEach((p, idx) => {
  13686. const x = left + idx * stepX;
  13687. const val = valFn(p);
  13688. const y = top + h - (val / maxVal) * h;
  13689. if (idx === 0) {
  13690. ctx.moveTo(x, y);
  13691. } else {
  13692. ctx.lineTo(x, y);
  13693. }
  13694. });
  13695. // Complete path for fill
  13696. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13697. ctx.lineTo(left, top + h);
  13698. ctx.closePath();
  13699. ctx.fillStyle = grad;
  13700. ctx.fill();
  13701. // Draw line stroke
  13702. ctx.beginPath();
  13703. ctx.lineWidth = 2.5;
  13704. ctx.strokeStyle = strokeColor;
  13705. points.forEach((p, idx) => {
  13706. const x = left + idx * stepX;
  13707. const val = valFn(p);
  13708. const y = top + h - (val / maxVal) * h;
  13709. if (idx === 0) {
  13710. ctx.moveTo(x, y);
  13711. } else {
  13712. ctx.lineTo(x, y);
  13713. }
  13714. });
  13715. ctx.stroke();
  13716. // Draw end point halo
  13717. const lastP = points[points.length - 1];
  13718. const lastX = left + (points.length - 1) * stepX;
  13719. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13720. ctx.fillStyle = strokeColor;
  13721. ctx.beginPath();
  13722. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13723. ctx.fill();
  13724. }
  13725. async function loadBwTestHistory() {
  13726. try {
  13727. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13728. if (!res.ok) return;
  13729. const list = await res.json();
  13730. renderBwTestHistory(Array.isArray(list) ? list : []);
  13731. } catch (err) {
  13732. console.error('Failed to load BwTest history:', err);
  13733. }
  13734. }
  13735. function renderBwTestHistory(list) {
  13736. const tbody = document.getElementById('bwtest-history-tbody');
  13737. if (!tbody) return;
  13738. if (list.length === 0) {
  13739. 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>`;
  13740. return;
  13741. }
  13742. tbody.innerHTML = '';
  13743. list.forEach(item => {
  13744. const s = item.summary || {};
  13745. const tr = document.createElement('tr');
  13746. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13747. const dirBadge = item.direction === 'both'
  13748. ? `<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>`
  13749. : item.direction === 'tx'
  13750. ? `<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>`
  13751. : `<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>`;
  13752. const protoBadge = item.protocol === 'tcp'
  13753. ? `<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>`
  13754. : `<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>`;
  13755. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13756. tr.innerHTML = `
  13757. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13758. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13759. <td class="py-2.5 px-4">${protoBadge}</td>
  13760. <td class="py-2.5 px-4">${dirBadge}</td>
  13761. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13762. <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>
  13763. <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>
  13764. <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>
  13765. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13766. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13767. `;
  13768. tbody.appendChild(tr);
  13769. });
  13770. }
  13771. // ======================== SETTINGS & ROUTER DNS ========================
  13772. state.settingsSubTab = 'dns';
  13773. state.dnsSettings = null;
  13774. state.dnsStaticRecords = [];
  13775. state.dnsStatus = null;
  13776. function switchSettingsSubTab(sub) {
  13777. state.settingsSubTab = sub;
  13778. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13779. const btnSys = document.getElementById('btn-settings-subtab-system');
  13780. const tabDns = document.getElementById('settings-subtab-dns');
  13781. const tabSys = document.getElementById('settings-subtab-system');
  13782. if (sub === 'dns') {
  13783. if (btnDns) {
  13784. 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';
  13785. }
  13786. if (btnSys) {
  13787. 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';
  13788. }
  13789. tabDns?.classList.remove('hidden');
  13790. tabSys?.classList.add('hidden');
  13791. loadDNSSettings();
  13792. } else {
  13793. if (btnSys) {
  13794. 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';
  13795. }
  13796. if (btnDns) {
  13797. 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';
  13798. }
  13799. tabSys?.classList.remove('hidden');
  13800. tabDns?.classList.add('hidden');
  13801. loadSystemSettings();
  13802. }
  13803. }
  13804. async function loadSettingsData(showLoading = false) {
  13805. if (state.settingsSubTab === 'system') {
  13806. await loadSystemSettings();
  13807. } else {
  13808. await loadDNSSettings();
  13809. }
  13810. }
  13811. async function loadDNSSettings() {
  13812. try {
  13813. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13814. fetch(`${API_BASE}/dns/settings`),
  13815. fetch(`${API_BASE}/dns/static`),
  13816. fetch(`${API_BASE}/dns/status`)
  13817. ]);
  13818. if (settingsRes.ok) {
  13819. state.dnsSettings = await settingsRes.json();
  13820. populateDNSSettingsForm(state.dnsSettings);
  13821. }
  13822. if (staticRes.ok) {
  13823. state.dnsStaticRecords = await staticRes.json();
  13824. renderStaticDNSList();
  13825. }
  13826. if (statusRes.ok) {
  13827. state.dnsStatus = await statusRes.json();
  13828. updateDNSStatusView(state.dnsStatus);
  13829. }
  13830. } catch (err) {
  13831. console.error('Failed to load DNS settings:', err);
  13832. }
  13833. }
  13834. function populateDNSSettingsForm(s) {
  13835. if (!s) return;
  13836. const dnsForm = document.getElementById('form-dns-settings');
  13837. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13838. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13839. if (dynamicEl) {
  13840. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13841. 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(' ');
  13842. } else {
  13843. dynamicEl.innerText = 'None';
  13844. }
  13845. }
  13846. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13847. if (isEditing) return;
  13848. const serversInput = document.getElementById('dns-servers-input');
  13849. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13850. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13851. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13852. const domainInput = document.getElementById('dns-domain-input');
  13853. if (domainInput) domainInput.value = s.domain || '';
  13854. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13855. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13856. }
  13857. function updateDNSStatusView(st) {
  13858. if (!st) return;
  13859. const preview = document.getElementById('dns-resolv-preview');
  13860. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13861. const pillText = document.getElementById('dns-live-status-text');
  13862. const pill = document.getElementById('dns-live-status-pill');
  13863. if (pill && pillText) {
  13864. if (st.service_running) {
  13865. 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';
  13866. pillText.innerText = 'DNS Service Active';
  13867. } else {
  13868. 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';
  13869. pillText.innerText = 'DNS Service Inactive';
  13870. }
  13871. }
  13872. }
  13873. function appendDNSPreset(preset) {
  13874. const input = document.getElementById('dns-servers-input');
  13875. if (!input) return;
  13876. const dnsForm = document.getElementById('form-dns-settings');
  13877. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13878. const current = input.value.trim();
  13879. if (!current) {
  13880. input.value = preset;
  13881. } else {
  13882. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13883. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13884. toAdd.forEach(ip => {
  13885. if (!existing.includes(ip)) existing.push(ip);
  13886. });
  13887. input.value = existing.join(', ');
  13888. }
  13889. }
  13890. async function saveDNSSettings(e) {
  13891. e.preventDefault();
  13892. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13893. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13894. if (servers.length === 0) {
  13895. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13896. return;
  13897. }
  13898. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13899. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13900. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13901. try {
  13902. const res = await fetch(`${API_BASE}/dns/settings`, {
  13903. method: 'POST',
  13904. headers: { 'Content-Type': 'application/json' },
  13905. body: JSON.stringify({
  13906. servers: servers,
  13907. cache_size: cacheSize,
  13908. domain: domain,
  13909. allow_remote_requests: allowRemote
  13910. })
  13911. });
  13912. const data = await res.json();
  13913. if (res.ok) {
  13914. const dnsForm = document.getElementById('form-dns-settings');
  13915. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13916. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13917. loadDNSSettings();
  13918. } else {
  13919. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13920. }
  13921. } catch (err) {
  13922. showToast('Error', err.message, 'error');
  13923. }
  13924. }
  13925. async function flushDNSCache() {
  13926. try {
  13927. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13928. if (res.ok) {
  13929. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13930. loadDNSSettings();
  13931. } else {
  13932. const err = await res.json();
  13933. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13934. }
  13935. } catch (err) {
  13936. showToast('Error', err.message, 'error');
  13937. }
  13938. }
  13939. function renderStaticDNSList() {
  13940. const tbody = document.getElementById('dns-static-tbody');
  13941. const empty = document.getElementById('dns-static-empty');
  13942. const badge = document.getElementById('dns-static-count-badge');
  13943. if (!tbody) return;
  13944. tbody.innerHTML = '';
  13945. const records = state.dnsStaticRecords || [];
  13946. if (badge) badge.innerText = `${records.length} Records`;
  13947. if (records.length === 0) {
  13948. empty?.classList.remove('hidden');
  13949. return;
  13950. }
  13951. empty?.classList.add('hidden');
  13952. records.forEach(rec => {
  13953. const tr = document.createElement('tr');
  13954. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13955. tr.innerHTML = `
  13956. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13957. <td class="py-2.5 px-4">
  13958. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13959. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13960. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13961. }">
  13962. ${rec.type || 'A'}
  13963. </span>
  13964. </td>
  13965. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13966. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13967. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13968. <td class="py-2.5 px-4">
  13969. <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'}">
  13970. ${rec.disabled ? 'Disabled' : 'Active'}
  13971. </span>
  13972. </td>
  13973. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13974. <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>
  13975. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13976. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13977. </td>
  13978. `;
  13979. tbody.appendChild(tr);
  13980. });
  13981. }
  13982. function openStaticDNSModal(id = null) {
  13983. const modal = document.getElementById('modal-static-dns');
  13984. const title = document.getElementById('modal-static-dns-title');
  13985. const form = document.getElementById('form-static-dns');
  13986. if (!modal || !form) return;
  13987. form.reset();
  13988. document.getElementById('modal-static-dns-id').value = '';
  13989. if (id) {
  13990. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  13991. if (rec) {
  13992. if (title) title.innerText = 'Edit Static DNS Record';
  13993. document.getElementById('modal-static-dns-id').value = rec.id;
  13994. document.getElementById('modal-static-dns-name').value = rec.name;
  13995. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  13996. document.getElementById('modal-static-dns-addr').value = rec.address;
  13997. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  13998. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  13999. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14000. }
  14001. } else {
  14002. if (title) title.innerText = 'Add Static DNS Record';
  14003. }
  14004. modal.classList.remove('hidden');
  14005. }
  14006. function closeStaticDNSModal() {
  14007. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14008. }
  14009. async function submitSaveStaticDNS(e) {
  14010. e.preventDefault();
  14011. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14012. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14013. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14014. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14015. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14016. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14017. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14018. if (!name || !address) {
  14019. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14020. return;
  14021. }
  14022. try {
  14023. const res = await fetch(`${API_BASE}/dns/static`, {
  14024. method: 'POST',
  14025. headers: { 'Content-Type': 'application/json' },
  14026. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14027. });
  14028. const data = await res.json();
  14029. if (res.ok) {
  14030. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14031. closeStaticDNSModal();
  14032. loadDNSSettings();
  14033. } else {
  14034. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14035. }
  14036. } catch (err) {
  14037. showToast('Error', err.message, 'error');
  14038. }
  14039. }
  14040. async function deleteStaticDNS(id) {
  14041. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14042. try {
  14043. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14044. if (res.ok) {
  14045. showToast('Deleted', 'Static DNS record deleted', 'success');
  14046. loadDNSSettings();
  14047. }
  14048. } catch (err) {
  14049. showToast('Error', err.message, 'error');
  14050. }
  14051. }
  14052. async function toggleStaticDNS(id, disabled) {
  14053. try {
  14054. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14055. method: 'POST',
  14056. headers: { 'Content-Type': 'application/json' },
  14057. body: JSON.stringify({ disabled })
  14058. });
  14059. if (res.ok) {
  14060. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14061. loadDNSSettings();
  14062. }
  14063. } catch (err) {
  14064. showToast('Error', err.message, 'error');
  14065. }
  14066. }
  14067. async function loadSystemSettings() {
  14068. try {
  14069. const sysForm = document.getElementById('form-system-settings');
  14070. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14071. const res = await fetch(`${API_BASE}/system/settings`);
  14072. if (res.ok) {
  14073. const data = await res.json();
  14074. if (!isEditing) {
  14075. const hostInput = document.getElementById('system-hostname-input');
  14076. if (hostInput) hostInput.value = data.hostname || '';
  14077. const tzInput = document.getElementById('system-timezone-input');
  14078. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14079. }
  14080. }
  14081. } catch (err) {
  14082. console.error('Failed to load system settings:', err);
  14083. }
  14084. }
  14085. async function saveSystemSettings(e) {
  14086. e.preventDefault();
  14087. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14088. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14089. try {
  14090. const res = await fetch(`${API_BASE}/system/settings`, {
  14091. method: 'POST',
  14092. headers: { 'Content-Type': 'application/json' },
  14093. body: JSON.stringify({ hostname, timezone })
  14094. });
  14095. const data = await res.json();
  14096. if (res.ok) {
  14097. const sysForm = document.getElementById('form-system-settings');
  14098. if (sysForm) sysForm.dataset.dirty = 'false';
  14099. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14100. const sideH = document.getElementById('side-hostname');
  14101. if (sideH) sideH.innerText = data.hostname;
  14102. } else {
  14103. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14104. }
  14105. } catch (err) {
  14106. showToast('Error', err.message, 'error');
  14107. }
  14108. }