app.js 662 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. initLiveTrafficStream();
  80. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  81. setInterval(() => {
  82. if (state.isPolling) {
  83. fetchData(false);
  84. }
  85. }, 5000);
  86. });
  87. let trafficEventSource = null;
  88. let trafficPollFallback = null;
  89. function initLiveTrafficStream() {
  90. if (trafficEventSource) {
  91. try { trafficEventSource.close(); } catch(e) {}
  92. trafficEventSource = null;
  93. }
  94. if (trafficPollFallback) {
  95. clearInterval(trafficPollFallback);
  96. trafficPollFallback = null;
  97. }
  98. if (window.EventSource) {
  99. try {
  100. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  101. trafficEventSource.onmessage = (event) => {
  102. try {
  103. const data = JSON.parse(event.data);
  104. updateLiveInterfaceTraffic(data);
  105. } catch (e) {
  106. console.error('Error parsing live traffic event:', e);
  107. }
  108. };
  109. trafficEventSource.onerror = () => {
  110. // Fallback polling if SSE disconnects
  111. if (!trafficPollFallback) {
  112. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  113. }
  114. };
  115. trafficEventSource.onopen = () => {
  116. if (trafficPollFallback) {
  117. clearInterval(trafficPollFallback);
  118. trafficPollFallback = null;
  119. }
  120. };
  121. return;
  122. } catch (e) {
  123. console.warn('EventSource failed, using 1s polling fallback:', e);
  124. }
  125. }
  126. // Fallback if EventSource is unavailable
  127. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  128. }
  129. async function pollLiveTrafficSnapshot() {
  130. try {
  131. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  132. if (res.ok) {
  133. const data = await res.json();
  134. updateLiveInterfaceTraffic(data);
  135. }
  136. } catch (e) {}
  137. }
  138. function updateLiveInterfaceTraffic(data) {
  139. if (!data || !data.interfaces) return;
  140. state.latestTraffic = data;
  141. // 1. Update Top & Dashboard Total Bandwidth Indicators
  142. const rxHuman = data.total_rx_human || '0 B/s';
  143. const txHuman = data.total_tx_human || '0 B/s';
  144. const statRx = document.getElementById('stat-traffic-rx');
  145. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  146. const statTx = document.getElementById('stat-traffic-tx');
  147. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  148. // 2. Update state.interfaces rates in-memory
  149. if (Array.isArray(state.interfaces)) {
  150. state.interfaces.forEach(i => {
  151. const live = data.interfaces[i.name];
  152. if (live) {
  153. i.rate = {
  154. rx_bytes_sec: live.rx_bytes_sec,
  155. tx_bytes_sec: live.tx_bytes_sec,
  156. rx_human: live.rx_human,
  157. tx_human: live.tx_human
  158. };
  159. i.stats = {
  160. rx_bytes: live.rx_bytes,
  161. tx_bytes: live.tx_bytes,
  162. rx_packets: live.rx_packets,
  163. tx_packets: live.tx_packets,
  164. rx_errors: live.rx_errors,
  165. tx_errors: live.tx_errors,
  166. rx_dropped: live.rx_dropped,
  167. tx_dropped: live.tx_dropped
  168. };
  169. }
  170. });
  171. }
  172. // 3. Update all live UI rate spans in-place (ZERO flicker)
  173. Object.keys(data.interfaces).forEach(name => {
  174. const live = data.interfaces[name];
  175. // Dashboard Port Matrix Card
  176. const cardRate = document.getElementById(`port-card-rate-${name}`);
  177. if (cardRate && cardRate.innerText !== live.rx_human) {
  178. cardRate.innerText = live.rx_human;
  179. }
  180. // Dashboard Quick Interfaces Table
  181. const quickRx = document.getElementById(`quick-rx-${name}`);
  182. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  183. const quickTx = document.getElementById(`quick-tx-${name}`);
  184. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  185. // Main Interfaces Tree Table
  186. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  187. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  188. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  189. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  190. // VLAN Sub-interfaces Table
  191. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  192. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  193. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  194. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  195. // VLAN Page Table
  196. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  197. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  198. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  199. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  200. });
  201. }
  202. // Navigation Handler
  203. function navigate(tabName) {
  204. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  205. navigate('bgp');
  206. return;
  207. }
  208. if (tabName === 'vlans') {
  209. navigate('interfaces');
  210. return;
  211. }
  212. state.activeTab = tabName;
  213. window.location.hash = tabName;
  214. // Update nav links styling
  215. document.querySelectorAll('.nav-link').forEach(link => {
  216. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  217. });
  218. const activeNav = document.getElementById(`nav-${tabName}`);
  219. if (activeNav) {
  220. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  221. }
  222. // Update page headers
  223. const titles = {
  224. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  225. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  226. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  227. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  228. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  229. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  230. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  231. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  232. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  233. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  234. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  235. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  236. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  237. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  238. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  239. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  240. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  241. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  242. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  243. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  244. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  245. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  246. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  247. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  248. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  249. };
  250. const header = titles[tabName] || titles.dashboard;
  251. const pTitle = document.getElementById('page-title');
  252. if (pTitle) pTitle.innerText = header.title;
  253. const pSub = document.getElementById('page-subtitle');
  254. if (pSub) pSub.innerText = header.sub;
  255. // Toggle sections dynamically for all section elements
  256. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  257. if (el.id === `section-${tabName}`) {
  258. el.classList.remove('hidden');
  259. } else {
  260. el.classList.add('hidden');
  261. }
  262. });
  263. if (tabName === 'interfaces') {
  264. loadRoles();
  265. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  266. else switchIfaceSubTab('tree');
  267. }
  268. if (tabName === 'bridge') loadBridge();
  269. if (tabName === 'firewall') loadFirewall();
  270. if (tabName === 'routes') loadRoutes();
  271. if (tabName === 'bgp') {
  272. loadDynamicRouting();
  273. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  274. }
  275. if (tabName === 'ospf') {
  276. loadDynamicRouting();
  277. switchOspfTab(state.activeOspfTab || 'instances');
  278. }
  279. if (tabName === 'routing-filters') loadDynamicRouting();
  280. if (tabName === 'dynamic-routing') loadDynamicRouting();
  281. if (tabName === 'ppp') loadPPP();
  282. if (tabName === 'eoip') loadEoIP();
  283. if (tabName === 'aerotun') loadAeroTUN();
  284. if (tabName === 'persistence') loadDebianConfig();
  285. if (tabName === 'pppoe') loadPPPoE();
  286. if (tabName === 'wireguard') loadWireGuard();
  287. if (tabName === 'ipsec') loadIPSec();
  288. if (tabName === 'l2tp') loadL2TP();
  289. if (tabName === 'pptp') loadPPTP();
  290. if (tabName === 'tools') loadToolsView();
  291. if (tabName === 'dhcp-client') loadDHCPClients();
  292. if (tabName === 'dhcp-server') loadDHCPServer();
  293. if (tabName === 'vrrp') loadVRRP();
  294. if (tabName === 'bwtest') loadBwTestView();
  295. if (tabName === 'settings') loadSettingsData();
  296. setTimeout(initTableSorting, 50);
  297. }
  298. // Fetch all core system, network and VPN telemetry
  299. async function fetchData(isManual = false) {
  300. const spinner = document.getElementById('refresh-spinner');
  301. if (isManual && spinner) spinner.classList.add('animate-spin');
  302. try {
  303. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  304. fetch(`${API_BASE}/system/status`),
  305. fetch(`${API_BASE}/interfaces`),
  306. fetch(`${API_BASE}/vlans`),
  307. fetch(`${API_BASE}/vpn/status`),
  308. fetch(`${API_BASE}/firewall/summary`),
  309. fetch(`${API_BASE}/routing/dynamic/summary`),
  310. fetch(`${API_BASE}/bridge/summary`),
  311. fetch(`${API_BASE}/dhcp/clients/summary`),
  312. fetch(`${API_BASE}/dhcp/clients`),
  313. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  314. fetch(`${API_BASE}/roles`).catch(() => null)
  315. ]);
  316. if (rolesRes && rolesRes.ok) {
  317. state.roles = await rolesRes.json();
  318. const countEl = document.getElementById('badge-roles-count');
  319. if (countEl) countEl.innerText = (state.roles || []).length;
  320. }
  321. if (vrrpSumRes && vrrpSumRes.ok) {
  322. state.vrrpSummary = await vrrpSumRes.json();
  323. renderVRRPSummary();
  324. }
  325. if (dhcpSumRes && dhcpSumRes.ok) {
  326. state.dhcpSummary = await dhcpSumRes.json();
  327. const bDhcp = document.getElementById('badge-dhcp-client-count');
  328. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  329. }
  330. if (dhcpClientsRes && dhcpClientsRes.ok) {
  331. state.dhcpClients = await dhcpClientsRes.json();
  332. }
  333. if (brSummaryRes.ok) {
  334. state.bridgeSummary = await brSummaryRes.json();
  335. const bBridge = document.getElementById('badge-bridge-count');
  336. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  337. const sBr = document.getElementById('bridge-stat-bridges');
  338. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  339. const sPorts = document.getElementById('bridge-stat-ports');
  340. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  341. const sHosts = document.getElementById('bridge-stat-hosts');
  342. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  343. }
  344. if (statusRes.ok) state.systemStatus = await statusRes.json();
  345. if (ifacesRes.ok) {
  346. const ifacesData = await ifacesRes.json();
  347. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  348. state.interfaces = rawIfaces.filter(i => {
  349. if (!i.name) return false;
  350. if (i.name.startsWith('ep_')) return false;
  351. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  352. });
  353. try { populateToolsInterfaces(); } catch (e) {}
  354. }
  355. if (vlansRes.ok) {
  356. const vlansData = await vlansRes.json();
  357. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  358. }
  359. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  360. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  361. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  362. updateSystemMetrics();
  363. updateBadges();
  364. if (state.activeTab === 'dashboard') renderDashboard();
  365. if (state.activeTab === 'interfaces') {
  366. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  367. else renderInterfacesList();
  368. }
  369. if (state.activeTab === 'vlans') renderVlansList();
  370. if (state.activeTab === 'firewall') loadFirewall(false);
  371. if (state.activeTab === 'routes') loadRoutes(false);
  372. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  373. if (state.activeTab === 'ppp') loadPPP(false);
  374. if (state.activeTab === 'eoip') loadEoIP(false);
  375. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  376. if (state.activeTab === 'pppoe') loadPPPoE(false);
  377. if (state.activeTab === 'wireguard') loadWireGuard(false);
  378. if (state.activeTab === 'ipsec') loadIPSec(false);
  379. if (state.activeTab === 'l2tp') loadL2TP(false);
  380. if (state.activeTab === 'pptp') loadPPTP(false);
  381. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  382. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  383. if (state.activeTab === 'vrrp') loadVRRP(false);
  384. if (state.activeTab === 'settings') loadSettingsData(false);
  385. fetchBwTestServerStatus();
  386. } catch (err) {
  387. console.error('Failed to fetch router state:', err);
  388. } finally {
  389. if (isManual && spinner) {
  390. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  391. }
  392. }
  393. }
  394. // Update Top KPI and Sidebar Telemetry
  395. function updateSystemMetrics() {
  396. const s = state.systemStatus;
  397. const v = state.vpnStatus;
  398. if (!s) return;
  399. // Sidebar Host & Uptime
  400. const sideHost = document.getElementById('side-hostname');
  401. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  402. const sideUp = document.getElementById('side-uptime');
  403. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  404. const sideGw = document.getElementById('side-gateway-ip');
  405. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  406. // Compute CPU Metrics
  407. let cpuPct = 0;
  408. if (s.cpu_pct !== undefined) {
  409. cpuPct = s.cpu_pct;
  410. } else if (s.cpu_load && s.cpu_load.length > 0) {
  411. const cores = s.cpu_cores || 1;
  412. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  413. }
  414. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  415. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  416. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  417. // Sidebar CPU
  418. const sideCpuVal = document.getElementById('side-cpu-val');
  419. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  420. const sideCpuBar = document.getElementById('side-cpu-bar');
  421. if (sideCpuBar) {
  422. sideCpuBar.style.width = cpuWidth;
  423. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  424. }
  425. // Dashboard CPU Card
  426. const dashCpuVal = document.getElementById('dash-cpu-val');
  427. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  428. const dashCpuBar = document.getElementById('dash-cpu-bar');
  429. if (dashCpuBar) {
  430. dashCpuBar.style.width = cpuWidth;
  431. if (cpuPct > 85) {
  432. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  433. } else if (cpuPct > 65) {
  434. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  435. } else {
  436. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  437. }
  438. }
  439. const dashCpuCores = document.getElementById('dash-cpu-cores');
  440. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  441. const dashCpuLoad = document.getElementById('dash-cpu-load');
  442. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  443. const dashCpuStatus = document.getElementById('dash-cpu-status');
  444. if (dashCpuStatus) {
  445. if (cpuPct > 85) {
  446. dashCpuStatus.innerText = 'High';
  447. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  448. } else if (cpuPct > 65) {
  449. dashCpuStatus.innerText = 'Heavy';
  450. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  451. } else {
  452. dashCpuStatus.innerText = 'Normal';
  453. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  454. }
  455. }
  456. // Compute RAM Metrics
  457. const memPct = Math.round(s.mem_usage_pct || 0);
  458. const memPctStr = `${memPct}%`;
  459. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  460. const usedMB = s.mem_used_mb || 0;
  461. const totalMB = s.mem_total_mb || 0;
  462. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  463. function fmtMemMB(mb) {
  464. if (mb >= 1024) {
  465. return `${(mb / 1024).toFixed(1)} GB`;
  466. }
  467. return `${mb} MB`;
  468. }
  469. // Sidebar RAM
  470. const sideRamVal = document.getElementById('side-ram-val');
  471. if (sideRamVal) sideRamVal.innerText = memPctStr;
  472. const sideRamBar = document.getElementById('side-ram-bar');
  473. if (sideRamBar) sideRamBar.style.width = memWidth;
  474. // Dashboard RAM Card
  475. const dashRamVal = document.getElementById('dash-ram-val');
  476. if (dashRamVal) dashRamVal.innerText = memPctStr;
  477. const dashRamBar = document.getElementById('dash-ram-bar');
  478. if (dashRamBar) {
  479. dashRamBar.style.width = memWidth;
  480. if (memPct > 85) {
  481. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  482. } else if (memPct > 70) {
  483. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  484. } else {
  485. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  486. }
  487. }
  488. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  489. if (dashRamUsedTotal) {
  490. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  491. }
  492. const dashRamFree = document.getElementById('dash-ram-free');
  493. if (dashRamFree) {
  494. dashRamFree.innerText = fmtMemMB(freeMB);
  495. }
  496. const dashRamStatus = document.getElementById('dash-ram-status');
  497. if (dashRamStatus) {
  498. if (memPct > 85) {
  499. dashRamStatus.innerText = 'High';
  500. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  501. } else {
  502. dashRamStatus.innerText = 'Active';
  503. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  504. }
  505. }
  506. // Legacy Dashboard Stats (Safe checks)
  507. const elIfacesUp = document.getElementById('stat-ifaces-up');
  508. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  509. const elIfacesTot = document.getElementById('stat-ifaces-total');
  510. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  511. const elIfacesDown = document.getElementById('stat-ifaces-down');
  512. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  513. const elVlans = document.getElementById('stat-vlans-count');
  514. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  515. // VPN Status Indicators
  516. if (v) {
  517. const totalActive = v.total_active_tunnels || 0;
  518. const statVpnActive = document.getElementById('stat-vpn-active');
  519. if (statVpnActive) statVpnActive.innerText = totalActive;
  520. const tunnelsDot = document.getElementById('tunnels-dot');
  521. const tunnelsLabel = document.getElementById('tunnels-label');
  522. if (tunnelsDot && tunnelsLabel) {
  523. if (totalActive > 0) {
  524. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  525. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  526. } else {
  527. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  528. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  529. }
  530. }
  531. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  532. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  533. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  534. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  535. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  536. }
  537. // Total Live Bandwidth Rate
  538. let totalRx = 0;
  539. let totalTx = 0;
  540. (state.interfaces || []).forEach(i => {
  541. if (i.rate) {
  542. totalRx += i.rate.rx_bytes_sec || 0;
  543. totalTx += i.rate.tx_bytes_sec || 0;
  544. }
  545. });
  546. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  547. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  548. }
  549. function setDotBadge(id, active) {
  550. const el = document.getElementById(id);
  551. if (!el) return;
  552. if (active) {
  553. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  554. } else {
  555. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  556. }
  557. }
  558. function updateBadges() {
  559. const bIfaces = document.getElementById('badge-ifaces-count');
  560. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  561. const bVlans = document.getElementById('badge-vlans-count');
  562. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  563. if (state.fwSummary) {
  564. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  565. const badgeFw = document.getElementById('badge-firewall-count');
  566. if (badgeFw) badgeFw.innerText = totalFwRules;
  567. }
  568. if (state.vpnStatus) {
  569. const v = state.vpnStatus;
  570. const bEoIP = document.getElementById('badge-eoip-count');
  571. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  572. const bAero = document.getElementById('badge-aerotun-count');
  573. if (bAero) bAero.innerText = v.total_aerotun || 0;
  574. const bPPPSess = document.getElementById('badge-ppp-sessions');
  575. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  576. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  577. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  578. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  579. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  580. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  581. }
  582. if (state.dynSummary) {
  583. const d = state.dynSummary;
  584. setDotBadge('badge-bgp-dot', d.bgp_running);
  585. setDotBadge('badge-ospf-dot', d.ospf_running);
  586. const bBgp = document.getElementById('badge-bgp-count');
  587. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  588. const bOspf = document.getElementById('badge-ospf-count');
  589. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  590. const bFilters = document.getElementById('badge-filters-count');
  591. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  592. }
  593. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  594. if (bDhcpServer) {
  595. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  596. }
  597. }
  598. // Render Dashboard View
  599. function renderDashboard() {
  600. const matrix = document.getElementById('port-matrix');
  601. if (!matrix) return;
  602. const ifaces = state.interfaces || [];
  603. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  604. if (matrix.dataset.sig === sig) {
  605. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  606. }
  607. matrix.dataset.sig = sig;
  608. matrix.innerHTML = '';
  609. (state.interfaces || []).forEach(iface => {
  610. const isUp = iface.state === 'UP';
  611. const isVlan = iface.is_vlan;
  612. const portCard = document.createElement('div');
  613. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  614. isUp
  615. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  616. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  617. }`;
  618. portCard.onclick = () => openIfaceModal(iface.name);
  619. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  620. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  621. portCard.innerHTML = `
  622. <div class="flex items-center justify-between mb-2">
  623. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  624. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  625. </div>
  626. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  627. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  628. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  629. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  630. </div>
  631. `;
  632. matrix.appendChild(portCard);
  633. });
  634. const ifaceTbody = document.getElementById('quick-interfaces-table');
  635. if (ifaceTbody) {
  636. ifaceTbody.innerHTML = '';
  637. (state.interfaces || []).forEach(i => {
  638. const isUp = i.state === 'UP';
  639. const tr = document.createElement('tr');
  640. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  641. tr.onclick = () => openIfaceModal(i.name);
  642. const rxStr = i.rate?.rx_human || '0 B/s';
  643. const txStr = i.rate?.tx_human || '0 B/s';
  644. tr.innerHTML = `
  645. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  646. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  647. <span>${i.name}</span>
  648. </td>
  649. <td class="py-2.5 text-slate-300 font-sans">
  650. ${getRoleBadge(i.role || 'LAN')}
  651. </td>
  652. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  653. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  654. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  655. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  656. </td>
  657. <td class="py-2.5 text-right font-sans font-semibold">
  658. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  659. </td>
  660. `;
  661. ifaceTbody.appendChild(tr);
  662. });
  663. }
  664. const vlanTbody = document.getElementById('quick-vlans-table');
  665. if (vlanTbody) {
  666. vlanTbody.innerHTML = '';
  667. }
  668. }
  669. // Expand / Collapse Handlers
  670. function toggleExpand(parentName) {
  671. if (state.expandedParents.has(parentName)) {
  672. state.expandedParents.delete(parentName);
  673. } else {
  674. state.expandedParents.add(parentName);
  675. }
  676. renderInterfacesList();
  677. }
  678. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  679. function supportsVLAN(iface) {
  680. if (!iface) return false;
  681. if (iface.is_vlan) return false;
  682. const name = (iface.name || '').toLowerCase();
  683. const type = (iface.type || '').toLowerCase();
  684. const role = (iface.role || '').toLowerCase();
  685. // Exclude loopback
  686. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  687. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  688. if (type === 'wireguard' || name.startsWith('wg')) return false;
  689. // Exclude PPP / PPPoE
  690. if (type === 'ppp' || name.startsWith('ppp')) return false;
  691. // Exclude other Layer 3 tunnels and dummy devices
  692. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  693. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  694. return false;
  695. }
  696. // If name already contains a dot, it's already a sub-interface
  697. if (name.includes('.')) return false;
  698. return true;
  699. }
  700. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  701. function supportsDHCPClient(iface) {
  702. if (!iface) return false;
  703. const name = (iface.name || '').toLowerCase();
  704. const type = (iface.type || '').toLowerCase();
  705. const role = (iface.role || '').toLowerCase();
  706. // Exclude loopback
  707. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  708. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  709. if (type === 'wireguard' || name.startsWith('wg')) return false;
  710. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  711. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  712. // Exclude other Layer 3 tunnels and dummy devices
  713. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  714. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  715. return false;
  716. }
  717. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  718. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  719. if (isBridgePort) return false;
  720. return true;
  721. }
  722. // Expand / Collapse Handlers
  723. function toggleExpand(parentName) {
  724. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  725. if (childVlans.length === 0) {
  726. // Cannot expand an interface with no VLANs
  727. state.expandedParents.delete(parentName);
  728. return;
  729. }
  730. if (state.expandedParents.has(parentName)) {
  731. state.expandedParents.delete(parentName);
  732. } else {
  733. state.expandedParents.add(parentName);
  734. }
  735. renderInterfacesList();
  736. }
  737. function expandAllIfaces(expand) {
  738. if (expand) {
  739. (state.interfaces || []).forEach(i => {
  740. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  741. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  742. });
  743. } else {
  744. state.expandedParents.clear();
  745. }
  746. renderInterfacesList();
  747. }
  748. // =========================================================================
  749. // INTERFACE ROLE TAGS MANAGEMENT
  750. // =========================================================================
  751. const ROLE_COLORS = {
  752. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  753. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  754. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  755. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  756. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  757. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  758. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  759. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  760. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  761. };
  762. function getRoleBadge(roleName) {
  763. const name = roleName || 'LAN';
  764. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  765. const colorKey = (role?.color || 'blue').toLowerCase();
  766. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  767. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  768. }
  769. function switchIfaceSubTab(subTab) {
  770. state.activeIfaceSubTab = subTab;
  771. const treeTab = document.getElementById('ifaces-subtab-tree');
  772. const rolesTab = document.getElementById('ifaces-subtab-roles');
  773. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  774. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  775. if (subTab === 'roles') {
  776. treeTab?.classList.add('hidden');
  777. rolesTab?.classList.remove('hidden');
  778. if (btnRoles) {
  779. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  780. }
  781. if (btnTree) {
  782. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  783. }
  784. loadRoles();
  785. } else {
  786. rolesTab?.classList.add('hidden');
  787. treeTab?.classList.remove('hidden');
  788. if (btnTree) {
  789. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  790. }
  791. if (btnRoles) {
  792. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  793. }
  794. renderInterfacesList();
  795. }
  796. }
  797. async function loadRoles() {
  798. try {
  799. const res = await fetch(`${API_BASE}/roles`);
  800. if (res.ok) {
  801. state.roles = await res.json();
  802. const countEl = document.getElementById('badge-roles-count');
  803. if (countEl) countEl.innerText = (state.roles || []).length;
  804. renderRolesTable();
  805. populateRoleSelects();
  806. }
  807. } catch (err) {
  808. console.error('Failed to load role tags:', err);
  809. }
  810. }
  811. function renderRolesTable() {
  812. const tbody = document.getElementById('roles-table-body');
  813. const empty = document.getElementById('roles-empty-state');
  814. if (!tbody) return;
  815. const roles = state.roles || [];
  816. if (roles.length === 0) {
  817. tbody.innerHTML = '';
  818. empty?.classList.remove('hidden');
  819. return;
  820. }
  821. empty?.classList.add('hidden');
  822. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  823. if (tbody.dataset.sig === sig) return;
  824. tbody.dataset.sig = sig;
  825. tbody.innerHTML = roles.map(r => {
  826. const colorKey = (r.color || 'blue').toLowerCase();
  827. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  828. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  829. const ifacesChips = ifaces.length > 0
  830. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  831. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  832. return `
  833. <tr class="hover:bg-slate-800/40 transition">
  834. <td class="py-3 px-4">
  835. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  836. ${escapeHtml(r.name)}
  837. </span>
  838. </td>
  839. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  840. <span>${escapeHtml(r.name)}</span>
  841. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  842. </td>
  843. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  844. <span class="inline-flex items-center gap-1.5">
  845. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  846. <span>${escapeHtml(r.color || 'blue')}</span>
  847. </span>
  848. </td>
  849. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  850. <td class="py-3 px-4 font-sans">
  851. <div class="flex flex-wrap items-center">
  852. ${ifacesChips}
  853. </div>
  854. </td>
  855. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  856. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  857. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  858. Edit
  859. </button>
  860. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  861. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  862. Delete
  863. </button>
  864. </td>
  865. </tr>
  866. `;
  867. }).join('');
  868. }
  869. function openRoleModal(id = null) {
  870. const modal = document.getElementById('role-modal');
  871. if (!modal) return;
  872. const idInput = document.getElementById('role-modal-id');
  873. const nameInput = document.getElementById('role-modal-name');
  874. const colorSelect = document.getElementById('role-modal-color');
  875. const descInput = document.getElementById('role-modal-desc');
  876. const title = document.getElementById('role-modal-title');
  877. if (id) {
  878. const role = (state.roles || []).find(r => r.id === id);
  879. if (role) {
  880. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  881. if (idInput) idInput.value = role.id;
  882. if (nameInput) nameInput.value = role.name;
  883. if (colorSelect) colorSelect.value = role.color || 'blue';
  884. if (descInput) descInput.value = role.description || '';
  885. }
  886. } else {
  887. if (title) title.innerText = 'Add Role Tag';
  888. if (idInput) idInput.value = '';
  889. if (nameInput) nameInput.value = '';
  890. if (colorSelect) colorSelect.value = 'blue';
  891. if (descInput) descInput.value = '';
  892. }
  893. updateRoleModalPreview();
  894. modal.classList.remove('hidden');
  895. }
  896. function closeRoleModal() {
  897. const modal = document.getElementById('role-modal');
  898. if (modal) modal.classList.add('hidden');
  899. }
  900. function updateRoleModalPreview() {
  901. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  902. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  903. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  904. const preview = document.getElementById('role-modal-preview');
  905. if (preview) {
  906. preview.innerText = name;
  907. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  908. }
  909. }
  910. async function submitSaveRole(e) {
  911. e.preventDefault();
  912. const id = document.getElementById('role-modal-id')?.value;
  913. const name = document.getElementById('role-modal-name')?.value.trim();
  914. const color = document.getElementById('role-modal-color')?.value;
  915. const desc = document.getElementById('role-modal-desc')?.value.trim();
  916. if (!name) return;
  917. try {
  918. const payload = { id, name, color, description: desc };
  919. const method = id ? 'PUT' : 'POST';
  920. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  921. const res = await fetch(url, {
  922. method,
  923. headers: { 'Content-Type': 'application/json' },
  924. body: JSON.stringify(payload)
  925. });
  926. if (res.ok) {
  927. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  928. closeRoleModal();
  929. await loadRoles();
  930. fetchData(false);
  931. } else {
  932. const err = await res.json();
  933. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  934. }
  935. } catch (err) {
  936. showToast('Error', err.message, 'error');
  937. }
  938. }
  939. async function deleteRoleTag(id, name) {
  940. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  941. try {
  942. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  943. method: 'DELETE'
  944. });
  945. if (res.ok) {
  946. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  947. await loadRoles();
  948. fetchData(false);
  949. } else {
  950. const err = await res.json();
  951. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  952. }
  953. } catch (err) {
  954. showToast('Error', err.message, 'error');
  955. }
  956. }
  957. function populateRoleSelects(selectedRole = '') {
  958. const ifaceSelect = document.getElementById('modal-iface-role');
  959. const vlanSelect = document.getElementById('vlan-role');
  960. const roles = state.roles || [];
  961. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  962. if (ifaceSelect) {
  963. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  964. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  965. ifaceSelect.innerHTML = optionsHtml;
  966. ifaceSelect.dataset.optionsSig = optionsHtml;
  967. }
  968. if (currentVal) ifaceSelect.value = currentVal;
  969. }
  970. if (vlanSelect) {
  971. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  972. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  973. vlanSelect.innerHTML = optionsHtml;
  974. vlanSelect.dataset.optionsSig = optionsHtml;
  975. }
  976. if (currentVal) vlanSelect.value = currentVal;
  977. }
  978. }
  979. // Filter and Render Hierarchical Interfaces List
  980. function filterIfaces(filter) {
  981. state.ifaceFilter = filter || 'all';
  982. renderInterfacesList();
  983. }
  984. function renderInterfacesList() {
  985. const tbody = document.getElementById('interfaces-tree-tbody');
  986. const emptyState = document.getElementById('interfaces-empty-state');
  987. const summary = document.getElementById('ifaces-list-summary');
  988. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  989. const allIfaces = state.interfaces || [];
  990. const allVlans = state.vlans || [];
  991. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  992. const filteredParents = parentIfaces.filter(parent => {
  993. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  994. if (query) {
  995. const matchName = parent.name.toLowerCase().includes(query);
  996. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  997. const matchRole = (parent.role || '').toLowerCase().includes(query);
  998. const matchType = (parent.type || '').toLowerCase().includes(query);
  999. const matchVlan = childVlans.some(v =>
  1000. v.name.toLowerCase().includes(query) ||
  1001. String(v.vlan_id).includes(query) ||
  1002. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1003. (v.description || '').toLowerCase().includes(query)
  1004. );
  1005. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1006. }
  1007. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1008. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1009. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1010. return true;
  1011. });
  1012. if (summary) {
  1013. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1014. }
  1015. if (filteredParents.length === 0) {
  1016. emptyState?.classList.remove('hidden');
  1017. tbody.innerHTML = '';
  1018. return;
  1019. }
  1020. emptyState?.classList.add('hidden');
  1021. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1022. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1023. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1024. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1025. }).join(';');
  1026. if (tbody.dataset.sig === sig) {
  1027. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1028. }
  1029. tbody.dataset.sig = sig;
  1030. tbody.innerHTML = '';
  1031. filteredParents.forEach(parent => {
  1032. const isUp = parent.state === 'UP';
  1033. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1034. const hasVlans = childVlans.length > 0;
  1035. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1036. const canHaveVlan = supportsVLAN(parent);
  1037. const parentRow = document.createElement('tr');
  1038. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1039. parentRow.innerHTML = `
  1040. <td class="py-3 px-3 text-center">
  1041. ${hasVlans ? `
  1042. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1043. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1044. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1045. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1046. </svg>
  1047. </button>
  1048. ` : `
  1049. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1050. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1051. </div>
  1052. `}
  1053. </td>
  1054. <td class="py-3 px-4">
  1055. <div class="flex items-center space-x-2.5">
  1056. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1057. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1058. </div>
  1059. <div>
  1060. <div class="flex items-center gap-2">
  1061. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1062. <span>${parent.name}</span>
  1063. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1064. </span>
  1065. ${hasVlans ? `
  1066. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1067. ` : `
  1068. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1069. `}
  1070. </div>
  1071. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1072. </div>
  1073. </div>
  1074. </td>
  1075. <td class="py-3 px-4 font-sans">
  1076. <div class="flex items-center gap-1.5">
  1077. ${getRoleBadge(parent.role || 'LAN')}
  1078. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1079. </div>
  1080. </td>
  1081. <td class="py-3 px-4">
  1082. ${parent.ipv4 && parent.ipv4.length > 0
  1083. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1084. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1085. }
  1086. ${(() => {
  1087. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1088. if (!c) return '';
  1089. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1090. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1091. })()}
  1092. </td>
  1093. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1094. <div>${parent.mac || 'N/A'}</div>
  1095. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1096. </td>
  1097. <td class="py-3 px-4 text-[11px]">
  1098. <div class="flex items-center space-x-2">
  1099. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1100. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1101. </div>
  1102. </td>
  1103. <td class="py-3 px-4 font-sans">
  1104. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1105. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1106. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1107. }" title="Click to toggle link status">
  1108. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1109. <span>${parent.state}</span>
  1110. </button>
  1111. </td>
  1112. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1113. ${(() => {
  1114. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1115. if (c) {
  1116. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1117. }
  1118. if (!supportsDHCPClient(parent)) {
  1119. return '';
  1120. }
  1121. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1122. })()}
  1123. ${canHaveVlan ? `
  1124. <button onclick="openVlanModal('${parent.name}')"
  1125. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1126. + Add VLAN
  1127. </button>
  1128. ` : ''}
  1129. <button onclick="openIfaceModal('${parent.name}')"
  1130. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1131. Edit
  1132. </button>
  1133. </td>
  1134. `;
  1135. tbody.appendChild(parentRow);
  1136. if (isExpanded) {
  1137. const drawerRow = document.createElement('tr');
  1138. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1139. const drawerCell = document.createElement('td');
  1140. drawerCell.colSpan = 8;
  1141. drawerCell.className = 'p-0';
  1142. drawerCell.innerHTML = `
  1143. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1144. <div class="flex items-center justify-between mb-3">
  1145. <div class="flex items-center space-x-3">
  1146. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1147. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1148. </span>
  1149. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1150. ${childVlans.length} Attached
  1151. </span>
  1152. </div>
  1153. <button onclick="openVlanModal('${parent.name}')"
  1154. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1155. <span>+ Create VLAN on ${parent.name}</span>
  1156. </button>
  1157. </div>
  1158. ${childVlans.length === 0 ? `
  1159. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1160. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1161. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1162. <span>+ Create Your First VLAN on ${parent.name}</span>
  1163. </button>
  1164. </div>
  1165. ` : `
  1166. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1167. <table class="w-full text-left text-xs font-mono">
  1168. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1169. <tr>
  1170. <th class="py-2.5 px-4">VLAN ID</th>
  1171. <th class="py-2.5 px-4">Interface Device</th>
  1172. <th class="py-2.5 px-4">Subnet Gateway</th>
  1173. <th class="py-2.5 px-4">Role / Alias</th>
  1174. <th class="py-2.5 px-4">MTU</th>
  1175. <th class="py-2.5 px-4">Throughput</th>
  1176. <th class="py-2.5 px-4">Status</th>
  1177. <th class="py-2.5 px-4 text-right">Actions</th>
  1178. </tr>
  1179. </thead>
  1180. <tbody class="divide-y divide-slate-800/70">
  1181. ${childVlans.map(v => {
  1182. const isVlanUp = v.state === 'UP';
  1183. return `
  1184. <tr class="hover:bg-slate-800/40 transition">
  1185. <td class="py-2.5 px-4">
  1186. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1187. VLAN ${v.vlan_id}
  1188. </span>
  1189. </td>
  1190. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1191. <span class="text-cyan-500">└─</span>
  1192. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1193. <span>${v.name}</span>
  1194. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1195. </span>
  1196. </td>
  1197. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1198. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1199. ${(() => {
  1200. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1201. if (!c) return '';
  1202. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1203. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1204. })()}
  1205. </td>
  1206. <td class="py-2.5 px-4 font-sans text-slate-300">
  1207. <div class="flex items-center gap-1.5">
  1208. ${getRoleBadge(v.role || 'LAN')}
  1209. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1210. </div>
  1211. </td>
  1212. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1213. <td class="py-2.5 px-4 text-[11px]">
  1214. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1215. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1216. </td>
  1217. <td class="py-2.5 px-4 font-sans">
  1218. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1219. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1220. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1221. }">
  1222. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1223. <span>${v.state}</span>
  1224. </button>
  1225. </td>
  1226. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1227. ${(() => {
  1228. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1229. if (c) {
  1230. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1231. }
  1232. if (!supportsDHCPClient(v)) {
  1233. return '';
  1234. }
  1235. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1236. })()}
  1237. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1238. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1239. </td>
  1240. </tr>
  1241. `;
  1242. }).join('')}
  1243. </tbody>
  1244. </table>
  1245. </div>
  1246. `}
  1247. </div>
  1248. `;
  1249. drawerRow.appendChild(drawerCell);
  1250. tbody.appendChild(drawerRow);
  1251. }
  1252. });
  1253. }
  1254. // Render VLANs Dedicated View
  1255. function renderVlansList() {
  1256. const tbody = document.getElementById('vlans-table-body');
  1257. if (!tbody) return;
  1258. const emptyState = document.getElementById('vlans-empty-state');
  1259. const countBadge = document.getElementById('vlans-table-count');
  1260. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1261. const allVlans = state.vlans || [];
  1262. if (countBadge) countBadge.innerText = allVlans.length;
  1263. const filtered = allVlans.filter(v => {
  1264. if (!query) return true;
  1265. return v.name.toLowerCase().includes(query) ||
  1266. String(v.vlan_id).includes(query) ||
  1267. (v.description || '').toLowerCase().includes(query) ||
  1268. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1269. });
  1270. if (allVlans.length === 0) {
  1271. emptyState.classList.remove('hidden');
  1272. tbody.innerHTML = '';
  1273. return;
  1274. }
  1275. emptyState.classList.add('hidden');
  1276. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1277. if (tbody.dataset.sig === sig) return;
  1278. tbody.dataset.sig = sig;
  1279. tbody.innerHTML = '';
  1280. filtered.forEach(v => {
  1281. const isUp = v.state === 'UP';
  1282. const tr = document.createElement('tr');
  1283. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1284. tr.innerHTML = `
  1285. <td class="py-3 px-4">
  1286. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1287. VLAN ${v.vlan_id}
  1288. </span>
  1289. </td>
  1290. <td class="py-3 px-4 font-bold text-white">
  1291. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1292. <span>${v.name}</span>
  1293. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1294. </span>
  1295. </td>
  1296. <td class="py-3 px-4 text-slate-300">
  1297. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1298. </td>
  1299. <td class="py-3 px-4 text-emerald-400 font-medium">
  1300. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1301. </td>
  1302. <td class="py-3 px-4 text-slate-300 font-sans">
  1303. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1304. </td>
  1305. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1306. <td class="py-3 px-4 font-sans">
  1307. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1308. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1309. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1310. }">
  1311. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1312. <span>${v.state}</span>
  1313. </button>
  1314. </td>
  1315. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1316. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1317. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1318. </td>
  1319. `;
  1320. tbody.appendChild(tr);
  1321. });
  1322. }
  1323. // Toggle interface UP / DOWN
  1324. async function toggleInterfaceState(name, newState) {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1327. method: 'POST',
  1328. headers: { 'Content-Type': 'application/json' },
  1329. body: JSON.stringify({ state: newState })
  1330. });
  1331. const data = await res.json();
  1332. if (res.ok) {
  1333. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1334. fetchData(false);
  1335. } else {
  1336. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1337. }
  1338. } catch (err) {
  1339. showToast('Error', err.message, 'error');
  1340. }
  1341. }
  1342. // ---------------- MikroTik Flag & Utilities ----------------
  1343. function renderMikroTikFlag(running, disabled) {
  1344. if (running) {
  1345. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1346. }
  1347. if (disabled) {
  1348. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1349. }
  1350. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1351. }
  1352. function copyToClipboard(text, label = 'Text') {
  1353. navigator.clipboard.writeText(text).then(() => {
  1354. showToast('Copied', `${label} copied to clipboard`, 'success');
  1355. }).catch(() => {
  1356. prompt('Copy value:', text);
  1357. });
  1358. }
  1359. // ======================== PPP Profiles Shared Helper ========================
  1360. async function fetchPPPProfilesList() {
  1361. try {
  1362. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1363. if (res.ok) {
  1364. state.pppProfiles = await res.json();
  1365. }
  1366. } catch (err) {
  1367. console.error('Failed to load PPP profiles:', err);
  1368. }
  1369. }
  1370. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1371. const sel = document.getElementById(selectId);
  1372. if (!sel) return;
  1373. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1374. { name: 'default', use_encryption: 'no' },
  1375. { name: 'default-encryption', use_encryption: 'required' }
  1376. ];
  1377. sel.innerHTML = '';
  1378. profiles.forEach(p => {
  1379. const opt = document.createElement('option');
  1380. opt.value = p.name;
  1381. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1382. opt.innerText = `${p.name}${encBadge}`;
  1383. sel.appendChild(opt);
  1384. });
  1385. if (selectedVal) {
  1386. sel.value = selectedVal;
  1387. } else {
  1388. sel.value = defaultVal;
  1389. }
  1390. if (!sel.value && sel.options.length > 0) {
  1391. sel.selectedIndex = 0;
  1392. }
  1393. }
  1394. // ======================== PPPoE Multi-Instance ========================
  1395. async function loadPPPoE(populateInputs = true) {
  1396. try {
  1397. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1398. await fetchPPPProfilesList();
  1399. }
  1400. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1401. const list = await res.json();
  1402. state.pppoeList = Array.isArray(list) ? list : [];
  1403. const badge = document.getElementById('pppoe-count-badge');
  1404. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1405. const tbody = document.getElementById('pppoe-table-body');
  1406. const empty = document.getElementById('pppoe-empty');
  1407. if (!tbody) return;
  1408. tbody.innerHTML = '';
  1409. if (state.pppoeList.length === 0) {
  1410. if (empty) empty.classList.remove('hidden');
  1411. } else {
  1412. if (empty) empty.classList.add('hidden');
  1413. state.pppoeList.forEach(inst => {
  1414. const tr = document.createElement('tr');
  1415. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1416. tr.innerHTML = `
  1417. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1418. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1419. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1420. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1421. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1422. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1423. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1424. <td class="py-2.5 px-3 text-center">
  1425. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1426. ${inst.default_route ? 'Yes' : 'No'}
  1427. </span>
  1428. </td>
  1429. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1430. ${inst.running ? `
  1431. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1432. ` : `
  1433. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1434. `}
  1435. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1436. ${inst.disabled ? 'Enable' : 'Disable'}
  1437. </button>
  1438. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1439. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1440. </td>
  1441. `;
  1442. tbody.appendChild(tr);
  1443. });
  1444. }
  1445. } catch (err) {
  1446. console.error('Failed to load PPPoE:', err);
  1447. }
  1448. }
  1449. function openAddPPPoEModal() {
  1450. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1451. document.getElementById('pppoe-modal-edit-orig').value = '';
  1452. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1453. document.getElementById('pppoe-modal-name').readOnly = false;
  1454. document.getElementById('pppoe-modal-user').value = '';
  1455. document.getElementById('pppoe-modal-pass').value = '';
  1456. document.getElementById('pppoe-modal-service').value = '';
  1457. document.getElementById('pppoe-modal-mtu').value = '1492';
  1458. document.getElementById('pppoe-modal-defroute').checked = true;
  1459. document.getElementById('pppoe-modal-reconnect').checked = true;
  1460. document.getElementById('pppoe-modal-disabled').checked = false;
  1461. // Populate profiles
  1462. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1463. // Populate interfaces
  1464. const sel = document.getElementById('pppoe-modal-iface');
  1465. sel.innerHTML = '';
  1466. (state.interfaces || []).forEach(i => {
  1467. if (i.name === 'lo') return;
  1468. const opt = document.createElement('option');
  1469. opt.value = i.name;
  1470. opt.innerText = `${i.name} (${i.role || i.type})`;
  1471. sel.appendChild(opt);
  1472. });
  1473. document.getElementById('pppoe-modal').classList.remove('hidden');
  1474. }
  1475. function openEditPPPoEModal(name) {
  1476. const inst = (state.pppoeList || []).find(i => i.name === name);
  1477. if (!inst) return;
  1478. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1479. document.getElementById('pppoe-modal-edit-orig').value = name;
  1480. document.getElementById('pppoe-modal-name').value = inst.name;
  1481. document.getElementById('pppoe-modal-name').readOnly = true;
  1482. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1483. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1484. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1485. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1486. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1487. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1488. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1489. // Populate profiles
  1490. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1491. const sel = document.getElementById('pppoe-modal-iface');
  1492. sel.innerHTML = '';
  1493. (state.interfaces || []).forEach(i => {
  1494. if (i.name === 'lo') return;
  1495. const opt = document.createElement('option');
  1496. opt.value = i.name;
  1497. opt.innerText = `${i.name} (${i.role || i.type})`;
  1498. if (i.name === inst.interface) opt.selected = true;
  1499. sel.appendChild(opt);
  1500. });
  1501. document.getElementById('pppoe-modal').classList.remove('hidden');
  1502. }
  1503. function closePPPoEModal() {
  1504. document.getElementById('pppoe-modal').classList.add('hidden');
  1505. }
  1506. async function submitSavePPPoE(e) {
  1507. e.preventDefault();
  1508. const name = document.getElementById('pppoe-modal-name').value.trim();
  1509. const iface = document.getElementById('pppoe-modal-iface').value;
  1510. const user = document.getElementById('pppoe-modal-user').value.trim();
  1511. const pass = document.getElementById('pppoe-modal-pass').value;
  1512. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1513. const service = document.getElementById('pppoe-modal-service').value.trim();
  1514. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1515. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1516. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1517. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1518. try {
  1519. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1520. method: 'POST',
  1521. headers: { 'Content-Type': 'application/json' },
  1522. body: JSON.stringify({
  1523. name,
  1524. interface: iface,
  1525. username: user,
  1526. password: pass,
  1527. profile: profile,
  1528. service_name: service,
  1529. mtu,
  1530. default_route: defRoute,
  1531. auto_reconnect: reconnect,
  1532. disabled
  1533. })
  1534. });
  1535. if (res.ok) {
  1536. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1537. closePPPoEModal();
  1538. loadPPPoE(false);
  1539. fetchData(false);
  1540. } else {
  1541. const err = await res.json();
  1542. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1543. }
  1544. } catch (err) {
  1545. showToast('Error', err.message, 'error');
  1546. }
  1547. }
  1548. async function connectPPPoEInstance(name) {
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1551. if (res.ok) {
  1552. showToast('Connecting', `Dialing ${name}...`, 'info');
  1553. setTimeout(() => loadPPPoE(false), 2000);
  1554. }
  1555. } catch (err) {
  1556. showToast('Error', err.message, 'error');
  1557. }
  1558. }
  1559. async function disconnectPPPoEInstance(name) {
  1560. try {
  1561. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1562. if (res.ok) {
  1563. showToast('Disconnected', `${name} session terminated`, 'info');
  1564. setTimeout(() => loadPPPoE(false), 1000);
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function togglePPPoEState(name, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ enabled: enable })
  1576. });
  1577. if (res.ok) {
  1578. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1579. loadPPPoE(false);
  1580. }
  1581. } catch (err) {
  1582. showToast('Error', err.message, 'error');
  1583. }
  1584. }
  1585. async function deletePPPoEInstance(name) {
  1586. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1587. try {
  1588. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1589. if (res.ok) {
  1590. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1591. loadPPPoE(false);
  1592. fetchData(false);
  1593. }
  1594. } catch (err) {
  1595. showToast('Error', err.message, 'error');
  1596. }
  1597. }
  1598. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1599. state.wgSubTab = 'ifaces';
  1600. function switchWGSubTab(tab) {
  1601. state.wgSubTab = tab;
  1602. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1603. const peersPanel = document.getElementById('wg-subtab-peers');
  1604. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1605. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1606. if (tab === 'ifaces') {
  1607. ifacesPanel?.classList.remove('hidden');
  1608. peersPanel?.classList.add('hidden');
  1609. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1610. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1611. } else {
  1612. ifacesPanel?.classList.add('hidden');
  1613. peersPanel?.classList.remove('hidden');
  1614. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1615. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1616. renderWGPeers();
  1617. }
  1618. }
  1619. async function loadWireGuard(populateInputs = true) {
  1620. try {
  1621. const [ifacesRes, peersRes] = await Promise.all([
  1622. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1623. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1624. ]);
  1625. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1626. const peers = peersRes.ok ? await peersRes.json() : [];
  1627. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1628. state.wgPeers = Array.isArray(peers) ? peers : [];
  1629. // Badges
  1630. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1631. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1632. const peersCountBadge = document.getElementById('wg-peers-count');
  1633. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1634. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1635. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1636. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1637. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1638. // Render Interfaces
  1639. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1640. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1641. if (ifacesTbody) {
  1642. ifacesTbody.innerHTML = '';
  1643. if (state.wgInterfaces.length === 0) {
  1644. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1645. } else {
  1646. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1647. state.wgInterfaces.forEach(iface => {
  1648. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1649. const tr = document.createElement('tr');
  1650. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1651. tr.innerHTML = `
  1652. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1653. <td class="py-2.5 px-3">
  1654. <div class="flex items-center gap-1.5">
  1655. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1656. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1657. </div>
  1658. </td>
  1659. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1660. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1661. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1662. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1663. ${(iface.public_key || '').substring(0, 10)}... 📋
  1664. </span>
  1665. </td>
  1666. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1667. <td class="py-2.5 px-3 text-center">
  1668. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1669. </td>
  1670. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1671. ${iface.running ? `
  1672. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1673. ` : `
  1674. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1675. `}
  1676. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1677. ${iface.disabled ? 'Enable' : 'Disable'}
  1678. </button>
  1679. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1680. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1681. </td>
  1682. `;
  1683. ifacesTbody.appendChild(tr);
  1684. });
  1685. }
  1686. }
  1687. // Populate filter dropdown in peers tab
  1688. const filterSel = document.getElementById('wg-peers-filter-iface');
  1689. if (filterSel) {
  1690. const currentVal = filterSel.value;
  1691. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1692. state.wgInterfaces.forEach(i => {
  1693. const opt = document.createElement('option');
  1694. opt.value = i.name;
  1695. opt.innerText = i.name;
  1696. if (i.name === currentVal) opt.selected = true;
  1697. filterSel.appendChild(opt);
  1698. });
  1699. }
  1700. renderWGPeers();
  1701. } catch (err) {
  1702. console.error('Failed to load WireGuard:', err);
  1703. }
  1704. }
  1705. function formatWGPeerEndpoint(address, port) {
  1706. if (!address || address === '(none)') return '--';
  1707. let addr = address.trim();
  1708. let p = port || 0;
  1709. while (addr.includes(':') && !addr.startsWith('[')) {
  1710. const lastColon = addr.lastIndexOf(':');
  1711. const maybePort = addr.substring(lastColon + 1);
  1712. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1713. if (!p) p = parseInt(maybePort, 10);
  1714. addr = addr.substring(0, lastColon);
  1715. } else {
  1716. break;
  1717. }
  1718. }
  1719. return p ? `${addr}:${p}` : addr;
  1720. }
  1721. function renderWGPeers() {
  1722. const filterSel = document.getElementById('wg-peers-filter-iface');
  1723. const selectedIface = filterSel ? filterSel.value : '';
  1724. const tbody = document.getElementById('wg-peers-table-body');
  1725. const empty = document.getElementById('wg-peers-empty');
  1726. if (!tbody) return;
  1727. tbody.innerHTML = '';
  1728. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1729. if (filtered.length === 0) {
  1730. if (empty) empty.classList.remove('hidden');
  1731. } else {
  1732. if (empty) empty.classList.add('hidden');
  1733. filtered.forEach(p => {
  1734. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1735. const tr = document.createElement('tr');
  1736. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1737. tr.innerHTML = `
  1738. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1739. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1740. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1741. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1742. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1743. ${(p.public_key || '').substring(0, 10)}... 📋
  1744. </span>
  1745. </td>
  1746. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1747. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1748. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1749. <td class="py-2.5 px-3 font-mono text-[11px]">
  1750. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1751. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1752. </td>
  1753. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1754. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1755. ${p.disabled ? 'Enable' : 'Disable'}
  1756. </button>
  1757. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1758. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1759. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1760. </td>
  1761. `;
  1762. tbody.appendChild(tr);
  1763. });
  1764. }
  1765. }
  1766. function openAddWGInterfaceModal() {
  1767. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1768. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1769. const nameEl = document.getElementById('wg-iface-modal-name');
  1770. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1771. nameEl.readOnly = false;
  1772. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1773. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1774. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1775. document.getElementById('wg-iface-modal-comment').value = '';
  1776. document.getElementById('wg-iface-modal-pubkey').value = '';
  1777. document.getElementById('wg-iface-modal-privkey').value = '';
  1778. document.getElementById('wg-iface-modal-disabled').checked = false;
  1779. generateWGInterfaceKeys();
  1780. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1781. }
  1782. function openEditWGInterfaceModal(name) {
  1783. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1784. if (!iface) return;
  1785. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1786. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1787. const nameEl = document.getElementById('wg-iface-modal-name');
  1788. nameEl.value = iface.name;
  1789. nameEl.readOnly = false; // ALLOW RENAMING
  1790. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1791. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1792. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1793. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1794. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1795. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1796. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1797. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1798. }
  1799. function closeAddWGInterfaceModal() {
  1800. document.getElementById('wg-iface-modal').classList.add('hidden');
  1801. }
  1802. async function generateWGInterfaceKeys() {
  1803. try {
  1804. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1805. const keys = await res.json();
  1806. if (res.ok) {
  1807. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1808. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1809. }
  1810. } catch (err) {
  1811. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1812. }
  1813. }
  1814. async function onWGInterfacePrivKeyInput() {
  1815. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1816. if (!privKey) return;
  1817. try {
  1818. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1819. method: 'POST',
  1820. headers: { 'Content-Type': 'application/json' },
  1821. body: JSON.stringify({ private_key: privKey })
  1822. });
  1823. if (res.ok) {
  1824. const data = await res.json();
  1825. if (data.public_key) {
  1826. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1827. }
  1828. }
  1829. } catch (err) {
  1830. // Ignore while typing
  1831. }
  1832. }
  1833. function toggleWGPrivKeyVisibility() {
  1834. const el = document.getElementById('wg-iface-modal-privkey');
  1835. const btn = document.getElementById('btn-toggle-wg-privkey');
  1836. if (el.type === 'password') {
  1837. el.type = 'text';
  1838. btn.innerText = '🙈 Hide';
  1839. } else {
  1840. el.type = 'password';
  1841. btn.innerText = '👁️ Show';
  1842. }
  1843. }
  1844. function copyWGInterfacePubKey() {
  1845. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1846. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1847. }
  1848. async function submitSaveWGInterface(e) {
  1849. e.preventDefault();
  1850. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1851. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1852. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1853. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1854. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1855. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1856. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1857. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1858. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1859. try {
  1860. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1861. method: 'POST',
  1862. headers: { 'Content-Type': 'application/json' },
  1863. body: JSON.stringify({
  1864. orig_name: origName,
  1865. name,
  1866. listen_port: port,
  1867. address: addr,
  1868. mtu,
  1869. comment,
  1870. public_key: pub,
  1871. private_key: priv,
  1872. disabled
  1873. })
  1874. });
  1875. const data = await res.json();
  1876. if (res.ok) {
  1877. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1878. closeAddWGInterfaceModal();
  1879. loadWireGuard(false);
  1880. fetchData(false);
  1881. } else {
  1882. showToast('Error', data.error || 'Failed to save interface', 'error');
  1883. }
  1884. } catch (err) {
  1885. showToast('Error', err.message, 'error');
  1886. }
  1887. }
  1888. async function startWGInterface(name) {
  1889. try {
  1890. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1891. if (res.ok) {
  1892. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1893. loadWireGuard(false);
  1894. fetchData(false);
  1895. }
  1896. } catch (err) {
  1897. showToast('Error', err.message, 'error');
  1898. }
  1899. }
  1900. async function stopWGInterface(name) {
  1901. try {
  1902. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1903. if (res.ok) {
  1904. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1905. loadWireGuard(false);
  1906. fetchData(false);
  1907. }
  1908. } catch (err) {
  1909. showToast('Error', err.message, 'error');
  1910. }
  1911. }
  1912. async function toggleWGInterfaceState(name, enable) {
  1913. try {
  1914. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1915. method: 'POST',
  1916. headers: { 'Content-Type': 'application/json' },
  1917. body: JSON.stringify({ enabled: enable })
  1918. });
  1919. if (res.ok) {
  1920. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1921. loadWireGuard(false);
  1922. fetchData(false);
  1923. }
  1924. } catch (err) {
  1925. showToast('Error', err.message, 'error');
  1926. }
  1927. }
  1928. async function deleteWGInterface(name) {
  1929. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1930. try {
  1931. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1932. if (res.ok) {
  1933. showToast('Deleted', `Interface ${name} removed`, 'success');
  1934. loadWireGuard(false);
  1935. fetchData(false);
  1936. }
  1937. } catch (err) {
  1938. showToast('Error', err.message, 'error');
  1939. }
  1940. }
  1941. function populateWGPeerIfaceSelect(selectedIface = '') {
  1942. const sel = document.getElementById('wg-peer-modal-iface');
  1943. if (!sel) return;
  1944. sel.innerHTML = '';
  1945. (state.wgInterfaces || []).forEach(i => {
  1946. const opt = document.createElement('option');
  1947. opt.value = i.name;
  1948. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1949. if (i.name === selectedIface) opt.selected = true;
  1950. sel.appendChild(opt);
  1951. });
  1952. }
  1953. function openAddWGPeerModal() {
  1954. if ((state.wgInterfaces || []).length === 0) {
  1955. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1956. openAddWGInterfaceModal();
  1957. return;
  1958. }
  1959. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1960. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1961. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1962. populateWGPeerIfaceSelect();
  1963. document.getElementById('wg-peer-modal-name').value = '';
  1964. document.getElementById('wg-peer-modal-pubkey').value = '';
  1965. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1966. document.getElementById('wg-peer-modal-endpoint').value = '';
  1967. document.getElementById('wg-peer-modal-port').value = '';
  1968. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1969. document.getElementById('wg-peer-modal-preshared').value = '';
  1970. document.getElementById('wg-peer-modal-disabled').checked = false;
  1971. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1972. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1973. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1974. }
  1975. function openEditWGPeerModal(ifaceName, pubKey) {
  1976. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1977. if (!peer) {
  1978. showToast('Not Found', 'Peer not found', 'warning');
  1979. return;
  1980. }
  1981. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1982. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1983. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1984. populateWGPeerIfaceSelect(peer.interface);
  1985. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1986. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1987. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1988. let epHost = (peer.endpoint_address || '').trim();
  1989. let epPort = peer.endpoint_port || '';
  1990. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1991. const lastColon = epHost.lastIndexOf(':');
  1992. const maybePort = epHost.substring(lastColon + 1);
  1993. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1994. if (!epPort) epPort = parseInt(maybePort, 10);
  1995. epHost = epHost.substring(0, lastColon);
  1996. } else {
  1997. break;
  1998. }
  1999. }
  2000. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2001. document.getElementById('wg-peer-modal-port').value = epPort;
  2002. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2003. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2004. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2005. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2006. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2007. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2008. }
  2009. function closeAddWGPeerModal() {
  2010. document.getElementById('wg-peer-modal').classList.add('hidden');
  2011. }
  2012. async function generatePeerKeypairHelper() {
  2013. try {
  2014. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2015. const keys = await res.json();
  2016. if (res.ok) {
  2017. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2018. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2019. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2020. checkWGPeerKeyValidity();
  2021. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2022. }
  2023. } catch (err) {
  2024. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2025. }
  2026. }
  2027. function copyGeneratedPeerPrivKey() {
  2028. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2029. if (priv) copyToClipboard(priv, 'Client Private Key');
  2030. }
  2031. async function generatePeerPSK() {
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2034. const keys = await res.json();
  2035. if (res.ok && keys.private_key) {
  2036. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2037. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2038. }
  2039. } catch (err) {
  2040. showToast('Error', err.message, 'error');
  2041. }
  2042. }
  2043. function checkWGPeerKeyValidity() {
  2044. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2045. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2046. const warningEl = document.getElementById('wg-peer-key-warning');
  2047. if (!warningEl) return;
  2048. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2049. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2050. warningEl.classList.remove('hidden');
  2051. } else {
  2052. warningEl.classList.add('hidden');
  2053. }
  2054. }
  2055. async function submitSaveWGPeer(e) {
  2056. e.preventDefault();
  2057. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2058. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2059. const iface = document.getElementById('wg-peer-modal-iface').value;
  2060. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2061. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2062. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2063. .split(',')
  2064. .map(s => s.trim())
  2065. .filter(s => s.length > 0);
  2066. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2067. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2068. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2069. const lastColon = epHost.lastIndexOf(':');
  2070. const maybePort = epHost.substring(lastColon + 1);
  2071. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2072. if (!epPort) epPort = parseInt(maybePort, 10);
  2073. epHost = epHost.substring(0, lastColon);
  2074. } else {
  2075. break;
  2076. }
  2077. }
  2078. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2079. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2080. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2081. // Validation
  2082. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2083. if (targetIface && targetIface.public_key === pub) {
  2084. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2085. return;
  2086. }
  2087. try {
  2088. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2089. method: 'POST',
  2090. headers: { 'Content-Type': 'application/json' },
  2091. body: JSON.stringify({
  2092. orig_interface: origIface,
  2093. orig_public_key: origPubKey,
  2094. interface: iface,
  2095. name,
  2096. public_key: pub,
  2097. allowed_ips: allowed,
  2098. endpoint_address: epHost,
  2099. endpoint_port: epPort,
  2100. persistent_keepalive: keepalive,
  2101. preshared_key: psk,
  2102. disabled
  2103. })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2108. closeAddWGPeerModal();
  2109. loadWireGuard(false);
  2110. } else {
  2111. showToast('Error', data.error || 'Failed to save peer', 'error');
  2112. }
  2113. } catch (err) {
  2114. showToast('Error', err.message, 'error');
  2115. }
  2116. }
  2117. async function toggleWGPeerState(iface, pubkey, enable) {
  2118. try {
  2119. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2120. method: 'POST',
  2121. headers: { 'Content-Type': 'application/json' },
  2122. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2123. });
  2124. const data = await res.json();
  2125. if (res.ok) {
  2126. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2127. loadWireGuard(false);
  2128. } else {
  2129. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2130. }
  2131. } catch (err) {
  2132. showToast('Error', err.message, 'error');
  2133. }
  2134. }
  2135. async function deleteWGPeer(iface, pubkey) {
  2136. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2137. try {
  2138. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2139. method: 'POST',
  2140. headers: { 'Content-Type': 'application/json' },
  2141. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2142. });
  2143. const data = await res.json();
  2144. if (res.ok) {
  2145. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2146. loadWireGuard(false);
  2147. } else {
  2148. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2149. }
  2150. } catch (err) {
  2151. showToast('Error', err.message, 'error');
  2152. }
  2153. }
  2154. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2155. function switchIpsecModalTab(tab) {
  2156. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2157. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2158. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2159. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2160. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2161. if (tab === 'p1') {
  2162. if (p1Tab) {
  2163. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2164. }
  2165. if (p2Tab) {
  2166. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2167. }
  2168. if (p1Content) p1Content.classList.remove('hidden');
  2169. if (p2Content) p2Content.classList.add('hidden');
  2170. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2171. } else {
  2172. if (p1Tab) {
  2173. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2174. }
  2175. if (p2Tab) {
  2176. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2177. }
  2178. if (p1Content) p1Content.classList.add('hidden');
  2179. if (p2Content) p2Content.classList.remove('hidden');
  2180. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2181. }
  2182. }
  2183. function toggleIpsecPhaseStep() {
  2184. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2185. if (p1Content && !p1Content.classList.contains('hidden')) {
  2186. switchIpsecModalTab('p2');
  2187. } else {
  2188. switchIpsecModalTab('p1');
  2189. }
  2190. }
  2191. function toggleIpsecPskVisibility() {
  2192. const pskInput = document.getElementById('ipsec-modal-psk');
  2193. if (!pskInput) return;
  2194. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2195. }
  2196. function addIpsecLocalSubnet(val = '') {
  2197. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2198. if (!container) return;
  2199. const row = document.createElement('div');
  2200. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2201. row.innerHTML = `
  2202. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2203. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2204. `;
  2205. container.appendChild(row);
  2206. }
  2207. function addIpsecRemoteSubnet(val = '') {
  2208. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2209. if (!container) return;
  2210. const row = document.createElement('div');
  2211. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2212. row.innerHTML = `
  2213. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2214. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2215. `;
  2216. container.appendChild(row);
  2217. }
  2218. function updateIpsecEspProposalFromPFS(val) {
  2219. const prop = document.getElementById('ipsec-modal-espprop');
  2220. if (!prop) return;
  2221. if (val === 'none') {
  2222. prop.value = 'aes256-sha256,aes128-sha256,default';
  2223. } else {
  2224. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2225. }
  2226. }
  2227. function updateIpsecIkeProposalFromDH(dh) {
  2228. const el = document.getElementById('ipsec-modal-ikeprop');
  2229. if (el) {
  2230. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2231. }
  2232. }
  2233. function safeSetVal(id, val) {
  2234. const el = document.getElementById(id);
  2235. if (el) el.value = val;
  2236. }
  2237. function safeSetChecked(id, val) {
  2238. const el = document.getElementById(id);
  2239. if (el) el.checked = !!val;
  2240. }
  2241. function safeGetVal(id, def = '') {
  2242. const el = document.getElementById(id);
  2243. return el ? el.value : def;
  2244. }
  2245. async function loadIPSec(populateInputs = true) {
  2246. try {
  2247. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2248. const list = await res.json();
  2249. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2250. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2251. const badge = document.getElementById('ipsec-sas-badge');
  2252. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2253. const tbody = document.getElementById('ipsec-table-body');
  2254. const empty = document.getElementById('ipsec-empty');
  2255. if (!tbody) return;
  2256. tbody.innerHTML = '';
  2257. if (state.ipsecTunnels.length === 0) {
  2258. if (empty) empty.classList.remove('hidden');
  2259. } else {
  2260. if (empty) empty.classList.add('hidden');
  2261. state.ipsecTunnels.forEach(c => {
  2262. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2263. const tr = document.createElement('tr');
  2264. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2265. // Local subnets tags
  2266. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2267. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2268. // Remote subnets tags
  2269. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2270. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2271. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2272. const p2Name = c.phase2_name || `${c.name}_p2`;
  2273. tr.innerHTML = `
  2274. <td class="py-2.5 px-3 text-center">
  2275. ${isEstablished ? `
  2276. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2277. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2278. <span>UP</span>
  2279. </span>
  2280. ` : (c.disabled ? `
  2281. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2282. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2283. <span>DOWN</span>
  2284. </span>
  2285. ` : `
  2286. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2287. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2288. <span>IDLE</span>
  2289. </span>
  2290. `)}
  2291. </td>
  2292. <td class="py-2.5 px-4 font-bold text-white">
  2293. <div class="flex items-center gap-2">
  2294. <span class="text-amber-400">🛡</span>
  2295. <div>
  2296. <div>${escapeHtml(c.name)}</div>
  2297. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2298. </div>
  2299. </div>
  2300. </td>
  2301. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2302. <td class="py-2.5 px-4 font-sans">
  2303. <div class="flex items-center gap-1.5">
  2304. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2305. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2306. </div>
  2307. </td>
  2308. <td class="py-2.5 px-4">
  2309. <div class="space-y-1">
  2310. <div class="flex items-center flex-wrap gap-1">
  2311. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2312. ${localBadges}
  2313. </div>
  2314. <div class="flex items-center flex-wrap gap-1">
  2315. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2316. ${remoteBadges}
  2317. </div>
  2318. </div>
  2319. </td>
  2320. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2321. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2322. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2323. </div>
  2324. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2325. </td>
  2326. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2327. ${isEstablished ? `
  2328. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2329. ` : `
  2330. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2331. `}
  2332. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2333. ${c.disabled ? 'Enable' : 'Disable'}
  2334. </button>
  2335. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2336. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2337. </td>
  2338. `;
  2339. tbody.appendChild(tr);
  2340. });
  2341. }
  2342. } catch (err) {
  2343. console.error('Failed to load IPSec:', err);
  2344. }
  2345. }
  2346. function openAddIPSecModal() {
  2347. const modal = document.getElementById('ipsec-modal');
  2348. if (!modal) return;
  2349. const title = document.getElementById('ipsec-modal-title');
  2350. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2351. // Phase 1 Fields
  2352. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2353. const nameEl = document.getElementById('ipsec-modal-name');
  2354. if (nameEl) nameEl.readOnly = false;
  2355. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2356. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2357. safeSetVal('ipsec-modal-remotegw', '');
  2358. safeSetVal('ipsec-modal-localaddrs', '');
  2359. safeSetVal('ipsec-modal-comments', '');
  2360. safeSetVal('ipsec-modal-psk', '');
  2361. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2362. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2363. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2364. safeSetVal('ipsec-modal-localid', '');
  2365. safeSetVal('ipsec-modal-remoteid', '');
  2366. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2367. // Phase 2 Fields
  2368. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2369. safeSetVal('ipsec-modal-espkeylife', '28800');
  2370. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2371. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2372. safeSetChecked('ipsec-modal-autostart', true);
  2373. safeSetChecked('ipsec-modal-disabled', false);
  2374. // Clear & Populate default dynamic subnets
  2375. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2376. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2377. if (localContainer) {
  2378. localContainer.innerHTML = '';
  2379. addIpsecLocalSubnet('192.168.10.0/24');
  2380. }
  2381. if (remoteContainer) {
  2382. remoteContainer.innerHTML = '';
  2383. addIpsecRemoteSubnet('192.168.20.0/24');
  2384. }
  2385. switchIpsecModalTab('p1');
  2386. modal.classList.remove('hidden');
  2387. }
  2388. function openEditIPSecModal(name) {
  2389. const modal = document.getElementById('ipsec-modal');
  2390. if (!modal) return;
  2391. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2392. if (!conn) return;
  2393. const title = document.getElementById('ipsec-modal-title');
  2394. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2395. // Phase 1 Fields
  2396. safeSetVal('ipsec-modal-name', conn.name);
  2397. const nameEl = document.getElementById('ipsec-modal-name');
  2398. if (nameEl) nameEl.readOnly = true;
  2399. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2400. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2401. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2402. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2403. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2404. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2405. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2406. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2407. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2408. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2409. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2410. // Phase 2 Fields
  2411. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2412. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2413. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2414. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2415. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2416. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2417. // Populate dynamic subnets
  2418. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2419. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2420. if (localContainer) {
  2421. localContainer.innerHTML = '';
  2422. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2423. locals.forEach(s => addIpsecLocalSubnet(s));
  2424. }
  2425. if (remoteContainer) {
  2426. remoteContainer.innerHTML = '';
  2427. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2428. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2429. }
  2430. switchIpsecModalTab('p1');
  2431. modal.classList.remove('hidden');
  2432. }
  2433. function closeAddIPSecModal() {
  2434. const modal = document.getElementById('ipsec-modal');
  2435. if (modal) modal.classList.add('hidden');
  2436. }
  2437. async function submitSaveIPSec(e) {
  2438. if (e) e.preventDefault();
  2439. const name = safeGetVal('ipsec-modal-name').trim();
  2440. if (!name) {
  2441. showToast('Error', 'Tunnel name is required', 'error');
  2442. return;
  2443. }
  2444. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2445. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2446. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2447. const comments = safeGetVal('ipsec-modal-comments').trim();
  2448. const psk = safeGetVal('ipsec-modal-psk');
  2449. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2450. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2451. const localId = safeGetVal('ipsec-modal-localid').trim();
  2452. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2453. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2454. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2455. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2456. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2457. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2458. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2459. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2460. // Scrape dynamic local and remote subnets
  2461. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2462. const localSubnets = [];
  2463. localInputs.forEach(inp => {
  2464. const v = inp.value.trim();
  2465. if (v) localSubnets.push(v);
  2466. });
  2467. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2468. const remoteSubnets = [];
  2469. remoteInputs.forEach(inp => {
  2470. const v = inp.value.trim();
  2471. if (v) remoteSubnets.push(v);
  2472. });
  2473. try {
  2474. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2475. method: 'POST',
  2476. headers: { 'Content-Type': 'application/json' },
  2477. body: JSON.stringify({
  2478. name,
  2479. comment: comments,
  2480. ike_version: ikeVersion,
  2481. local_addrs: localAddrs,
  2482. remote_addrs: remotegw,
  2483. preshared_key: psk,
  2484. ike_proposals: ikeProposals,
  2485. ike_keylife: ikeKeylife,
  2486. local_id: localId,
  2487. remote_id: remoteId,
  2488. dpd: dpd,
  2489. phase2_name: phase2Name,
  2490. esp_proposals: espProposals,
  2491. esp_keylife: espKeylife,
  2492. pfs_group: pfsGroup,
  2493. pfs: pfsGroup !== 'none',
  2494. local_subnets: localSubnets,
  2495. remote_subnets: remoteSubnets,
  2496. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2497. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2498. auto_start: autostart,
  2499. disabled
  2500. })
  2501. });
  2502. if (res.ok) {
  2503. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2504. closeAddIPSecModal();
  2505. loadIPSec(false);
  2506. } else {
  2507. const err = await res.json();
  2508. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2509. }
  2510. } catch (err) {
  2511. showToast('Error', err.message, 'error');
  2512. }
  2513. }
  2514. async function startIPSecTunnel(name) {
  2515. try {
  2516. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2517. if (res.ok) {
  2518. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2519. setTimeout(() => loadIPSec(false), 2000);
  2520. }
  2521. } catch (err) {
  2522. showToast('Error', err.message, 'error');
  2523. }
  2524. }
  2525. async function stopIPSecTunnel(name) {
  2526. try {
  2527. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2528. if (res.ok) {
  2529. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2530. loadIPSec(false);
  2531. }
  2532. } catch (err) {
  2533. showToast('Error', err.message, 'error');
  2534. }
  2535. }
  2536. async function toggleIPSecState(name, enable) {
  2537. try {
  2538. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2539. method: 'POST',
  2540. headers: { 'Content-Type': 'application/json' },
  2541. body: JSON.stringify({ enabled: enable })
  2542. });
  2543. if (res.ok) {
  2544. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2545. loadIPSec(false);
  2546. }
  2547. } catch (err) {
  2548. showToast('Error', err.message, 'error');
  2549. }
  2550. }
  2551. async function deleteIPSecConn(name) {
  2552. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2553. try {
  2554. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2555. if (res.ok) {
  2556. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2557. loadIPSec(false);
  2558. fetchData(false);
  2559. }
  2560. } catch (err) {
  2561. showToast('Error', err.message, 'error');
  2562. }
  2563. }
  2564. // ======================== L2TP Multi-Instance ========================
  2565. async function loadL2TP(populateInputs = true) {
  2566. try {
  2567. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2568. await fetchPPPProfilesList();
  2569. }
  2570. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2571. const list = await res.json();
  2572. state.l2tpList = Array.isArray(list) ? list : [];
  2573. const badge = document.getElementById('l2tp-count-badge');
  2574. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2575. const tbody = document.getElementById('l2tp-table-body');
  2576. const empty = document.getElementById('l2tp-empty');
  2577. if (!tbody) return;
  2578. tbody.innerHTML = '';
  2579. if (state.l2tpList.length === 0) {
  2580. if (empty) empty.classList.remove('hidden');
  2581. } else {
  2582. if (empty) empty.classList.add('hidden');
  2583. state.l2tpList.forEach(inst => {
  2584. const tr = document.createElement('tr');
  2585. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2586. tr.innerHTML = `
  2587. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2588. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2589. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2590. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2591. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2592. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2593. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2594. <td class="py-2.5 px-3 text-center">
  2595. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2596. ${inst.default_route ? 'Yes' : 'No'}
  2597. </span>
  2598. </td>
  2599. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2600. ${inst.running ? `
  2601. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2602. ` : `
  2603. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2604. `}
  2605. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2606. ${inst.disabled ? 'Enable' : 'Disable'}
  2607. </button>
  2608. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2609. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2610. </td>
  2611. `;
  2612. tbody.appendChild(tr);
  2613. });
  2614. }
  2615. } catch (err) {
  2616. console.error('Failed to load L2TP:', err);
  2617. }
  2618. }
  2619. async function openAddL2TPModal() {
  2620. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2621. await fetchPPPProfilesList();
  2622. }
  2623. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2624. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2625. document.getElementById('l2tp-modal-name').readOnly = false;
  2626. document.getElementById('l2tp-modal-server').value = '';
  2627. document.getElementById('l2tp-modal-user').value = '';
  2628. document.getElementById('l2tp-modal-pass').value = '';
  2629. document.getElementById('l2tp-modal-ipsec').value = '';
  2630. document.getElementById('l2tp-modal-defroute').checked = true;
  2631. document.getElementById('l2tp-modal-disabled').checked = false;
  2632. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2633. document.getElementById('l2tp-modal').classList.remove('hidden');
  2634. }
  2635. async function openEditL2TPModal(name) {
  2636. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2637. await fetchPPPProfilesList();
  2638. }
  2639. const inst = (state.l2tpList || []).find(i => i.name === name);
  2640. if (!inst) return;
  2641. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2642. document.getElementById('l2tp-modal-name').value = inst.name;
  2643. document.getElementById('l2tp-modal-name').readOnly = true;
  2644. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2645. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2646. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2647. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2648. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2649. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2650. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2651. document.getElementById('l2tp-modal').classList.remove('hidden');
  2652. }
  2653. function closeL2TPModal() {
  2654. document.getElementById('l2tp-modal').classList.add('hidden');
  2655. }
  2656. async function submitSaveL2TP(e) {
  2657. e.preventDefault();
  2658. const name = document.getElementById('l2tp-modal-name').value.trim();
  2659. const server = document.getElementById('l2tp-modal-server').value.trim();
  2660. const user = document.getElementById('l2tp-modal-user').value.trim();
  2661. const pass = document.getElementById('l2tp-modal-pass').value;
  2662. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2663. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2664. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2665. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2666. try {
  2667. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2668. method: 'POST',
  2669. headers: { 'Content-Type': 'application/json' },
  2670. body: JSON.stringify({
  2671. name,
  2672. connect_to: server,
  2673. username: user,
  2674. password: pass,
  2675. profile: profile,
  2676. ipsec_secret: ipsec,
  2677. default_route: defRoute,
  2678. disabled
  2679. })
  2680. });
  2681. if (res.ok) {
  2682. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2683. closeL2TPModal();
  2684. loadL2TP(false);
  2685. fetchData(false);
  2686. }
  2687. } catch (err) {
  2688. showToast('Error', err.message, 'error');
  2689. }
  2690. }
  2691. async function connectL2TPInstance(name) {
  2692. try {
  2693. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2694. if (res.ok) {
  2695. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2696. setTimeout(() => loadL2TP(false), 2000);
  2697. }
  2698. } catch (err) {
  2699. showToast('Error', err.message, 'error');
  2700. }
  2701. }
  2702. async function disconnectL2TPInstance(name) {
  2703. try {
  2704. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2705. if (res.ok) {
  2706. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2707. loadL2TP(false);
  2708. }
  2709. } catch (err) {
  2710. showToast('Error', err.message, 'error');
  2711. }
  2712. }
  2713. async function toggleL2TPState(name, enable) {
  2714. try {
  2715. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2716. method: 'POST',
  2717. headers: { 'Content-Type': 'application/json' },
  2718. body: JSON.stringify({ enabled: enable })
  2719. });
  2720. if (res.ok) {
  2721. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2722. loadL2TP(false);
  2723. }
  2724. } catch (err) {
  2725. showToast('Error', err.message, 'error');
  2726. }
  2727. }
  2728. async function deleteL2TPInstance(name) {
  2729. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2730. try {
  2731. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2732. if (res.ok) {
  2733. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2734. loadL2TP(false);
  2735. fetchData(false);
  2736. }
  2737. } catch (err) {
  2738. showToast('Error', err.message, 'error');
  2739. }
  2740. }
  2741. // ======================== PPTP Multi-Instance ========================
  2742. async function loadPPTP(populateInputs = true) {
  2743. try {
  2744. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2745. await fetchPPPProfilesList();
  2746. }
  2747. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2748. const list = await res.json();
  2749. state.pptpList = Array.isArray(list) ? list : [];
  2750. const badge = document.getElementById('pptp-count-badge');
  2751. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2752. const tbody = document.getElementById('pptp-table-body');
  2753. const empty = document.getElementById('pptp-empty');
  2754. if (!tbody) return;
  2755. tbody.innerHTML = '';
  2756. if (state.pptpList.length === 0) {
  2757. if (empty) empty.classList.remove('hidden');
  2758. } else {
  2759. if (empty) empty.classList.add('hidden');
  2760. state.pptpList.forEach(inst => {
  2761. const tr = document.createElement('tr');
  2762. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2763. tr.innerHTML = `
  2764. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2765. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2766. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2767. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2768. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2769. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2770. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2771. <td class="py-2.5 px-3 text-center">
  2772. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2773. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2774. </span>
  2775. </td>
  2776. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2777. ${inst.running ? `
  2778. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2779. ` : `
  2780. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2781. `}
  2782. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2783. ${inst.disabled ? 'Enable' : 'Disable'}
  2784. </button>
  2785. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2786. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2787. </td>
  2788. `;
  2789. tbody.appendChild(tr);
  2790. });
  2791. }
  2792. } catch (err) {
  2793. console.error('Failed to load PPTP:', err);
  2794. }
  2795. }
  2796. async function openAddPPTPModal() {
  2797. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2798. await fetchPPPProfilesList();
  2799. }
  2800. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2801. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2802. document.getElementById('pptp-modal-name').readOnly = false;
  2803. document.getElementById('pptp-modal-server').value = '';
  2804. document.getElementById('pptp-modal-user').value = '';
  2805. document.getElementById('pptp-modal-pass').value = '';
  2806. document.getElementById('pptp-modal-mppe').checked = true;
  2807. document.getElementById('pptp-modal-defroute').checked = true;
  2808. document.getElementById('pptp-modal-disabled').checked = false;
  2809. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2810. document.getElementById('pptp-modal').classList.remove('hidden');
  2811. }
  2812. async function openEditPPTPModal(name) {
  2813. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2814. await fetchPPPProfilesList();
  2815. }
  2816. const inst = (state.pptpList || []).find(i => i.name === name);
  2817. if (!inst) return;
  2818. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2819. document.getElementById('pptp-modal-name').value = inst.name;
  2820. document.getElementById('pptp-modal-name').readOnly = true;
  2821. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2822. document.getElementById('pptp-modal-user').value = inst.username || '';
  2823. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2824. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2825. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2826. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2827. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2828. document.getElementById('pptp-modal').classList.remove('hidden');
  2829. }
  2830. function closePPTPModal() {
  2831. document.getElementById('pptp-modal').classList.add('hidden');
  2832. }
  2833. async function submitSavePPTP(e) {
  2834. e.preventDefault();
  2835. const name = document.getElementById('pptp-modal-name').value.trim();
  2836. const server = document.getElementById('pptp-modal-server').value.trim();
  2837. const user = document.getElementById('pptp-modal-user').value.trim();
  2838. const pass = document.getElementById('pptp-modal-pass').value;
  2839. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2840. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2841. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2842. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2843. try {
  2844. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2845. method: 'POST',
  2846. headers: { 'Content-Type': 'application/json' },
  2847. body: JSON.stringify({
  2848. name,
  2849. connect_to: server,
  2850. username: user,
  2851. password: pass,
  2852. profile: profile,
  2853. require_mppe: mppe,
  2854. default_route: defRoute,
  2855. auto_reconnect: true,
  2856. disabled
  2857. })
  2858. });
  2859. if (res.ok) {
  2860. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2861. closePPTPModal();
  2862. loadPPTP(false);
  2863. fetchData(false);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function connectPPTPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2874. setTimeout(() => loadPPTP(false), 2000);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function disconnectPPTPInstance(name) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2883. if (res.ok) {
  2884. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2885. loadPPTP(false);
  2886. }
  2887. } catch (err) {
  2888. showToast('Error', err.message, 'error');
  2889. }
  2890. }
  2891. async function togglePPTPState(name, enable) {
  2892. try {
  2893. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2894. method: 'POST',
  2895. headers: { 'Content-Type': 'application/json' },
  2896. body: JSON.stringify({ enabled: enable })
  2897. });
  2898. if (res.ok) {
  2899. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2900. loadPPTP(false);
  2901. }
  2902. } catch (err) {
  2903. showToast('Error', err.message, 'error');
  2904. }
  2905. }
  2906. async function deletePPTPInstance(name) {
  2907. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2908. try {
  2909. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2910. if (res.ok) {
  2911. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2912. loadPPTP(false);
  2913. fetchData(false);
  2914. }
  2915. } catch (err) {
  2916. showToast('Error', err.message, 'error');
  2917. }
  2918. }
  2919. // ---------------- Modal & Helper Functions ----------------
  2920. function openVlanModal(defaultParent = '') {
  2921. const select = document.getElementById('vlan-parent');
  2922. select.innerHTML = '';
  2923. const allIfaces = state.interfaces || [];
  2924. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2925. if (eligible.length === 0) {
  2926. const opt = document.createElement('option');
  2927. opt.value = '';
  2928. opt.innerText = 'No VLAN-capable interfaces available';
  2929. select.appendChild(opt);
  2930. } else {
  2931. eligible.forEach(i => {
  2932. const opt = document.createElement('option');
  2933. opt.value = i.name;
  2934. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2935. if (i.name === defaultParent) opt.selected = true;
  2936. select.appendChild(opt);
  2937. });
  2938. }
  2939. document.getElementById('vlan-id').value = '';
  2940. document.getElementById('vlan-name').value = '';
  2941. document.getElementById('vlan-ip').value = '';
  2942. document.getElementById('vlan-desc').value = '';
  2943. populateRoleSelects('LAN');
  2944. autoSuggestVlanName();
  2945. document.getElementById('vlan-modal').classList.remove('hidden');
  2946. }
  2947. function closeVlanModal() {
  2948. document.getElementById('vlan-modal').classList.add('hidden');
  2949. }
  2950. function autoSuggestVlanName() {
  2951. const parent = document.getElementById('vlan-parent').value;
  2952. if (!parent) return;
  2953. const id = document.getElementById('vlan-id').value;
  2954. const nameInput = document.getElementById('vlan-name');
  2955. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2956. }
  2957. function setSubnetPreset(cidr) {
  2958. const ipInput = document.getElementById('vlan-ip');
  2959. const id = document.getElementById('vlan-id').value || '10';
  2960. ipInput.value = `192.168.${id}.1${cidr}`;
  2961. }
  2962. async function submitCreateVlan(e) {
  2963. e.preventDefault();
  2964. const btn = document.getElementById('vlan-submit-btn');
  2965. btn.disabled = true;
  2966. btn.innerText = 'Creating...';
  2967. const parent = document.getElementById('vlan-parent').value;
  2968. if (!parent) {
  2969. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2970. btn.disabled = false;
  2971. btn.innerText = 'Create VLAN';
  2972. return;
  2973. }
  2974. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2975. const name = document.getElementById('vlan-name').value.trim();
  2976. const ip = document.getElementById('vlan-ip').value.trim();
  2977. const role = document.getElementById('vlan-role').value;
  2978. const desc = document.getElementById('vlan-desc').value.trim();
  2979. try {
  2980. const res = await fetch(`${API_BASE}/vlans`, {
  2981. method: 'POST',
  2982. headers: { 'Content-Type': 'application/json' },
  2983. body: JSON.stringify({
  2984. parent_name: parent,
  2985. vlan_id: id,
  2986. name: name,
  2987. ip_address: ip,
  2988. role: role,
  2989. description: desc,
  2990. mtu: 1500,
  2991. auto_up: true
  2992. })
  2993. });
  2994. const data = await res.json();
  2995. if (res.ok) {
  2996. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2997. state.expandedParents.add(parent);
  2998. closeVlanModal();
  2999. await fetchData(true);
  3000. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3001. } else {
  3002. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3003. }
  3004. } catch (err) {
  3005. showToast('Error', err.message, 'error');
  3006. } finally {
  3007. btn.disabled = false;
  3008. btn.innerText = 'Create VLAN';
  3009. }
  3010. }
  3011. async function confirmDeleteVlan(name) {
  3012. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3013. try {
  3014. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3015. if (res.ok) {
  3016. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3017. closeIfaceModal();
  3018. fetchData(true);
  3019. }
  3020. } catch (err) {
  3021. showToast('Error', err.message, 'error');
  3022. }
  3023. }
  3024. function openIfaceModal(name) {
  3025. const iface = (state.interfaces || []).find(i => i.name === name);
  3026. if (!iface) return;
  3027. state.currentModalIface = iface.name;
  3028. document.getElementById('modal-iface-name').innerText = iface.name;
  3029. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3030. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3031. populateRoleSelects(iface.role || 'LAN');
  3032. document.getElementById('modal-iface-desc').value = iface.description || '';
  3033. const nameInput = document.getElementById('modal-iface-new-name');
  3034. const renameBtn = document.getElementById('modal-btn-rename');
  3035. const renameHelp = document.getElementById('modal-iface-rename-help');
  3036. if (nameInput) {
  3037. nameInput.value = iface.name;
  3038. if (iface.name === 'lo' || iface.type === 'loopback') {
  3039. nameInput.disabled = true;
  3040. if (renameBtn) renameBtn.disabled = true;
  3041. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3042. } else {
  3043. nameInput.disabled = false;
  3044. if (renameBtn) renameBtn.disabled = false;
  3045. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3046. }
  3047. }
  3048. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3049. if (iface.is_vlan) {
  3050. delBtn.classList.remove('hidden');
  3051. } else {
  3052. delBtn.classList.add('hidden');
  3053. }
  3054. renderModalIPs(iface);
  3055. document.getElementById('iface-modal').classList.remove('hidden');
  3056. }
  3057. function renderModalIPs(iface) {
  3058. const container = document.getElementById('modal-ip-list');
  3059. container.innerHTML = '';
  3060. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3061. if (addrs.length === 0) {
  3062. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3063. return;
  3064. }
  3065. addrs.forEach(addr => {
  3066. const row = document.createElement('div');
  3067. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3068. row.innerHTML = `
  3069. <span class="text-white">${addr}</span>
  3070. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3071. `;
  3072. container.appendChild(row);
  3073. });
  3074. }
  3075. function closeIfaceModal() {
  3076. document.getElementById('iface-modal').classList.add('hidden');
  3077. state.currentModalIface = null;
  3078. }
  3079. async function setIfaceState(name, newState) {
  3080. const target = name || state.currentModalIface;
  3081. if (!target) return;
  3082. await toggleInterfaceState(target, newState);
  3083. const updated = (state.interfaces || []).find(i => i.name === target);
  3084. if (updated) openIfaceModal(target);
  3085. }
  3086. async function applyMTU() {
  3087. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3088. try {
  3089. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3090. method: 'POST',
  3091. headers: { 'Content-Type': 'application/json' },
  3092. body: JSON.stringify({ mtu })
  3093. });
  3094. if (res.ok) {
  3095. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3096. fetchData(false);
  3097. }
  3098. } catch (err) {
  3099. showToast('Error', err.message, 'error');
  3100. }
  3101. }
  3102. async function addInterfaceIP() {
  3103. const ip = document.getElementById('modal-new-ip').value.trim();
  3104. if (!ip) return;
  3105. try {
  3106. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3107. method: 'POST',
  3108. headers: { 'Content-Type': 'application/json' },
  3109. body: JSON.stringify({ ip })
  3110. });
  3111. if (res.ok) {
  3112. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3113. document.getElementById('modal-new-ip').value = '';
  3114. await fetchData(false);
  3115. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3116. if (iface) renderModalIPs(iface);
  3117. } else {
  3118. const err = await res.json();
  3119. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3120. }
  3121. } catch (err) {
  3122. showToast('Error', err.message, 'error');
  3123. }
  3124. }
  3125. async function removeInterfaceIP(ip) {
  3126. if (!confirm(`Remove IP ${ip}?`)) return;
  3127. try {
  3128. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3129. method: 'DELETE',
  3130. headers: { 'Content-Type': 'application/json' },
  3131. body: JSON.stringify({ ip })
  3132. });
  3133. if (res.ok) {
  3134. showToast('IP Removed', `Removed ${ip}`, 'success');
  3135. await fetchData(false);
  3136. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3137. if (iface) renderModalIPs(iface);
  3138. }
  3139. } catch (err) {
  3140. showToast('Error', err.message, 'error');
  3141. }
  3142. }
  3143. async function renameInterface() {
  3144. const oldName = state.currentModalIface;
  3145. const newNameInput = document.getElementById('modal-iface-new-name');
  3146. const newName = (newNameInput?.value || '').trim();
  3147. if (!oldName) return;
  3148. if (!newName) {
  3149. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3150. return;
  3151. }
  3152. if (newName === oldName) {
  3153. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3154. return;
  3155. }
  3156. if (newName.length > 15) {
  3157. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3158. return;
  3159. }
  3160. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3161. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3162. return;
  3163. }
  3164. const renameBtn = document.getElementById('modal-btn-rename');
  3165. if (renameBtn) {
  3166. renameBtn.disabled = true;
  3167. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3168. }
  3169. try {
  3170. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3171. method: 'POST',
  3172. headers: { 'Content-Type': 'application/json' },
  3173. body: JSON.stringify({ new_name: newName })
  3174. });
  3175. const data = await res.json();
  3176. if (!res.ok) {
  3177. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3178. return;
  3179. }
  3180. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3181. state.currentModalIface = newName;
  3182. document.getElementById('modal-iface-name').innerText = newName;
  3183. // Refresh application state
  3184. await fetchData(false);
  3185. const updated = (state.interfaces || []).find(i => i.name === newName);
  3186. if (updated) {
  3187. openIfaceModal(newName);
  3188. } else {
  3189. closeIfaceModal();
  3190. }
  3191. } catch (err) {
  3192. showToast('Error', err.message, 'error');
  3193. } finally {
  3194. if (renameBtn) {
  3195. renameBtn.disabled = false;
  3196. renameBtn.innerHTML = `
  3197. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3198. <span>Rename</span>
  3199. `;
  3200. }
  3201. }
  3202. }
  3203. async function saveInterfaceMetadata() {
  3204. const oldName = state.currentModalIface;
  3205. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3206. const role = document.getElementById('modal-iface-role').value;
  3207. const desc = document.getElementById('modal-iface-desc').value.trim();
  3208. let targetName = oldName;
  3209. // If user changed the name before clicking Save Changes, execute rename first
  3210. if (newName && newName !== oldName && oldName !== 'lo') {
  3211. try {
  3212. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3213. method: 'POST',
  3214. headers: { 'Content-Type': 'application/json' },
  3215. body: JSON.stringify({ new_name: newName })
  3216. });
  3217. const data = await renameRes.json();
  3218. if (!renameRes.ok) {
  3219. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3220. return;
  3221. }
  3222. targetName = newName;
  3223. state.currentModalIface = newName;
  3224. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3225. } catch (err) {
  3226. showToast('Error', err.message, 'error');
  3227. return;
  3228. }
  3229. }
  3230. try {
  3231. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3232. method: 'POST',
  3233. headers: { 'Content-Type': 'application/json' },
  3234. body: JSON.stringify({ role, description: desc })
  3235. });
  3236. if (res.ok) {
  3237. showToast('Saved', 'Interface configuration updated', 'success');
  3238. closeIfaceModal();
  3239. fetchData(false);
  3240. } else {
  3241. const err = await res.json();
  3242. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3243. }
  3244. } catch (err) {
  3245. showToast('Error', err.message, 'error');
  3246. }
  3247. }
  3248. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3249. state.fwSubTab = 'filter';
  3250. state.routesSubTab = 'routes';
  3251. function renderRuleFlag(disabled, hasComment) {
  3252. let flags = '';
  3253. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3254. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3255. return flags || '<span class="text-slate-600">-</span>';
  3256. }
  3257. function renderActionBadge(action) {
  3258. const act = (action || '').toLowerCase();
  3259. let color = 'bg-slate-800 text-slate-300';
  3260. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3261. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3262. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3263. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3264. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3265. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3266. }
  3267. function switchFWSubTab(tab) {
  3268. state.fwSubTab = tab;
  3269. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3270. tabs.forEach(t => {
  3271. const panel = document.getElementById(`fw-subtab-${t}`);
  3272. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3273. if (panel) {
  3274. if (t === tab) panel.classList.remove('hidden');
  3275. else panel.classList.add('hidden');
  3276. }
  3277. if (btn) {
  3278. if (t === tab) {
  3279. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3280. } else {
  3281. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3282. }
  3283. }
  3284. });
  3285. const addBtn = document.getElementById('fw-primary-add-btn');
  3286. if (addBtn) {
  3287. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3288. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3289. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3290. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3291. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3292. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3293. }
  3294. if (tab === 'geo') loadGeoIP();
  3295. if (tab === 'connections') loadConnections();
  3296. setTimeout(initTableSorting, 50);
  3297. }
  3298. function openCurrentFWModal() {
  3299. if (state.fwSubTab === 'filter') openAddFilterModal();
  3300. else if (state.fwSubTab === 'nat') openAddNATModal();
  3301. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3302. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3303. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3304. else if (state.fwSubTab === 'connections') loadConnections();
  3305. }
  3306. async function loadFirewall(populateDropdowns = true) {
  3307. try {
  3308. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3309. fetch(`${API_BASE}/firewall/summary`),
  3310. fetch(`${API_BASE}/firewall/filter`),
  3311. fetch(`${API_BASE}/firewall/nat`),
  3312. fetch(`${API_BASE}/firewall/mangle`),
  3313. fetch(`${API_BASE}/firewall/address-lists`),
  3314. fetch(`${API_BASE}/firewall/geoip/status`),
  3315. fetch(`${API_BASE}/firewall/geoip/countries`)
  3316. ]);
  3317. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3318. if (filterRes.ok) state.filterRules = await filterRes.json();
  3319. if (natRes.ok) state.natRules = await natRes.json();
  3320. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3321. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3322. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3323. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3324. // Badges
  3325. const bFilter = document.getElementById('fw-badge-filter');
  3326. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3327. const bNat = document.getElementById('fw-badge-nat');
  3328. if (bNat) bNat.innerText = (state.natRules || []).length;
  3329. const bMangle = document.getElementById('fw-badge-mangle');
  3330. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3331. const bAddr = document.getElementById('fw-badge-addrlist');
  3332. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3333. const bGeo = document.getElementById('fw-badge-geo');
  3334. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3335. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3336. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3337. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3338. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3339. const tbodyFilter = document.getElementById('filter-rules-table-body');
  3340. if (tbodyFilter && (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter)) {
  3341. tbodyFilter.dataset.sig = sigFilter;
  3342. renderFilterRules();
  3343. }
  3344. const tbodyNat = document.getElementById('nat-rules-table-body');
  3345. if (tbodyNat && (populateDropdowns || tbodyNat.dataset.sig !== sigNat)) {
  3346. tbodyNat.dataset.sig = sigNat;
  3347. renderNATRules();
  3348. }
  3349. const tbodyMangle = document.getElementById('mangle-rules-table-body');
  3350. if (tbodyMangle && (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle)) {
  3351. tbodyMangle.dataset.sig = sigMangle;
  3352. renderMangleRules();
  3353. }
  3354. const tbodyAddr = document.getElementById('addr-list-table-body');
  3355. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3356. tbodyAddr.dataset.sig = sigAddr;
  3357. renderAddressLists();
  3358. }
  3359. renderGeoCountries();
  3360. if (state.fwSubTab === 'connections') {
  3361. loadConnections();
  3362. }
  3363. } catch (err) {
  3364. console.error('Failed to load firewall:', err);
  3365. }
  3366. }
  3367. // ----------------- Filter Rules -----------------
  3368. function renderFilterRules() {
  3369. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3370. const tbody = document.getElementById('filter-table-body');
  3371. const empty = document.getElementById('filter-empty');
  3372. if (!tbody) return;
  3373. tbody.innerHTML = '';
  3374. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3375. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3376. if (rules.length === 0) {
  3377. empty?.classList.remove('hidden');
  3378. return;
  3379. }
  3380. empty?.classList.add('hidden');
  3381. rules.forEach((r, idx) => {
  3382. const tr = document.createElement('tr');
  3383. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3384. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3385. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3386. let actionExtra = '';
  3387. if (r.action === 'reject') {
  3388. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3389. } else if (r.action === 'jump') {
  3390. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3391. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3392. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3393. } else if (r.action === 'log' && r.log_prefix) {
  3394. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3395. }
  3396. tr.innerHTML = `
  3397. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3398. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3399. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3400. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3401. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3402. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3403. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3404. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3405. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3406. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3407. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3408. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3409. </td>
  3410. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3411. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3412. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3413. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3414. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3415. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3416. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3417. </td>
  3418. `;
  3419. tbody.appendChild(tr);
  3420. });
  3421. }
  3422. function formatTarget(addr, list, geo) {
  3423. const parts = [];
  3424. if (addr) parts.push(`<span>${addr}</span>`);
  3425. if (list) {
  3426. const inv = list.startsWith('!') ? '!' : '';
  3427. const clean = list.replace(/^!/, '');
  3428. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3429. }
  3430. if (geo) {
  3431. const inv = geo.startsWith('!') ? '!' : '';
  3432. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3433. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3434. }
  3435. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3436. return parts.join(' ');
  3437. }
  3438. function populateInterfaceSelect(selectId, currentVal = '') {
  3439. const sel = document.getElementById(selectId);
  3440. if (!sel) return;
  3441. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3442. (state.interfaces || []).forEach(i => {
  3443. const opt = document.createElement('option');
  3444. opt.value = i.name;
  3445. opt.innerText = `${i.name} (${i.role || i.type})`;
  3446. if (i.name === currentVal) opt.selected = true;
  3447. sel.appendChild(opt);
  3448. });
  3449. }
  3450. function populateAddressListSelect(selectId, currentVal = '') {
  3451. const sel = document.getElementById(selectId);
  3452. if (!sel) return;
  3453. sel.innerHTML = '<option value="">(None)</option>';
  3454. const cleanVal = (currentVal || '').replace(/^!/, '');
  3455. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3456. customNames.forEach(name => {
  3457. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3458. const opt = document.createElement('option');
  3459. opt.value = name;
  3460. opt.innerText = `${name} (${count} entries)`;
  3461. if (name === cleanVal) opt.selected = true;
  3462. sel.appendChild(opt);
  3463. });
  3464. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3465. const opt = document.createElement('option');
  3466. opt.value = cleanVal;
  3467. opt.innerText = cleanVal;
  3468. opt.selected = true;
  3469. sel.appendChild(opt);
  3470. }
  3471. populateCommonAddrListDatalist();
  3472. }
  3473. function populateCommonAddrListDatalist() {
  3474. const dl = document.getElementById('fw-addrlist-datalist');
  3475. if (!dl) return;
  3476. dl.innerHTML = '';
  3477. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3478. names.forEach(name => {
  3479. const opt = document.createElement('option');
  3480. opt.value = name;
  3481. dl.appendChild(opt);
  3482. });
  3483. }
  3484. function populateGeoIPSelect(selectId, currentVal = '') {
  3485. const sel = document.getElementById(selectId);
  3486. if (!sel) return;
  3487. sel.innerHTML = '<option value="">(None)</option>';
  3488. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3489. // Presets optgroup
  3490. const grpPresets = document.createElement('optgroup');
  3491. grpPresets.label = '⚡ Regional Presets';
  3492. const presets = [
  3493. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3494. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3495. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3496. ];
  3497. presets.forEach(p => {
  3498. const opt = document.createElement('option');
  3499. opt.value = p.code;
  3500. opt.innerText = p.label;
  3501. if (p.code === cleanVal) opt.selected = true;
  3502. grpPresets.appendChild(opt);
  3503. });
  3504. sel.appendChild(grpPresets);
  3505. // All Countries optgroup
  3506. const grpCountries = document.createElement('optgroup');
  3507. grpCountries.label = '🌍 All Countries';
  3508. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3509. countries.forEach(c => {
  3510. const opt = document.createElement('option');
  3511. opt.value = c.code;
  3512. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3513. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3514. if (c.code === cleanVal) opt.selected = true;
  3515. grpCountries.appendChild(opt);
  3516. });
  3517. sel.appendChild(grpCountries);
  3518. }
  3519. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3520. function switchFwRuleTab(tab) {
  3521. state.activeFwRuleTab = tab;
  3522. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3523. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3524. btn.classList.add('text-slate-400', 'border-transparent');
  3525. });
  3526. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3527. if (activeBtn) {
  3528. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3529. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3530. }
  3531. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3532. const activePane = document.getElementById(`fw-pane-${tab}`);
  3533. if (activePane) activePane.classList.remove('hidden');
  3534. if (tab === 'statistics') {
  3535. startFwStatPolling();
  3536. } else {
  3537. stopFwStatPolling();
  3538. }
  3539. }
  3540. function toggleFwField(fieldKey, expand) {
  3541. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3542. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3543. if (!plusBtn || !fieldBox) return;
  3544. if (expand) {
  3545. plusBtn.classList.add('hidden');
  3546. fieldBox.classList.remove('hidden');
  3547. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3548. if (valInput) valInput.focus();
  3549. } else {
  3550. fieldBox.classList.add('hidden');
  3551. plusBtn.classList.remove('hidden');
  3552. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3553. if (valInput) {
  3554. if (valInput.tagName === 'SELECT') {
  3555. valInput.selectedIndex = 0;
  3556. } else {
  3557. valInput.value = '';
  3558. }
  3559. }
  3560. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3561. if (invInput) invInput.checked = false;
  3562. if (fieldKey === 'cs') {
  3563. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3564. const el = document.getElementById(id);
  3565. if (el) el.checked = false;
  3566. });
  3567. }
  3568. if (fieldKey === 'natstate') {
  3569. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3570. const el = document.getElementById(id);
  3571. if (el) el.checked = false;
  3572. });
  3573. }
  3574. if (fieldKey === 'days') {
  3575. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3576. const el = document.getElementById(`fw-day-${d}`);
  3577. if (el) el.checked = true;
  3578. });
  3579. }
  3580. }
  3581. }
  3582. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3583. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3584. toggleFwField(fieldKey, true);
  3585. let strVal = String(value);
  3586. if (hasInvert) {
  3587. const inv = strVal.startsWith('!');
  3588. if (inv) strVal = strVal.slice(1);
  3589. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3590. if (invEl) invEl.checked = inv;
  3591. }
  3592. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3593. if (valEl) valEl.value = strVal;
  3594. } else {
  3595. toggleFwField(fieldKey, false);
  3596. }
  3597. }
  3598. function getFwFieldVal(fieldKey, hasInvert = false) {
  3599. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3600. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3601. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3602. let v = valEl ? valEl.value.trim() : '';
  3603. if (!v) return '';
  3604. if (hasInvert) {
  3605. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3606. if (invEl && invEl.checked) {
  3607. v = '!' + v.replace(/^!/, '');
  3608. }
  3609. }
  3610. return v;
  3611. }
  3612. function toggleMaximizeFilterModal() {
  3613. const win = document.getElementById('filter-modal-window');
  3614. if (!win) return;
  3615. if (win.classList.contains('max-w-[720px]')) {
  3616. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3617. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3618. } else {
  3619. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3620. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3621. }
  3622. }
  3623. function openAddFilterModal() {
  3624. switchFwRuleTab('general');
  3625. const badge = document.getElementById('fw-modal-badge');
  3626. if (badge) badge.innerText = 'New...';
  3627. document.getElementById('filter-modal-id').value = '';
  3628. document.getElementById('filter-modal-enabled').checked = true;
  3629. document.getElementById('filter-modal-comment').value = '';
  3630. document.getElementById('filter-modal-chain').value = 'forward';
  3631. document.getElementById('filter-modal-action').value = 'accept';
  3632. document.getElementById('filter-modal-log').checked = false;
  3633. populateInterfaceSelect('fw-val-iniface');
  3634. populateInterfaceSelect('fw-val-outiface');
  3635. populateAddressListSelect('fw-val-srclist');
  3636. populateAddressListSelect('fw-val-dstlist');
  3637. populateGeoIPSelect('fw-val-srcgeo');
  3638. populateGeoIPSelect('fw-val-dstgeo');
  3639. const allFieldKeys = [
  3640. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3641. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3642. 'routingmark', 'conntype', 'cs', 'natstate',
  3643. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3644. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3645. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3646. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3647. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3648. ];
  3649. allFieldKeys.forEach(k => toggleFwField(k, false));
  3650. resetCurrentRuleCounters();
  3651. toggleFilterActionFields();
  3652. document.getElementById('filter-modal').classList.remove('hidden');
  3653. }
  3654. function openEditFilterModal(id) {
  3655. const r = (state.filterRules || []).find(rule => rule.id === id);
  3656. if (!r) return;
  3657. switchFwRuleTab('general');
  3658. const badge = document.getElementById('fw-modal-badge');
  3659. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3660. document.getElementById('filter-modal-id').value = r.id;
  3661. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3662. document.getElementById('filter-modal-comment').value = r.comment || '';
  3663. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3664. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3665. document.getElementById('filter-modal-log').checked = !!r.log;
  3666. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3667. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3668. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3669. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3670. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3671. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3672. setFwFieldVal('src', r.src_address, true);
  3673. setFwFieldVal('dst', r.dst_address, true);
  3674. setFwFieldVal('srclist', r.src_address_list, true);
  3675. setFwFieldVal('dstlist', r.dst_address_list, true);
  3676. setFwFieldVal('srcgeo', r.src_geoip, true);
  3677. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3678. if (r.protocol && r.protocol !== 'all') {
  3679. setFwFieldVal('proto', r.protocol, true);
  3680. } else {
  3681. toggleFwField('proto', false);
  3682. }
  3683. setFwFieldVal('sport', r.src_port, true);
  3684. setFwFieldVal('dport', r.dst_port, true);
  3685. setFwFieldVal('anyport', r.any_port, true);
  3686. setFwFieldVal('iniface', r.in_interface, true);
  3687. setFwFieldVal('outiface', r.out_interface, true);
  3688. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3689. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3690. setFwFieldVal('pktmark', r.packet_mark, true);
  3691. setFwFieldVal('connmark', r.connection_mark, true);
  3692. setFwFieldVal('routingmark', r.routing_mark, true);
  3693. setFwFieldVal('conntype', r.connection_type, false);
  3694. const states = r.connection_state || [];
  3695. if (states.length > 0) {
  3696. toggleFwField('cs', true);
  3697. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3698. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3699. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3700. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3701. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3702. } else {
  3703. toggleFwField('cs', false);
  3704. }
  3705. const natStates = r.connection_nat_state || [];
  3706. if (natStates.length > 0) {
  3707. toggleFwField('natstate', true);
  3708. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3709. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3710. } else {
  3711. toggleFwField('natstate', false);
  3712. }
  3713. // Advanced tab fields
  3714. setFwFieldVal('layer7', r.layer7_protocol, false);
  3715. setFwFieldVal('content', r.content, false);
  3716. setFwFieldVal('connbytes', r.connection_bytes, false);
  3717. setFwFieldVal('connrate', r.connection_rate, false);
  3718. setFwFieldVal('pcc', r.pcc, false);
  3719. setFwFieldVal('srcmac', r.src_mac_address, true);
  3720. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3721. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3722. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3723. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3724. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3725. setFwFieldVal('tlshost', r.tls_host, false);
  3726. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3727. setFwFieldVal('priority', r.priority, false);
  3728. setFwFieldVal('dscp', r.dscp, false);
  3729. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3730. if (r.tos) {
  3731. const tosEl = document.getElementById('fw-val-tos');
  3732. if (tosEl) tosEl.value = r.tos;
  3733. }
  3734. setFwFieldVal('pktsize', r.packet_size, false);
  3735. setFwFieldVal('random', r.random, false);
  3736. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3737. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3738. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3739. setFwFieldVal('ttl', r.ttl, false);
  3740. // Extra tab fields
  3741. setFwFieldVal('time', r.time, false);
  3742. if (r.days) {
  3743. toggleFwField('days', true);
  3744. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3745. const chk = document.getElementById(`fw-day-${d}`);
  3746. if (chk) chk.checked = r.days.includes(d);
  3747. });
  3748. } else {
  3749. toggleFwField('days', false);
  3750. }
  3751. setFwFieldVal('limit', r.limit, false);
  3752. setFwFieldVal('dstlimit', r.dst_limit, false);
  3753. setFwFieldVal('psd', r.psd, false);
  3754. // Action fields
  3755. if (r.reject_with) {
  3756. const rwEl = document.getElementById('filter-modal-rejectwith');
  3757. if (rwEl) rwEl.value = r.reject_with;
  3758. }
  3759. if (r.jump_target) {
  3760. const jtEl = document.getElementById('filter-modal-jumptarget');
  3761. if (jtEl) jtEl.value = r.jump_target;
  3762. }
  3763. if (r.address_list) {
  3764. const alEl = document.getElementById('filter-modal-action-addrlist');
  3765. if (alEl) alEl.value = r.address_list;
  3766. }
  3767. if (r.address_list_timeout) {
  3768. const toEl = document.getElementById('filter-modal-action-timeout');
  3769. if (toEl) toEl.value = r.address_list_timeout;
  3770. }
  3771. setFwFieldVal('logprefix', r.log_prefix, false);
  3772. // Statistics
  3773. const bEl = document.getElementById('fw-stat-bytes');
  3774. const pEl = document.getElementById('fw-stat-packets');
  3775. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3776. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3777. state.fwLastBytes = r.bytes || 0;
  3778. state.fwLastPackets = r.packets || 0;
  3779. state.fwLastTimestamp = Date.now();
  3780. state.fwStatRateHistory = new Array(30).fill(0);
  3781. state.fwStatPktHistory = new Array(30).fill(0);
  3782. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3783. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3784. toggleFilterActionFields();
  3785. document.getElementById('filter-modal').classList.remove('hidden');
  3786. }
  3787. function closeFilterModal() {
  3788. stopFwStatPolling();
  3789. document.getElementById('filter-modal').classList.add('hidden');
  3790. }
  3791. function toggleFilterActionFields() {
  3792. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3793. const rejectBox = document.getElementById('filter-action-reject-box');
  3794. const jumpBox = document.getElementById('filter-action-jump-box');
  3795. const addrBox = document.getElementById('filter-action-addrlist-box');
  3796. if (rejectBox) {
  3797. if (act === 'reject') rejectBox.classList.remove('hidden');
  3798. else rejectBox.classList.add('hidden');
  3799. }
  3800. if (jumpBox) {
  3801. if (act === 'jump') jumpBox.classList.remove('hidden');
  3802. else jumpBox.classList.add('hidden');
  3803. }
  3804. if (addrBox) {
  3805. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3806. addrBox.classList.remove('hidden');
  3807. } else {
  3808. addrBox.classList.add('hidden');
  3809. }
  3810. }
  3811. if (act === 'log') {
  3812. const logEl = document.getElementById('filter-modal-log');
  3813. if (logEl) logEl.checked = true;
  3814. toggleFwField('logprefix', true);
  3815. }
  3816. }
  3817. function toggleFwLogPrefix() {
  3818. const isLog = document.getElementById('filter-modal-log')?.checked;
  3819. toggleFwField('logprefix', !!isLog);
  3820. }
  3821. function copyFilterRule() {
  3822. document.getElementById('filter-modal-id').value = '';
  3823. const badge = document.getElementById('fw-modal-badge');
  3824. if (badge) badge.innerText = 'New...';
  3825. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3826. }
  3827. function resetCurrentRuleCounters() {
  3828. state.fwStatRateHistory = new Array(30).fill(0);
  3829. state.fwStatPktHistory = new Array(30).fill(0);
  3830. state.fwLastBytes = 0;
  3831. state.fwLastPackets = 0;
  3832. state.fwLastTimestamp = Date.now();
  3833. const bEl = document.getElementById('fw-stat-bytes');
  3834. const pEl = document.getElementById('fw-stat-packets');
  3835. const rEl = document.getElementById('fw-stat-rate');
  3836. const prEl = document.getElementById('fw-stat-pktrate');
  3837. if (bEl) bEl.value = '0 B';
  3838. if (pEl) pEl.value = '0';
  3839. if (rEl) rEl.value = '0 bps';
  3840. if (prEl) prEl.value = '0 p/s';
  3841. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3842. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3843. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3844. }
  3845. async function resetAllFwCounters() {
  3846. try {
  3847. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3848. if (res.ok) {
  3849. resetCurrentRuleCounters();
  3850. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3851. loadFirewall(false);
  3852. }
  3853. } catch (err) {
  3854. showToast('Error', err.message, 'error');
  3855. }
  3856. }
  3857. async function applyFilterRule(closeAfter = false) {
  3858. const id = document.getElementById('filter-modal-id').value;
  3859. const chain = document.getElementById('filter-modal-chain').value;
  3860. const action = document.getElementById('filter-modal-action').value;
  3861. const comment = document.getElementById('filter-modal-comment').value.trim();
  3862. const enabled = document.getElementById('filter-modal-enabled').checked;
  3863. const src = getFwFieldVal('src', true);
  3864. const dst = getFwFieldVal('dst', true);
  3865. const srclist = getFwFieldVal('srclist', true);
  3866. const dstlist = getFwFieldVal('dstlist', true);
  3867. const srcgeo = getFwFieldVal('srcgeo', true);
  3868. const dstgeo = getFwFieldVal('dstgeo', true);
  3869. const proto = getFwFieldVal('proto', true);
  3870. const sport = getFwFieldVal('sport', true);
  3871. const dport = getFwFieldVal('dport', true);
  3872. const anyport = getFwFieldVal('anyport', true);
  3873. const iniface = getFwFieldVal('iniface', true);
  3874. const outiface = getFwFieldVal('outiface', true);
  3875. const inifacelist = getFwFieldVal('inifacelist', true);
  3876. const outifacelist = getFwFieldVal('outifacelist', true);
  3877. const pktmark = getFwFieldVal('pktmark', true);
  3878. const connmark = getFwFieldVal('connmark', true);
  3879. const routingmark = getFwFieldVal('routingmark', true);
  3880. const conntype = getFwFieldVal('conntype', false);
  3881. const states = [];
  3882. const csBox = document.getElementById('fw-field-cs');
  3883. if (csBox && !csBox.classList.contains('hidden')) {
  3884. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3885. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3886. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3887. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3888. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3889. }
  3890. const natStates = [];
  3891. const natBox = document.getElementById('fw-field-natstate');
  3892. if (natBox && !natBox.classList.contains('hidden')) {
  3893. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3894. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3895. }
  3896. const payload = {
  3897. id,
  3898. chain,
  3899. action,
  3900. protocol: proto || 'all',
  3901. src_address: src,
  3902. dst_address: dst,
  3903. src_port: sport,
  3904. dst_port: dport,
  3905. any_port: anyport,
  3906. in_interface: iniface,
  3907. out_interface: outiface,
  3908. in_interface_list: inifacelist,
  3909. out_interface_list: outifacelist,
  3910. packet_mark: pktmark,
  3911. connection_mark: connmark,
  3912. routing_mark: routingmark,
  3913. connection_type: conntype,
  3914. connection_state: states,
  3915. connection_nat_state: natStates,
  3916. src_address_list: srclist,
  3917. dst_address_list: dstlist,
  3918. src_geoip: srcgeo,
  3919. dst_geoip: dstgeo,
  3920. comment,
  3921. disabled: !enabled,
  3922. // Advanced tab
  3923. layer7_protocol: getFwFieldVal('layer7', false),
  3924. content: getFwFieldVal('content', false),
  3925. connection_bytes: getFwFieldVal('connbytes', false),
  3926. connection_rate: getFwFieldVal('connrate', false),
  3927. pcc: getFwFieldVal('pcc', false),
  3928. src_mac_address: getFwFieldVal('srcmac', true),
  3929. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3930. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3931. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3932. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3933. ipsec_policy: getFwFieldVal('ipsec', false),
  3934. tls_host: getFwFieldVal('tlshost', false),
  3935. ingress_priority: getFwFieldVal('ingresspriority', false),
  3936. priority: getFwFieldVal('priority', false),
  3937. dscp: getFwFieldVal('dscp', false),
  3938. tcp_mss: getFwFieldVal('tcpmss', false),
  3939. tos: document.getElementById('fw-val-tos')?.value || '',
  3940. packet_size: getFwFieldVal('pktsize', false),
  3941. random: getFwFieldVal('random', false),
  3942. tcp_flags: getFwFieldVal('tcpflags', false),
  3943. icmp_options: getFwFieldVal('icmpoptions', false),
  3944. ipv4_options: getFwFieldVal('ipv4options', false),
  3945. ttl: getFwFieldVal('ttl', false),
  3946. // Extra tab
  3947. time: getFwFieldVal('time', false),
  3948. limit: getFwFieldVal('limit', false),
  3949. dst_limit: getFwFieldVal('dstlimit', false),
  3950. psd: getFwFieldVal('psd', false),
  3951. // Action tab
  3952. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3953. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3954. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3955. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3956. log: document.getElementById('filter-modal-log')?.checked || false,
  3957. log_prefix: getFwFieldVal('logprefix', false)
  3958. };
  3959. try {
  3960. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3961. method: 'POST',
  3962. headers: { 'Content-Type': 'application/json' },
  3963. body: JSON.stringify(payload)
  3964. });
  3965. if (res.ok) {
  3966. const data = await res.json();
  3967. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3968. loadFirewall(false);
  3969. if (closeAfter) {
  3970. closeFilterModal();
  3971. } else {
  3972. if (data.id) {
  3973. document.getElementById('filter-modal-id').value = data.id;
  3974. const badge = document.getElementById('fw-modal-badge');
  3975. if (badge) badge.innerText = `#${data.id}`;
  3976. }
  3977. }
  3978. } else {
  3979. const err = await res.json();
  3980. showToast('Error', err.message || 'Failed to save rule', 'error');
  3981. }
  3982. } catch (err) {
  3983. showToast('Error', err.message, 'error');
  3984. }
  3985. }
  3986. function submitSaveFilterRule(e) {
  3987. if (e && e.preventDefault) e.preventDefault();
  3988. return applyFilterRule(true);
  3989. }
  3990. function startFwStatPolling() {
  3991. stopFwStatPolling();
  3992. pollRuleStats();
  3993. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3994. }
  3995. function stopFwStatPolling() {
  3996. if (state.fwStatInterval) {
  3997. clearInterval(state.fwStatInterval);
  3998. state.fwStatInterval = null;
  3999. }
  4000. }
  4001. async function pollRuleStats() {
  4002. const id = document.getElementById('filter-modal-id')?.value;
  4003. if (!id) {
  4004. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4005. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4006. return;
  4007. }
  4008. try {
  4009. const res = await fetch(`${API_BASE}/firewall/filter`);
  4010. if (!res.ok) return;
  4011. const rules = await res.json();
  4012. const r = rules.find(x => x.id === id);
  4013. if (!r) return;
  4014. const now = Date.now();
  4015. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4016. state.fwLastTimestamp = now;
  4017. const curBytes = r.bytes || 0;
  4018. const curPackets = r.packets || 0;
  4019. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4020. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4021. state.fwLastBytes = curBytes;
  4022. state.fwLastPackets = curPackets;
  4023. const rateBps = Math.round((deltaBytes * 8) / dt);
  4024. const ratePkt = Math.round(deltaPkts / dt);
  4025. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4026. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4027. state.fwStatRateHistory.push(rateBps);
  4028. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4029. state.fwStatPktHistory.push(ratePkt);
  4030. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4031. const bEl = document.getElementById('fw-stat-bytes');
  4032. const pEl = document.getElementById('fw-stat-packets');
  4033. const rEl = document.getElementById('fw-stat-rate');
  4034. const prEl = document.getElementById('fw-stat-pktrate');
  4035. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4036. if (pEl) pEl.value = curPackets.toLocaleString();
  4037. if (rEl) rEl.value = formatBps(rateBps);
  4038. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4039. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4040. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4041. } catch (e) {
  4042. console.error('Error polling rule stats', e);
  4043. }
  4044. }
  4045. function formatBps(bps) {
  4046. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4047. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4048. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4049. return bps + ' bps';
  4050. }
  4051. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4052. const svg = document.getElementById(svgId);
  4053. if (!svg) return;
  4054. const w = 500;
  4055. const h = 100;
  4056. const paddingRight = 45;
  4057. const graphWidth = w - paddingRight;
  4058. const maxVal = Math.max(5, ...dataArray);
  4059. const currentVal = dataArray[dataArray.length - 1] || 0;
  4060. const leg = document.getElementById(legendId);
  4061. if (leg) {
  4062. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4063. }
  4064. let gridLines = '';
  4065. for (let i = 0; i <= 5; i++) {
  4066. const y = 8 + (i * (h - 18) / 5);
  4067. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4068. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4069. gridLines += `
  4070. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4071. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4072. `;
  4073. }
  4074. const step = graphWidth / (dataArray.length - 1);
  4075. const points = dataArray.map((val, idx) => {
  4076. const x = idx * step;
  4077. const y = (h - 10) - (val / maxVal) * (h - 20);
  4078. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4079. });
  4080. const polylineStr = points.join(' ');
  4081. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4082. svg.innerHTML = `
  4083. ${gridLines}
  4084. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4085. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4086. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4087. `;
  4088. }
  4089. async function moveFilterRule(id, dir) {
  4090. try {
  4091. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4092. method: 'POST',
  4093. headers: { 'Content-Type': 'application/json' },
  4094. body: JSON.stringify({ direction: dir })
  4095. });
  4096. if (res.ok) loadFirewall(false);
  4097. } catch (err) {
  4098. showToast('Error', err.message, 'error');
  4099. }
  4100. }
  4101. async function toggleFilterRuleState(id, disabled) {
  4102. try {
  4103. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4104. method: 'POST',
  4105. headers: { 'Content-Type': 'application/json' },
  4106. body: JSON.stringify({ disabled })
  4107. });
  4108. if (res.ok) loadFirewall(false);
  4109. } catch (err) {
  4110. showToast('Error', err.message, 'error');
  4111. }
  4112. }
  4113. async function deleteFilterRule(id) {
  4114. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4115. try {
  4116. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4117. if (res.ok) {
  4118. showToast('Deleted', 'Filter rule removed', 'success');
  4119. loadFirewall(false);
  4120. }
  4121. } catch (err) {
  4122. showToast('Error', err.message, 'error');
  4123. }
  4124. }
  4125. // ----------------- NAT Rules -----------------
  4126. function renderNATRules() {
  4127. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4128. const tbody = document.getElementById('nat-table-body');
  4129. const empty = document.getElementById('nat-empty');
  4130. if (!tbody) return;
  4131. tbody.innerHTML = '';
  4132. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4133. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4134. if (rules.length === 0) {
  4135. empty?.classList.remove('hidden');
  4136. return;
  4137. }
  4138. empty?.classList.add('hidden');
  4139. rules.forEach((r, idx) => {
  4140. const tr = document.createElement('tr');
  4141. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4142. let toTarget = '-';
  4143. if (r.action === 'jump') {
  4144. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4145. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4146. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4147. } else if (r.action === 'redirect') {
  4148. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4149. } else if (r.action === 'masquerade') {
  4150. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  4151. } else if (r.action === 'log') {
  4152. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4153. } else {
  4154. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4155. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4156. }
  4157. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4158. tr.innerHTML = `
  4159. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4160. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4161. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4162. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4163. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4164. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4165. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4166. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4167. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4168. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4169. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4170. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4171. </td>
  4172. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4173. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4174. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4175. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4176. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4177. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4178. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4179. </td>
  4180. `;
  4181. tbody.appendChild(tr);
  4182. });
  4183. }
  4184. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4185. function switchNATRuleTab(tab) {
  4186. state.activeNATRuleTab = tab;
  4187. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4188. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4189. btn.classList.add('text-slate-400', 'border-transparent');
  4190. });
  4191. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4192. if (activeBtn) {
  4193. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4194. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4195. }
  4196. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4197. const activePane = document.getElementById(`nat-pane-${tab}`);
  4198. if (activePane) activePane.classList.remove('hidden');
  4199. if (tab === 'statistics') {
  4200. startNATStatPolling();
  4201. } else {
  4202. stopNATStatPolling();
  4203. }
  4204. }
  4205. function toggleNATField(fieldKey, expand) {
  4206. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4207. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4208. if (!plusBtn || !fieldBox) return;
  4209. if (expand) {
  4210. plusBtn.classList.add('hidden');
  4211. fieldBox.classList.remove('hidden');
  4212. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4213. if (valInput) valInput.focus();
  4214. } else {
  4215. fieldBox.classList.add('hidden');
  4216. plusBtn.classList.remove('hidden');
  4217. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4218. if (valInput) {
  4219. if (valInput.tagName === 'SELECT') {
  4220. valInput.selectedIndex = 0;
  4221. } else {
  4222. valInput.value = '';
  4223. }
  4224. }
  4225. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4226. if (invInput) invInput.checked = false;
  4227. if (fieldKey === 'days') {
  4228. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4229. const el = document.getElementById(`nat-day-${d}`);
  4230. if (el) el.checked = true;
  4231. });
  4232. }
  4233. }
  4234. }
  4235. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4236. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4237. toggleNATField(fieldKey, true);
  4238. let strVal = String(value);
  4239. if (hasInvert) {
  4240. const inv = strVal.startsWith('!');
  4241. if (inv) strVal = strVal.slice(1);
  4242. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4243. if (invEl) invEl.checked = inv;
  4244. }
  4245. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4246. if (valEl) valEl.value = strVal;
  4247. } else {
  4248. toggleNATField(fieldKey, false);
  4249. }
  4250. }
  4251. function getNATFieldVal(fieldKey, hasInvert = false) {
  4252. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4253. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4254. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4255. let v = valEl ? valEl.value.trim() : '';
  4256. if (!v) return '';
  4257. if (hasInvert) {
  4258. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4259. if (invEl && invEl.checked) {
  4260. v = '!' + v.replace(/^!/, '');
  4261. }
  4262. }
  4263. return v;
  4264. }
  4265. function toggleMaximizeNATModal() {
  4266. const win = document.getElementById('nat-modal-window');
  4267. if (!win) return;
  4268. if (win.classList.contains('max-w-[720px]')) {
  4269. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4270. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4271. } else {
  4272. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4273. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4274. }
  4275. }
  4276. function handleNATChainChange() {
  4277. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4278. const actSel = document.getElementById('nat-modal-action');
  4279. if (actSel) {
  4280. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4281. actSel.value = 'masquerade';
  4282. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4283. actSel.value = 'dst-nat';
  4284. }
  4285. }
  4286. toggleNATActionFields();
  4287. }
  4288. function toggleNATActionFields() {
  4289. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4290. const rowAddr = document.getElementById('nat-row-toaddr');
  4291. const rowPort = document.getElementById('nat-row-toport');
  4292. const jumpBox = document.getElementById('nat-action-jump-box');
  4293. const addrBox = document.getElementById('nat-action-addrlist-box');
  4294. // Hide all dynamic rows first
  4295. if (rowAddr) rowAddr.classList.add('hidden');
  4296. if (rowPort) rowPort.classList.add('hidden');
  4297. if (jumpBox) jumpBox.classList.add('hidden');
  4298. if (addrBox) addrBox.classList.add('hidden');
  4299. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4300. if (rowAddr) rowAddr.classList.remove('hidden');
  4301. if (rowPort) rowPort.classList.remove('hidden');
  4302. } else if (act === 'redirect' || act === 'masquerade') {
  4303. if (rowPort) rowPort.classList.remove('hidden');
  4304. } else if (act === 'jump') {
  4305. if (jumpBox) jumpBox.classList.remove('hidden');
  4306. } else if (act.includes('address-list') || act.includes('address list')) {
  4307. if (addrBox) addrBox.classList.remove('hidden');
  4308. }
  4309. if (act === 'log') {
  4310. const logEl = document.getElementById('nat-modal-log');
  4311. if (logEl) logEl.checked = true;
  4312. toggleNATField('logprefix', true);
  4313. }
  4314. }
  4315. function toggleNATLogPrefix() {
  4316. const isLog = document.getElementById('nat-modal-log')?.checked;
  4317. toggleNATField('logprefix', !!isLog);
  4318. }
  4319. function openAddNATModal() {
  4320. switchNATRuleTab('general');
  4321. const badge = document.getElementById('nat-modal-badge');
  4322. if (badge) badge.innerText = 'New...';
  4323. document.getElementById('nat-modal-id').value = '';
  4324. document.getElementById('nat-modal-enabled').checked = true;
  4325. document.getElementById('nat-modal-comment').value = '';
  4326. document.getElementById('nat-modal-chain').value = 'srcnat';
  4327. document.getElementById('nat-modal-action').value = 'masquerade';
  4328. document.getElementById('nat-modal-toaddr').value = '';
  4329. document.getElementById('nat-modal-toport').value = '';
  4330. document.getElementById('nat-modal-log').checked = false;
  4331. populateInterfaceSelect('nat-val-iniface');
  4332. populateInterfaceSelect('nat-val-outiface');
  4333. populateAddressListSelect('nat-val-srclist');
  4334. populateAddressListSelect('nat-val-dstlist');
  4335. populateGeoIPSelect('nat-val-srcgeo');
  4336. populateGeoIPSelect('nat-val-dstgeo');
  4337. const allFieldKeys = [
  4338. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4339. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4340. 'routingmark', 'conntype',
  4341. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4342. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4343. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4344. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4345. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4346. ];
  4347. allFieldKeys.forEach(k => toggleNATField(k, false));
  4348. resetCurrentNATRuleCounters();
  4349. toggleNATActionFields();
  4350. document.getElementById('nat-modal').classList.remove('hidden');
  4351. }
  4352. function openEditNATModal(id) {
  4353. const r = (state.natRules || []).find(rule => rule.id === id);
  4354. if (!r) return;
  4355. switchNATRuleTab('general');
  4356. const badge = document.getElementById('nat-modal-badge');
  4357. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4358. document.getElementById('nat-modal-id').value = r.id;
  4359. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4360. document.getElementById('nat-modal-comment').value = r.comment || '';
  4361. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4362. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4363. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4364. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4365. document.getElementById('nat-modal-log').checked = !!r.log;
  4366. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4367. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4368. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4369. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4370. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4371. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4372. setNATFieldVal('src', r.src_address, true);
  4373. setNATFieldVal('dst', r.dst_address, true);
  4374. setNATFieldVal('srclist', r.src_address_list, true);
  4375. setNATFieldVal('dstlist', r.dst_address_list, true);
  4376. setNATFieldVal('srcgeo', r.src_geoip, true);
  4377. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4378. if (r.protocol && r.protocol !== 'all') {
  4379. setNATFieldVal('proto', r.protocol, true);
  4380. } else {
  4381. toggleNATField('proto', false);
  4382. }
  4383. setNATFieldVal('sport', r.src_port, true);
  4384. setNATFieldVal('dport', r.dst_port, true);
  4385. setNATFieldVal('anyport', r.any_port, true);
  4386. setNATFieldVal('iniface', r.in_interface, true);
  4387. setNATFieldVal('outiface', r.out_interface, true);
  4388. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4389. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4390. setNATFieldVal('pktmark', r.packet_mark, true);
  4391. setNATFieldVal('connmark', r.connection_mark, true);
  4392. setNATFieldVal('routingmark', r.routing_mark, true);
  4393. setNATFieldVal('conntype', r.connection_type, false);
  4394. // Advanced tab fields
  4395. setNATFieldVal('layer7', r.layer7_protocol, false);
  4396. setNATFieldVal('content', r.content, false);
  4397. setNATFieldVal('connbytes', r.connection_bytes, false);
  4398. setNATFieldVal('connrate', r.connection_rate, false);
  4399. setNATFieldVal('pcc', r.pcc, false);
  4400. setNATFieldVal('srcmac', r.src_mac_address, true);
  4401. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4402. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4403. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4404. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4405. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4406. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4407. setNATFieldVal('priority', r.priority, false);
  4408. setNATFieldVal('dscp', r.dscp, false);
  4409. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4410. if (r.tos) {
  4411. const tosEl = document.getElementById('nat-val-tos');
  4412. if (tosEl) tosEl.value = r.tos;
  4413. }
  4414. setNATFieldVal('pktsize', r.packet_size, false);
  4415. setNATFieldVal('random', r.random, false);
  4416. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4417. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4418. setNATFieldVal('ttl', r.ttl, false);
  4419. // Extra tab fields
  4420. setNATFieldVal('time', r.time, false);
  4421. if (r.days) {
  4422. toggleNATField('days', true);
  4423. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4424. const chk = document.getElementById(`nat-day-${d}`);
  4425. if (chk) chk.checked = r.days.includes(d);
  4426. });
  4427. } else {
  4428. toggleNATField('days', false);
  4429. }
  4430. setNATFieldVal('limit', r.limit, false);
  4431. setNATFieldVal('dstlimit', r.dst_limit, false);
  4432. setNATFieldVal('psd', r.psd, false);
  4433. // Action fields
  4434. if (r.jump_target) {
  4435. const jtEl = document.getElementById('nat-modal-jumptarget');
  4436. if (jtEl) jtEl.value = r.jump_target;
  4437. }
  4438. if (r.address_list) {
  4439. const alEl = document.getElementById('nat-modal-action-addrlist');
  4440. if (alEl) alEl.value = r.address_list;
  4441. }
  4442. if (r.address_list_timeout) {
  4443. const toEl = document.getElementById('nat-modal-action-timeout');
  4444. if (toEl) toEl.value = r.address_list_timeout;
  4445. }
  4446. setNATFieldVal('logprefix', r.log_prefix, false);
  4447. // Statistics
  4448. const bEl = document.getElementById('nat-stat-bytes');
  4449. const pEl = document.getElementById('nat-stat-packets');
  4450. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4451. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4452. state.natLastBytes = r.bytes || 0;
  4453. state.natLastPackets = r.packets || 0;
  4454. state.natLastTimestamp = Date.now();
  4455. state.natStatRateHistory = new Array(30).fill(0);
  4456. state.natStatPktHistory = new Array(30).fill(0);
  4457. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4458. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4459. toggleNATActionFields();
  4460. document.getElementById('nat-modal').classList.remove('hidden');
  4461. }
  4462. function closeNATModal() {
  4463. stopNATStatPolling();
  4464. document.getElementById('nat-modal').classList.add('hidden');
  4465. }
  4466. function copyNATRule() {
  4467. document.getElementById('nat-modal-id').value = '';
  4468. const badge = document.getElementById('nat-modal-badge');
  4469. if (badge) badge.innerText = 'New...';
  4470. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4471. }
  4472. function resetCurrentNATRuleCounters() {
  4473. state.natStatRateHistory = new Array(30).fill(0);
  4474. state.natStatPktHistory = new Array(30).fill(0);
  4475. state.natLastBytes = 0;
  4476. state.natLastPackets = 0;
  4477. state.natLastTimestamp = Date.now();
  4478. const bEl = document.getElementById('nat-stat-bytes');
  4479. const pEl = document.getElementById('nat-stat-packets');
  4480. const rEl = document.getElementById('nat-stat-rate');
  4481. const prEl = document.getElementById('nat-stat-pktrate');
  4482. if (bEl) bEl.value = '0 B';
  4483. if (pEl) pEl.value = '0';
  4484. if (rEl) rEl.value = '0 bps';
  4485. if (prEl) prEl.value = '0 p/s';
  4486. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4487. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4488. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4489. }
  4490. async function applyNATRule(closeAfter = false) {
  4491. const id = document.getElementById('nat-modal-id').value;
  4492. const chain = document.getElementById('nat-modal-chain').value;
  4493. const action = document.getElementById('nat-modal-action').value;
  4494. const comment = document.getElementById('nat-modal-comment').value.trim();
  4495. const enabled = document.getElementById('nat-modal-enabled').checked;
  4496. const src = getNATFieldVal('src', true);
  4497. const dst = getNATFieldVal('dst', true);
  4498. const srclist = getNATFieldVal('srclist', true);
  4499. const dstlist = getNATFieldVal('dstlist', true);
  4500. const srcgeo = getNATFieldVal('srcgeo', true);
  4501. const dstgeo = getNATFieldVal('dstgeo', true);
  4502. const proto = getNATFieldVal('proto', true);
  4503. const sport = getNATFieldVal('sport', true);
  4504. const dport = getNATFieldVal('dport', true);
  4505. const anyport = getNATFieldVal('anyport', true);
  4506. const iniface = getNATFieldVal('iniface', true);
  4507. const outiface = getNATFieldVal('outiface', true);
  4508. const inifacelist = getNATFieldVal('inifacelist', true);
  4509. const outifacelist = getNATFieldVal('outifacelist', true);
  4510. const pktmark = getNATFieldVal('pktmark', true);
  4511. const connmark = getNATFieldVal('connmark', true);
  4512. const routingmark = getNATFieldVal('routingmark', true);
  4513. const conntype = getNATFieldVal('conntype', false);
  4514. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4515. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4516. const payload = {
  4517. id,
  4518. chain,
  4519. action,
  4520. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4521. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4522. protocol: proto || 'all',
  4523. src_address: src,
  4524. dst_address: dst,
  4525. src_port: sport,
  4526. dst_port: dport,
  4527. any_port: anyport,
  4528. in_interface: iniface,
  4529. out_interface: outiface,
  4530. in_interface_list: inifacelist,
  4531. out_interface_list: outifacelist,
  4532. packet_mark: pktmark,
  4533. connection_mark: connmark,
  4534. routing_mark: routingmark,
  4535. connection_type: conntype,
  4536. src_address_list: srclist,
  4537. dst_address_list: dstlist,
  4538. src_geoip: srcgeo,
  4539. dst_geoip: dstgeo,
  4540. comment,
  4541. disabled: !enabled,
  4542. // Advanced tab
  4543. layer7_protocol: getNATFieldVal('layer7', false),
  4544. content: getNATFieldVal('content', false),
  4545. connection_bytes: getNATFieldVal('connbytes', false),
  4546. connection_rate: getNATFieldVal('connrate', false),
  4547. pcc: getNATFieldVal('pcc', false),
  4548. src_mac_address: getNATFieldVal('srcmac', true),
  4549. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4550. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4551. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4552. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4553. ipsec_policy: getNATFieldVal('ipsec', false),
  4554. ingress_priority: getNATFieldVal('ingresspriority', false),
  4555. priority: getNATFieldVal('priority', false),
  4556. dscp: getNATFieldVal('dscp', false),
  4557. tcp_mss: getNATFieldVal('tcpmss', false),
  4558. tos: document.getElementById('nat-val-tos')?.value || '',
  4559. packet_size: getNATFieldVal('pktsize', false),
  4560. random: getNATFieldVal('random', false),
  4561. icmp_options: getNATFieldVal('icmpoptions', false),
  4562. ipv4_options: getNATFieldVal('ipv4options', false),
  4563. ttl: getNATFieldVal('ttl', false),
  4564. // Extra tab
  4565. time: getNATFieldVal('time', false),
  4566. limit: getNATFieldVal('limit', false),
  4567. dst_limit: getNATFieldVal('dstlimit', false),
  4568. psd: getNATFieldVal('psd', false),
  4569. // Action tab
  4570. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4571. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4572. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4573. log: document.getElementById('nat-modal-log')?.checked || false,
  4574. log_prefix: getNATFieldVal('logprefix', false)
  4575. };
  4576. try {
  4577. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4578. method: 'POST',
  4579. headers: { 'Content-Type': 'application/json' },
  4580. body: JSON.stringify(payload)
  4581. });
  4582. if (res.ok) {
  4583. const data = await res.json();
  4584. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4585. loadFirewall(false);
  4586. if (closeAfter) {
  4587. closeNATModal();
  4588. } else {
  4589. if (data.id) {
  4590. document.getElementById('nat-modal-id').value = data.id;
  4591. const badge = document.getElementById('nat-modal-badge');
  4592. if (badge) badge.innerText = `#${data.id}`;
  4593. }
  4594. }
  4595. } else {
  4596. const err = await res.json();
  4597. showToast('Error', err.message || 'Failed to save rule', 'error');
  4598. }
  4599. } catch (err) {
  4600. showToast('Error', err.message, 'error');
  4601. }
  4602. }
  4603. function submitSaveNATRule(e) {
  4604. if (e && e.preventDefault) e.preventDefault();
  4605. return applyNATRule(true);
  4606. }
  4607. function startNATStatPolling() {
  4608. stopNATStatPolling();
  4609. pollNATRuleStats();
  4610. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4611. }
  4612. function stopNATStatPolling() {
  4613. if (state.natStatInterval) {
  4614. clearInterval(state.natStatInterval);
  4615. state.natStatInterval = null;
  4616. }
  4617. }
  4618. async function pollNATRuleStats() {
  4619. const id = document.getElementById('nat-modal-id')?.value;
  4620. if (!id) {
  4621. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4622. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4623. return;
  4624. }
  4625. try {
  4626. const res = await fetch(`${API_BASE}/firewall/nat`);
  4627. if (!res.ok) return;
  4628. const rules = await res.json();
  4629. const r = rules.find(x => x.id === id);
  4630. if (!r) return;
  4631. const now = Date.now();
  4632. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4633. state.natLastTimestamp = now;
  4634. const curBytes = r.bytes || 0;
  4635. const curPackets = r.packets || 0;
  4636. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4637. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4638. state.natLastBytes = curBytes;
  4639. state.natLastPackets = curPackets;
  4640. const rateBps = Math.round((deltaBytes * 8) / dt);
  4641. const ratePkt = Math.round(deltaPkts / dt);
  4642. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4643. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4644. state.natStatRateHistory.push(rateBps);
  4645. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4646. state.natStatPktHistory.push(ratePkt);
  4647. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4648. const bEl = document.getElementById('nat-stat-bytes');
  4649. const pEl = document.getElementById('nat-stat-packets');
  4650. const rEl = document.getElementById('nat-stat-rate');
  4651. const prEl = document.getElementById('nat-stat-pktrate');
  4652. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4653. if (pEl) pEl.value = curPackets.toLocaleString();
  4654. if (rEl) rEl.value = formatBps(rateBps);
  4655. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4656. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4657. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4658. } catch (e) {
  4659. console.error('Error polling NAT rule stats', e);
  4660. }
  4661. }
  4662. async function moveNATRule(id, dir) {
  4663. try {
  4664. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4665. method: 'POST',
  4666. headers: { 'Content-Type': 'application/json' },
  4667. body: JSON.stringify({ direction: dir })
  4668. });
  4669. if (res.ok) loadFirewall(false);
  4670. } catch (err) {
  4671. showToast('Error', err.message, 'error');
  4672. }
  4673. }
  4674. async function toggleNATRuleState(id, disabled) {
  4675. try {
  4676. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4677. method: 'POST',
  4678. headers: { 'Content-Type': 'application/json' },
  4679. body: JSON.stringify({ disabled })
  4680. });
  4681. if (res.ok) loadFirewall(false);
  4682. } catch (err) {
  4683. showToast('Error', err.message, 'error');
  4684. }
  4685. }
  4686. async function deleteNATRule(id) {
  4687. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4690. if (res.ok) {
  4691. showToast('Deleted', 'NAT rule removed', 'success');
  4692. loadFirewall(false);
  4693. }
  4694. } catch (err) {
  4695. showToast('Error', err.message, 'error');
  4696. }
  4697. }
  4698. // ----------------- Mangle Rules -----------------
  4699. function renderMangleRules() {
  4700. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4701. const tbody = document.getElementById('mangle-table-body');
  4702. const empty = document.getElementById('mangle-empty');
  4703. if (!tbody) return;
  4704. tbody.innerHTML = '';
  4705. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4706. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4707. if (rules.length === 0) {
  4708. empty?.classList.remove('hidden');
  4709. return;
  4710. }
  4711. empty?.classList.add('hidden');
  4712. rules.forEach((r, idx) => {
  4713. const tr = document.createElement('tr');
  4714. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4715. let markVal = '<span class="text-slate-500">-</span>';
  4716. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4717. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4718. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4719. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4720. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4721. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4722. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4723. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4724. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4725. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4726. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4727. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4728. tr.innerHTML = `
  4729. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4730. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4731. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4732. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4733. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4734. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4735. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4736. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  4737. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4738. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4739. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4740. </td>
  4741. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4742. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4743. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4744. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4745. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4746. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4747. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4748. </td>
  4749. `;
  4750. tbody.appendChild(tr);
  4751. });
  4752. }
  4753. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4754. function switchMangleRuleTab(tab) {
  4755. state.activeMangleRuleTab = tab;
  4756. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4757. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4758. btn.classList.add('text-slate-400', 'border-transparent');
  4759. });
  4760. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4761. if (activeBtn) {
  4762. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4763. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4764. }
  4765. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4766. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4767. if (activePane) activePane.classList.remove('hidden');
  4768. if (tab === 'statistics') {
  4769. startMangleStatPolling();
  4770. } else {
  4771. stopMangleStatPolling();
  4772. }
  4773. }
  4774. function toggleMangleField(fieldKey, expand) {
  4775. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4776. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4777. if (!plusBtn || !fieldBox) return;
  4778. if (expand) {
  4779. plusBtn.classList.add('hidden');
  4780. fieldBox.classList.remove('hidden');
  4781. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4782. if (valInput) valInput.focus();
  4783. } else {
  4784. fieldBox.classList.add('hidden');
  4785. plusBtn.classList.remove('hidden');
  4786. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4787. if (valInput) {
  4788. if (valInput.tagName === 'SELECT') {
  4789. valInput.selectedIndex = 0;
  4790. } else {
  4791. valInput.value = '';
  4792. }
  4793. }
  4794. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4795. if (invInput) invInput.checked = false;
  4796. if (fieldKey === 'cs') {
  4797. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4798. const el = document.getElementById(id);
  4799. if (el) el.checked = false;
  4800. });
  4801. }
  4802. if (fieldKey === 'natstate') {
  4803. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4804. const el = document.getElementById(id);
  4805. if (el) el.checked = false;
  4806. });
  4807. }
  4808. }
  4809. }
  4810. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4811. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4812. toggleMangleField(fieldKey, true);
  4813. let strVal = String(value);
  4814. if (hasInvert) {
  4815. const inv = strVal.startsWith('!');
  4816. if (inv) strVal = strVal.slice(1);
  4817. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4818. if (invEl) invEl.checked = inv;
  4819. }
  4820. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4821. if (valEl) valEl.value = strVal;
  4822. } else {
  4823. toggleMangleField(fieldKey, false);
  4824. }
  4825. }
  4826. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4827. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4828. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4829. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4830. let v = valEl ? valEl.value.trim() : '';
  4831. if (!v) return '';
  4832. if (hasInvert) {
  4833. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4834. if (invEl && invEl.checked) {
  4835. v = '!' + v.replace(/^!/, '');
  4836. }
  4837. }
  4838. return v;
  4839. }
  4840. function toggleMaximizeMangleModal() {
  4841. const win = document.getElementById('mangle-modal-window');
  4842. if (!win) return;
  4843. if (win.classList.contains('max-w-[720px]')) {
  4844. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4845. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4846. } else {
  4847. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4848. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4849. }
  4850. }
  4851. function toggleMangleActionFields() {
  4852. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4853. // Hide all dynamic rows first
  4854. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4855. const el = document.getElementById(`mangle-row-${id}`);
  4856. if (el) el.classList.add('hidden');
  4857. });
  4858. const jumpBox = document.getElementById('mangle-action-jump-box');
  4859. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4860. if (jumpBox) jumpBox.classList.add('hidden');
  4861. if (addrBox) addrBox.classList.add('hidden');
  4862. // Activate matching rows
  4863. if (act === 'mark-connection') {
  4864. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4865. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4866. } else if (act === 'mark-routing') {
  4867. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4868. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4869. } else if (act === 'mark-packet') {
  4870. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4871. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4872. } else if (act === 'change-mss') {
  4873. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4874. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4875. } else if (act === 'change-dscp') {
  4876. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4877. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4878. } else if (act === 'change-ttl') {
  4879. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4880. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4881. } else if (act === 'set-priority') {
  4882. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4883. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4884. } else if (act === 'route') {
  4885. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4886. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4887. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4888. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4889. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4890. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4891. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4892. } else if (act === 'jump') {
  4893. if (jumpBox) jumpBox.classList.remove('hidden');
  4894. } else if (act.includes('address-list') || act.includes('address list')) {
  4895. if (addrBox) addrBox.classList.remove('hidden');
  4896. }
  4897. if (act === 'log') {
  4898. const logEl = document.getElementById('mangle-modal-log');
  4899. if (logEl) logEl.checked = true;
  4900. toggleMangleField('logprefix', true);
  4901. }
  4902. }
  4903. function toggleMangleLogPrefix() {
  4904. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4905. toggleMangleField('logprefix', !!isLog);
  4906. }
  4907. const allMangleFieldKeys = [
  4908. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4909. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4910. 'routingmark', 'conntype', 'cs', 'natstate',
  4911. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4912. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4913. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4914. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4915. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4916. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4917. ];
  4918. function openAddMangleModal() {
  4919. switchMangleRuleTab('general');
  4920. const badge = document.getElementById('mangle-modal-badge');
  4921. if (badge) badge.innerText = 'New...';
  4922. document.getElementById('mangle-modal-id').value = '';
  4923. document.getElementById('mangle-modal-enabled').checked = true;
  4924. document.getElementById('mangle-modal-comment').value = '';
  4925. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4926. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4927. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4928. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4929. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4930. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4931. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4932. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4933. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4934. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4935. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4936. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4937. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4938. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4939. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4940. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4941. populateInterfaceSelect('mangle-val-iniface');
  4942. populateInterfaceSelect('mangle-val-outiface');
  4943. populateAddressListSelect('mangle-val-srclist');
  4944. populateAddressListSelect('mangle-val-dstlist');
  4945. populateGeoIPSelect('mangle-val-srcgeo');
  4946. populateGeoIPSelect('mangle-val-dstgeo');
  4947. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4948. resetCurrentMangleRuleCounters();
  4949. toggleMangleActionFields();
  4950. document.getElementById('mangle-modal').classList.remove('hidden');
  4951. }
  4952. function openEditMangleModal(id) {
  4953. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4954. if (!r) return;
  4955. switchMangleRuleTab('general');
  4956. const badge = document.getElementById('mangle-modal-badge');
  4957. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4958. document.getElementById('mangle-modal-id').value = r.id;
  4959. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4960. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4961. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4962. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4963. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4964. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4965. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4966. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4967. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4968. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4969. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4970. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4971. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4972. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4973. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4974. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4975. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4976. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4977. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4978. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4979. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4980. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4981. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4982. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4983. setMangleFieldVal('src', r.src_address, true);
  4984. setMangleFieldVal('dst', r.dst_address, true);
  4985. setMangleFieldVal('srclist', r.src_address_list, true);
  4986. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4987. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4988. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4989. if (r.protocol && r.protocol !== 'all') {
  4990. setMangleFieldVal('proto', r.protocol, true);
  4991. } else {
  4992. toggleMangleField('proto', false);
  4993. }
  4994. setMangleFieldVal('sport', r.src_port, true);
  4995. setMangleFieldVal('dport', r.dst_port, true);
  4996. setMangleFieldVal('anyport', r.any_port, true);
  4997. setMangleFieldVal('iniface', r.in_interface, true);
  4998. setMangleFieldVal('outiface', r.out_interface, true);
  4999. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5000. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5001. setMangleFieldVal('pktmark', r.packet_mark, true);
  5002. setMangleFieldVal('connmark', r.connection_mark, true);
  5003. setMangleFieldVal('routingmark', r.routing_mark, true);
  5004. setMangleFieldVal('conntype', r.connection_type, false);
  5005. // Connection State
  5006. const states = r.connection_state || [];
  5007. if (states.length > 0) {
  5008. toggleMangleField('cs', true);
  5009. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5010. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5011. if (el) el.checked = states.includes(s);
  5012. });
  5013. } else {
  5014. toggleMangleField('cs', false);
  5015. }
  5016. // Connection NAT State
  5017. const natStates = r.connection_nat_state || [];
  5018. if (natStates.length > 0) {
  5019. toggleMangleField('natstate', true);
  5020. ['srcnat', 'dstnat'].forEach(s => {
  5021. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5022. if (el) el.checked = natStates.includes(s);
  5023. });
  5024. } else {
  5025. toggleMangleField('natstate', false);
  5026. }
  5027. // Advanced tab fields
  5028. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5029. setMangleFieldVal('content', r.content, false);
  5030. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5031. setMangleFieldVal('connrate', r.connection_rate, false);
  5032. setMangleFieldVal('pcc', r.pcc, false);
  5033. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5034. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5035. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5036. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5037. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5038. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5039. setMangleFieldVal('tlshost', r.tls_host, false);
  5040. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5041. setMangleFieldVal('priority', r.priority, false);
  5042. setMangleFieldVal('dscp', r.dscp, false);
  5043. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5044. if (r.tos) {
  5045. const tosEl = document.getElementById('mangle-val-tos');
  5046. if (tosEl) tosEl.value = r.tos;
  5047. }
  5048. setMangleFieldVal('pktsize', r.packet_size, false);
  5049. setMangleFieldVal('random', r.random, false);
  5050. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5051. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5052. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5053. setMangleFieldVal('ttl', r.ttl, false);
  5054. // Extra tab fields
  5055. setMangleFieldVal('nth', r.nth, false);
  5056. setMangleFieldVal('connlimit', r.connection_limit, false);
  5057. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5058. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5059. setMangleFieldVal('hotspot', r.hotspot, false);
  5060. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5061. setMangleFieldVal('limit', r.limit, false);
  5062. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5063. setMangleFieldVal('time', r.time, false);
  5064. setMangleFieldVal('psd', r.psd, false);
  5065. // Action fields
  5066. if (r.jump_target) {
  5067. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5068. if (jtEl) jtEl.value = r.jump_target;
  5069. }
  5070. if (r.address_list) {
  5071. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5072. if (alEl) alEl.value = r.address_list;
  5073. }
  5074. if (r.address_list_timeout) {
  5075. const toEl = document.getElementById('mangle-modal-action-timeout');
  5076. if (toEl) toEl.value = r.address_list_timeout;
  5077. }
  5078. setMangleFieldVal('logprefix', r.log_prefix, false);
  5079. // Statistics
  5080. const bEl = document.getElementById('mangle-stat-bytes');
  5081. const pEl = document.getElementById('mangle-stat-packets');
  5082. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5083. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5084. state.mangleLastBytes = r.bytes || 0;
  5085. state.mangleLastPackets = r.packets || 0;
  5086. state.mangleLastTimestamp = Date.now();
  5087. state.mangleStatRateHistory = new Array(30).fill(0);
  5088. state.mangleStatPktHistory = new Array(30).fill(0);
  5089. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5090. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5091. toggleMangleActionFields();
  5092. document.getElementById('mangle-modal').classList.remove('hidden');
  5093. }
  5094. function closeMangleModal() {
  5095. stopMangleStatPolling();
  5096. document.getElementById('mangle-modal').classList.add('hidden');
  5097. }
  5098. function copyMangleRule() {
  5099. document.getElementById('mangle-modal-id').value = '';
  5100. const badge = document.getElementById('mangle-modal-badge');
  5101. if (badge) badge.innerText = 'New...';
  5102. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5103. }
  5104. function resetCurrentMangleRuleCounters() {
  5105. state.mangleStatRateHistory = new Array(30).fill(0);
  5106. state.mangleStatPktHistory = new Array(30).fill(0);
  5107. state.mangleLastBytes = 0;
  5108. state.mangleLastPackets = 0;
  5109. state.mangleLastTimestamp = Date.now();
  5110. const bEl = document.getElementById('mangle-stat-bytes');
  5111. const pEl = document.getElementById('mangle-stat-packets');
  5112. const rEl = document.getElementById('mangle-stat-rate');
  5113. const prEl = document.getElementById('mangle-stat-pktrate');
  5114. if (bEl) bEl.value = '0 B';
  5115. if (pEl) pEl.value = '0';
  5116. if (rEl) rEl.value = '0 bps';
  5117. if (prEl) prEl.value = '0 p/s';
  5118. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5119. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5120. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5121. }
  5122. async function applyMangleRule(closeAfter = false) {
  5123. const id = document.getElementById('mangle-modal-id').value;
  5124. const chain = document.getElementById('mangle-modal-chain').value;
  5125. const action = document.getElementById('mangle-modal-action').value;
  5126. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5127. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5128. const src = getMangleFieldVal('src', true);
  5129. const dst = getMangleFieldVal('dst', true);
  5130. const srclist = getMangleFieldVal('srclist', true);
  5131. const dstlist = getMangleFieldVal('dstlist', true);
  5132. const srcgeo = getMangleFieldVal('srcgeo', true);
  5133. const dstgeo = getMangleFieldVal('dstgeo', true);
  5134. const proto = getMangleFieldVal('proto', true);
  5135. const sport = getMangleFieldVal('sport', true);
  5136. const dport = getMangleFieldVal('dport', true);
  5137. const anyport = getMangleFieldVal('anyport', true);
  5138. const iniface = getMangleFieldVal('iniface', true);
  5139. const outiface = getMangleFieldVal('outiface', true);
  5140. const inifacelist = getMangleFieldVal('inifacelist', true);
  5141. const outifacelist = getMangleFieldVal('outifacelist', true);
  5142. const pktmark = getMangleFieldVal('pktmark', true);
  5143. const connmark = getMangleFieldVal('connmark', true);
  5144. const routingmark = getMangleFieldVal('routingmark', true);
  5145. const conntype = getMangleFieldVal('conntype', false);
  5146. const states = [];
  5147. const csBox = document.getElementById('mangle-field-cs');
  5148. if (csBox && !csBox.classList.contains('hidden')) {
  5149. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5150. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5151. });
  5152. }
  5153. const natStates = [];
  5154. const natBox = document.getElementById('mangle-field-natstate');
  5155. if (natBox && !natBox.classList.contains('hidden')) {
  5156. ['srcnat', 'dstnat'].forEach(s => {
  5157. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5158. });
  5159. }
  5160. const payload = {
  5161. id,
  5162. chain,
  5163. action,
  5164. protocol: proto || 'all',
  5165. src_address: src,
  5166. dst_address: dst,
  5167. src_port: sport,
  5168. dst_port: dport,
  5169. any_port: anyport,
  5170. in_interface: iniface,
  5171. out_interface: outiface,
  5172. in_interface_list: inifacelist,
  5173. out_interface_list: outifacelist,
  5174. packet_mark: pktmark,
  5175. connection_mark: connmark,
  5176. routing_mark: routingmark,
  5177. connection_type: conntype,
  5178. connection_state: states,
  5179. connection_nat_state: natStates,
  5180. src_address_list: srclist,
  5181. dst_address_list: dstlist,
  5182. src_geoip: srcgeo,
  5183. dst_geoip: dstgeo,
  5184. comment,
  5185. disabled: !enabled,
  5186. // Advanced tab
  5187. layer7_protocol: getMangleFieldVal('layer7', false),
  5188. content: getMangleFieldVal('content', false),
  5189. connection_bytes: getMangleFieldVal('connbytes', false),
  5190. connection_rate: getMangleFieldVal('connrate', false),
  5191. pcc: getMangleFieldVal('pcc', false),
  5192. src_mac_address: getMangleFieldVal('srcmac', true),
  5193. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5194. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5195. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5196. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5197. ipsec_policy: getMangleFieldVal('ipsec', false),
  5198. tls_host: getMangleFieldVal('tlshost', false),
  5199. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5200. priority: getMangleFieldVal('priority', false),
  5201. dscp: getMangleFieldVal('dscp', false),
  5202. tcp_mss: getMangleFieldVal('tcpmss', false),
  5203. tos: document.getElementById('mangle-val-tos')?.value || '',
  5204. packet_size: getMangleFieldVal('pktsize', false),
  5205. random: getMangleFieldVal('random', false),
  5206. tcp_flags: getMangleFieldVal('tcpflags', false),
  5207. icmp_options: getMangleFieldVal('icmpoptions', false),
  5208. ipv4_options: getMangleFieldVal('ipv4options', false),
  5209. ttl: getMangleFieldVal('ttl', false),
  5210. // Extra tab
  5211. nth: getMangleFieldVal('nth', false),
  5212. connection_limit: getMangleFieldVal('connlimit', false),
  5213. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5214. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5215. hotspot: getMangleFieldVal('hotspot', false),
  5216. ip_fragment: getMangleFieldVal('ipfragment', false),
  5217. limit: getMangleFieldVal('limit', false),
  5218. dst_limit: getMangleFieldVal('dstlimit', false),
  5219. time: getMangleFieldVal('time', false),
  5220. psd: getMangleFieldVal('psd', false),
  5221. // Action tab
  5222. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5223. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5224. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5225. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5226. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5227. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5228. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5229. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5230. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5231. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5232. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5233. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5234. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5235. log: document.getElementById('mangle-modal-log')?.checked || false,
  5236. log_prefix: getMangleFieldVal('logprefix', false)
  5237. };
  5238. try {
  5239. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5240. method: 'POST',
  5241. headers: { 'Content-Type': 'application/json' },
  5242. body: JSON.stringify(payload)
  5243. });
  5244. if (res.ok) {
  5245. const data = await res.json();
  5246. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5247. loadFirewall(false);
  5248. if (closeAfter) {
  5249. closeMangleModal();
  5250. } else {
  5251. if (data.id) {
  5252. document.getElementById('mangle-modal-id').value = data.id;
  5253. const badge = document.getElementById('mangle-modal-badge');
  5254. if (badge) badge.innerText = `#${data.id}`;
  5255. }
  5256. }
  5257. } else {
  5258. const err = await res.json();
  5259. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5260. }
  5261. } catch (err) {
  5262. showToast('Error', err.message, 'error');
  5263. }
  5264. }
  5265. function submitSaveMangleRule(e) {
  5266. if (e && e.preventDefault) e.preventDefault();
  5267. return applyMangleRule(true);
  5268. }
  5269. function startMangleStatPolling() {
  5270. stopMangleStatPolling();
  5271. pollMangleRuleStats();
  5272. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5273. }
  5274. function stopMangleStatPolling() {
  5275. if (state.mangleStatInterval) {
  5276. clearInterval(state.mangleStatInterval);
  5277. state.mangleStatInterval = null;
  5278. }
  5279. }
  5280. async function pollMangleRuleStats() {
  5281. const id = document.getElementById('mangle-modal-id')?.value;
  5282. if (!id) {
  5283. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5284. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5285. return;
  5286. }
  5287. try {
  5288. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5289. if (!res.ok) return;
  5290. const rules = await res.json();
  5291. const r = rules.find(x => x.id === id);
  5292. if (!r) return;
  5293. const now = Date.now();
  5294. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5295. state.mangleLastTimestamp = now;
  5296. const curBytes = r.bytes || 0;
  5297. const curPackets = r.packets || 0;
  5298. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5299. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5300. state.mangleLastBytes = curBytes;
  5301. state.mangleLastPackets = curPackets;
  5302. const rateBps = Math.round((deltaBytes * 8) / dt);
  5303. const ratePkt = Math.round(deltaPkts / dt);
  5304. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5305. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5306. state.mangleStatRateHistory.push(rateBps);
  5307. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5308. state.mangleStatPktHistory.push(ratePkt);
  5309. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5310. const bEl = document.getElementById('mangle-stat-bytes');
  5311. const pEl = document.getElementById('mangle-stat-packets');
  5312. const rEl = document.getElementById('mangle-stat-rate');
  5313. const prEl = document.getElementById('mangle-stat-pktrate');
  5314. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5315. if (pEl) pEl.value = curPackets.toLocaleString();
  5316. if (rEl) rEl.value = formatBps(rateBps);
  5317. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5318. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5319. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5320. } catch (e) {
  5321. console.error('Error polling Mangle rule stats', e);
  5322. }
  5323. }
  5324. async function moveMangleRule(id, dir) {
  5325. try {
  5326. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5327. method: 'POST',
  5328. headers: { 'Content-Type': 'application/json' },
  5329. body: JSON.stringify({ direction: dir })
  5330. });
  5331. if (res.ok) loadFirewall(false);
  5332. } catch (err) {
  5333. showToast('Error', err.message, 'error');
  5334. }
  5335. }
  5336. async function toggleMangleRuleState(id, disabled) {
  5337. try {
  5338. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5339. method: 'POST',
  5340. headers: { 'Content-Type': 'application/json' },
  5341. body: JSON.stringify({ disabled })
  5342. });
  5343. if (res.ok) loadFirewall(false);
  5344. } catch (err) {
  5345. showToast('Error', err.message, 'error');
  5346. }
  5347. }
  5348. async function deleteMangleRule(id) {
  5349. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5350. try {
  5351. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5352. if (res.ok) {
  5353. showToast('Deleted', 'Mangle rule removed', 'success');
  5354. loadFirewall(false);
  5355. }
  5356. } catch (err) {
  5357. showToast('Error', err.message, 'error');
  5358. }
  5359. }
  5360. // ----------------- Address Lists -----------------
  5361. function renderAddressLists() {
  5362. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5363. const tbody = document.getElementById('addrlist-table-body');
  5364. const empty = document.getElementById('addrlist-empty');
  5365. if (!tbody) return;
  5366. tbody.innerHTML = '';
  5367. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5368. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5369. // Update filter select
  5370. const sel = document.getElementById('addrlist-filter-name');
  5371. if (sel) {
  5372. const cur = sel.value;
  5373. sel.innerHTML = '<option value="">All Lists</option>';
  5374. const set = new Set((state.addressLists || []).map(a => a.name));
  5375. set.forEach(n => {
  5376. const opt = document.createElement('option');
  5377. opt.value = n;
  5378. opt.innerText = n;
  5379. if (n === cur) opt.selected = true;
  5380. sel.appendChild(opt);
  5381. });
  5382. }
  5383. if (entries.length === 0) {
  5384. empty?.classList.remove('hidden');
  5385. return;
  5386. }
  5387. empty?.classList.add('hidden');
  5388. entries.forEach((e, idx) => {
  5389. const tr = document.createElement('tr');
  5390. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5391. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5392. tr.innerHTML = `
  5393. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5394. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  5395. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5396. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5397. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5398. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5399. <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  5400. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5401. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5402. </td>
  5403. `;
  5404. tbody.appendChild(tr);
  5405. });
  5406. populateCommonAddrListDatalist();
  5407. }
  5408. function openAddAddrListModal() {
  5409. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5410. document.getElementById('addrlist-modal-id').value = '';
  5411. document.getElementById('addrlist-modal-name').value = '';
  5412. document.getElementById('addrlist-modal-addr').value = '';
  5413. document.getElementById('addrlist-modal-comment').value = '';
  5414. document.getElementById('addrlist-modal-disabled').checked = false;
  5415. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5416. if (submitBtn) submitBtn.innerText = 'Add to List';
  5417. document.getElementById('addrlist-modal').classList.remove('hidden');
  5418. }
  5419. function openEditAddrListModal(id) {
  5420. const e = (state.addressLists || []).find(item => item.id === id);
  5421. if (!e) return;
  5422. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5423. document.getElementById('addrlist-modal-id').value = e.id;
  5424. document.getElementById('addrlist-modal-name').value = e.name;
  5425. document.getElementById('addrlist-modal-addr').value = e.address;
  5426. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5427. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5428. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5429. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5430. document.getElementById('addrlist-modal').classList.remove('hidden');
  5431. }
  5432. function closeAddrListModal() {
  5433. document.getElementById('addrlist-modal').classList.add('hidden');
  5434. }
  5435. async function submitSaveAddrList(e) {
  5436. e.preventDefault();
  5437. const id = document.getElementById('addrlist-modal-id').value;
  5438. const name = document.getElementById('addrlist-modal-name').value.trim();
  5439. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5440. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5441. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5442. try {
  5443. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5444. method: 'POST',
  5445. headers: { 'Content-Type': 'application/json' },
  5446. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5447. });
  5448. if (res.ok) {
  5449. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5450. closeAddrListModal();
  5451. loadFirewall(false);
  5452. } else {
  5453. const err = await res.json();
  5454. showToast('Error', err.message || 'Failed to save address list', 'error');
  5455. }
  5456. } catch (err) {
  5457. showToast('Error', err.message, 'error');
  5458. }
  5459. }
  5460. async function toggleAddrListState(id, disabled) {
  5461. try {
  5462. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5463. method: 'POST',
  5464. headers: { 'Content-Type': 'application/json' },
  5465. body: JSON.stringify({ disabled })
  5466. });
  5467. if (res.ok) {
  5468. loadFirewall(false);
  5469. }
  5470. } catch (err) {
  5471. showToast('Error', err.message, 'error');
  5472. }
  5473. }
  5474. async function deleteAddrList(id) {
  5475. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5476. try {
  5477. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5478. if (res.ok) {
  5479. showToast('Deleted', 'Address list item removed', 'info');
  5480. loadFirewall(false);
  5481. }
  5482. } catch (err) {
  5483. showToast('Error', err.message, 'error');
  5484. }
  5485. }
  5486. // ----------------- Geo-Location IP Management -----------------
  5487. async function loadGeoIP() {
  5488. try {
  5489. const [statusRes, countriesRes] = await Promise.all([
  5490. fetch(`${API_BASE}/firewall/geoip/status`),
  5491. fetch(`${API_BASE}/firewall/geoip/countries`)
  5492. ]);
  5493. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5494. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5495. updateGeoHeader();
  5496. renderGeoCountries();
  5497. } catch (err) {
  5498. console.error('Failed to load GeoIP:', err);
  5499. }
  5500. }
  5501. function getGeoUsageMap() {
  5502. const usage = {};
  5503. const checkRule = (r, type) => {
  5504. ['src_geoip', 'dst_geoip'].forEach(field => {
  5505. let val = (r && r[field]) || '';
  5506. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5507. if (code) {
  5508. if (!usage[code]) usage[code] = [];
  5509. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5510. if (!usage[code].includes(label)) usage[code].push(label);
  5511. }
  5512. });
  5513. };
  5514. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5515. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5516. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5517. return usage;
  5518. }
  5519. function updateGeoHeader() {
  5520. const s = state.geoStatus || {};
  5521. const statusBadge = document.getElementById('geo-status-badge');
  5522. if (statusBadge) {
  5523. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5524. statusBadge.className = s.auto_update
  5525. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5526. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5527. }
  5528. const intervalLabel = document.getElementById('geo-interval-label');
  5529. if (intervalLabel) {
  5530. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5531. }
  5532. const usageMap = getGeoUsageMap();
  5533. const inUseCount = Object.keys(usageMap).length;
  5534. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5535. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5536. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5537. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5538. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5539. if (lastSyncEl) {
  5540. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5541. const d = new Date(s.last_updated);
  5542. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5543. } else {
  5544. lastSyncEl.innerText = 'Never (Sync Pending)';
  5545. }
  5546. }
  5547. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5548. if (nextSyncEl) {
  5549. if (s.next_update && !s.next_update.startsWith('0001')) {
  5550. const d = new Date(s.next_update);
  5551. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5552. } else {
  5553. nextSyncEl.innerText = '-';
  5554. }
  5555. }
  5556. const badge = document.getElementById('fw-badge-geo');
  5557. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5558. }
  5559. function renderGeoCountries() {
  5560. const tbody = document.getElementById('geo-table-body');
  5561. const empty = document.getElementById('geo-empty');
  5562. if (!tbody) return;
  5563. tbody.innerHTML = '';
  5564. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5565. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5566. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5567. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5568. const usageMap = getGeoUsageMap();
  5569. const countries = (state.geoCountries || []).filter(c => {
  5570. const isUsed = !!usageMap[c.code];
  5571. if (inUseOnly && !isUsed) return false;
  5572. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5573. if (continent && c.continent !== continent) return false;
  5574. if (q) {
  5575. const matchCode = c.code.toLowerCase().includes(q);
  5576. const matchName = c.name.toLowerCase().includes(q);
  5577. if (!matchCode && !matchName) return false;
  5578. }
  5579. return true;
  5580. });
  5581. if (countries.length === 0) {
  5582. empty?.classList.remove('hidden');
  5583. return;
  5584. }
  5585. empty?.classList.add('hidden');
  5586. countries.forEach(c => {
  5587. const tr = document.createElement('tr');
  5588. const isUsed = !!usageMap[c.code];
  5589. const rulesUsing = usageMap[c.code] || [];
  5590. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5591. let statusHtml = '';
  5592. if (isUsed) {
  5593. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  5594. } else if (c.subnet_count > 0) {
  5595. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  5596. } else {
  5597. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5598. }
  5599. tr.innerHTML = `
  5600. <td class="py-2.5 px-3 text-center">
  5601. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  5602. ${c.code}
  5603. </span>
  5604. </td>
  5605. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5606. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5607. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5608. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5609. </td>
  5610. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5611. <td class="py-2.5 px-3">
  5612. ${statusHtml}
  5613. </td>
  5614. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5615. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  5616. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5617. </td>
  5618. `;
  5619. tbody.appendChild(tr);
  5620. });
  5621. }
  5622. function quickFilterGeo(preset) {
  5623. const searchInput = document.getElementById('geo-search-input');
  5624. const continentSel = document.getElementById('geo-continent-filter');
  5625. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5626. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5627. if (searchInput) searchInput.value = '';
  5628. if (continentSel) continentSel.value = '';
  5629. if (inUseCheck) inUseCheck.checked = false;
  5630. if (cachedCheck) cachedCheck.checked = false;
  5631. if (preset === 'GR') {
  5632. if (searchInput) searchInput.value = 'Greece';
  5633. } else if (preset === 'Europe') {
  5634. if (continentSel) continentSel.value = 'Europe';
  5635. } else if (preset === 'HIGHRISK') {
  5636. if (searchInput) searchInput.value = 'China';
  5637. }
  5638. renderGeoCountries();
  5639. }
  5640. async function toggleGeoCountry(code, enabled) {
  5641. try {
  5642. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5643. method: 'POST',
  5644. headers: { 'Content-Type': 'application/json' },
  5645. body: JSON.stringify({ enabled })
  5646. });
  5647. if (res.ok) {
  5648. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5649. loadGeoIP();
  5650. } else {
  5651. const err = await res.json();
  5652. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5653. }
  5654. } catch (err) {
  5655. showToast('Error', err.message, 'error');
  5656. }
  5657. }
  5658. async function updateGeoCountry(code) {
  5659. try {
  5660. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5661. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5662. if (res.ok) {
  5663. const data = await res.json();
  5664. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5665. loadGeoIP();
  5666. } else {
  5667. const err = await res.json();
  5668. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5669. }
  5670. } catch (err) {
  5671. showToast('Error', err.message, 'error');
  5672. }
  5673. }
  5674. async function triggerGeoUpdateNow() {
  5675. const spinner = document.getElementById('geo-update-spinner');
  5676. if (spinner) spinner.classList.remove('hidden');
  5677. try {
  5678. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5679. if (res.ok) {
  5680. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5681. setTimeout(() => {
  5682. loadGeoIP();
  5683. if (spinner) spinner.classList.add('hidden');
  5684. }, 2500);
  5685. } else {
  5686. const err = await res.json();
  5687. showToast('Notice', err.message || 'Update in progress', 'info');
  5688. if (spinner) spinner.classList.add('hidden');
  5689. }
  5690. } catch (err) {
  5691. showToast('Error', err.message, 'error');
  5692. if (spinner) spinner.classList.add('hidden');
  5693. }
  5694. }
  5695. async function applyGeoPreset(preset) {
  5696. try {
  5697. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5698. method: 'POST',
  5699. headers: { 'Content-Type': 'application/json' },
  5700. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5701. });
  5702. if (res.ok) {
  5703. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5704. loadGeoIP();
  5705. }
  5706. } catch (err) {
  5707. showToast('Error', err.message, 'error');
  5708. }
  5709. }
  5710. function openGeoIntervalModal() {
  5711. const s = state.geoStatus || {};
  5712. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5713. const sel = document.getElementById('geo-cfg-interval');
  5714. const customBox = document.getElementById('geo-cfg-custom-box');
  5715. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5716. const curHours = s.interval_hours || 24;
  5717. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5718. if (matchOption) {
  5719. sel.value = String(curHours);
  5720. customBox.classList.add('hidden');
  5721. } else {
  5722. sel.value = 'custom';
  5723. customHoursInput.value = curHours;
  5724. customBox.classList.remove('hidden');
  5725. }
  5726. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5727. }
  5728. function closeGeoIntervalModal() {
  5729. document.getElementById('geo-interval-modal').classList.add('hidden');
  5730. }
  5731. function toggleCustomGeoInterval() {
  5732. const val = document.getElementById('geo-cfg-interval').value;
  5733. const customBox = document.getElementById('geo-cfg-custom-box');
  5734. if (val === 'custom') {
  5735. customBox.classList.remove('hidden');
  5736. } else {
  5737. customBox.classList.add('hidden');
  5738. }
  5739. }
  5740. async function submitGeoIntervalSettings(e) {
  5741. e.preventDefault();
  5742. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5743. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5744. let hours = 24;
  5745. if (intervalVal === 'custom') {
  5746. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5747. } else {
  5748. hours = parseInt(intervalVal, 10) || 24;
  5749. }
  5750. try {
  5751. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5752. method: 'POST',
  5753. headers: { 'Content-Type': 'application/json' },
  5754. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5755. });
  5756. if (res.ok) {
  5757. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5758. closeGeoIntervalModal();
  5759. loadGeoIP();
  5760. } else {
  5761. const err = await res.json();
  5762. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5763. }
  5764. } catch (err) {
  5765. showToast('Error', err.message, 'error');
  5766. }
  5767. }
  5768. async function viewGeoSubnets(code, name) {
  5769. if (!name) {
  5770. const found = (state.geoCountries || []).find(x => x.code === code);
  5771. name = found ? found.name : code;
  5772. }
  5773. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5774. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5775. const listEl = document.getElementById('geo-subnets-list');
  5776. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5777. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5778. try {
  5779. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5780. if (res.ok) {
  5781. const data = await res.json();
  5782. const subnets = data.subnets || [];
  5783. if (subnets.length === 0) {
  5784. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5785. } else {
  5786. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5787. }
  5788. } else {
  5789. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5790. }
  5791. } catch (err) {
  5792. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5793. }
  5794. }
  5795. function closeGeoSubnetsModal() {
  5796. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5797. }
  5798. // ----------------- Active Connections Tracking -----------------
  5799. async function loadConnections() {
  5800. try {
  5801. const res = await fetch(`${API_BASE}/firewall/connections`);
  5802. const data = await res.json();
  5803. state.connections = Array.isArray(data) ? data : [];
  5804. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5805. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5806. renderConnections();
  5807. } catch (err) {
  5808. console.error('Failed to load connections:', err);
  5809. }
  5810. }
  5811. function renderConnections() {
  5812. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5813. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5814. const tbody = document.getElementById('conns-table-body');
  5815. const empty = document.getElementById('conns-empty');
  5816. if (!tbody) return;
  5817. tbody.innerHTML = '';
  5818. const conns = (state.connections || []).filter(c => {
  5819. if (protoFilter && c.protocol !== protoFilter) return false;
  5820. if (search) {
  5821. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5822. if (!line.includes(search)) return false;
  5823. }
  5824. return true;
  5825. });
  5826. if (conns.length === 0) {
  5827. empty?.classList.remove('hidden');
  5828. return;
  5829. }
  5830. empty?.classList.add('hidden');
  5831. conns.slice(0, 150).forEach(c => {
  5832. const tr = document.createElement('tr');
  5833. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5834. let stateColor = 'text-slate-400';
  5835. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5836. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5837. tr.innerHTML = `
  5838. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5839. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5840. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5841. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  5842. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  5843. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5844. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5845. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function killConnection(protocol, src, sport, dst, dport) {
  5854. try {
  5855. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5856. method: 'POST',
  5857. headers: { 'Content-Type': 'application/json' },
  5858. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5859. });
  5860. if (res.ok) {
  5861. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5862. loadConnections();
  5863. }
  5864. } catch (err) {
  5865. showToast('Error', err.message, 'error');
  5866. }
  5867. }
  5868. async function resetFirewallCounters() {
  5869. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5870. try {
  5871. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5872. if (res.ok) {
  5873. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5874. loadFirewall(false);
  5875. }
  5876. } catch (err) {
  5877. showToast('Error', err.message, 'error');
  5878. }
  5879. }
  5880. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5881. function switchRoutesSubTab(tab) {
  5882. state.routesSubTab = tab;
  5883. const tabs = ['routes', 'rules', 'tables'];
  5884. tabs.forEach(t => {
  5885. const panel = document.getElementById(`routes-subtab-${t}`);
  5886. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5887. if (panel) {
  5888. if (t === tab) panel.classList.remove('hidden');
  5889. else panel.classList.add('hidden');
  5890. }
  5891. if (btn) {
  5892. if (t === tab) {
  5893. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  5894. } else {
  5895. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  5896. }
  5897. }
  5898. });
  5899. setTimeout(initTableSorting, 50);
  5900. }
  5901. async function loadRoutes() {
  5902. try {
  5903. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5904. fetch(`${API_BASE}/routes`),
  5905. fetch(`${API_BASE}/routing/rules`),
  5906. fetch(`${API_BASE}/routing/tables`)
  5907. ]);
  5908. if (routesRes.ok) state.routes = await routesRes.json();
  5909. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5910. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5911. const bRoutes = document.getElementById('routes-badge-routes');
  5912. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5913. const showSystem = document.getElementById('prule-show-system')?.checked;
  5914. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5915. const bRules = document.getElementById('routes-badge-rules');
  5916. if (bRules) bRules.innerText = userRules.length;
  5917. const bTables = document.getElementById('routes-badge-tables');
  5918. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5919. const bRoutesCount = document.getElementById('badge-routes-count');
  5920. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5921. renderRoutesList();
  5922. renderPolicyRules();
  5923. renderRoutingTables();
  5924. } catch (err) {
  5925. console.error('Failed to load routing:', err);
  5926. }
  5927. }
  5928. function getRouteProtocolBadge(proto) {
  5929. const p = (proto || 'static').toLowerCase();
  5930. switch (p) {
  5931. case 'bgp':
  5932. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  5933. case 'ibgp':
  5934. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  5935. case 'ospf':
  5936. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  5937. case 'rip':
  5938. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  5939. case 'static':
  5940. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  5941. case 'connected':
  5942. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  5943. case 'dhcp':
  5944. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  5945. case 'multicast':
  5946. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  5947. default:
  5948. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  5949. }
  5950. }
  5951. function renderRoutesList() {
  5952. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5953. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5954. const tbody = document.getElementById('routes-table-body');
  5955. const empty = document.getElementById('routes-empty');
  5956. if (!tbody) return;
  5957. // Update table filter select
  5958. const sel = document.getElementById('routes-filter-table');
  5959. if (sel) {
  5960. const cur = sel.value;
  5961. sel.innerHTML = '<option value="">All Tables</option>';
  5962. (state.routingTables || []).forEach(t => {
  5963. const opt = document.createElement('option');
  5964. opt.value = t.name;
  5965. opt.innerText = t.name;
  5966. if (t.name === cur) opt.selected = true;
  5967. sel.appendChild(opt);
  5968. });
  5969. }
  5970. const routes = (state.routes || []).filter(r => {
  5971. if (tableFilter && r.routing_table !== tableFilter) return false;
  5972. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5973. if (typeFilter === 'multicast' && !r.multicast) return false;
  5974. if (typeFilter === 'static' && !r.static) return false;
  5975. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5976. if (typeFilter === 'connected' && !r.connect) return false;
  5977. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5978. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5979. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5980. return true;
  5981. });
  5982. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5983. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5984. let summaryText = `${routes.length} Routes`;
  5985. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5986. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5987. const badgeEl = document.getElementById('routes-count-badge');
  5988. if (badgeEl) badgeEl.innerText = summaryText;
  5989. if (routes.length === 0) {
  5990. empty?.classList.remove('hidden');
  5991. tbody.innerHTML = '';
  5992. return;
  5993. }
  5994. empty?.classList.add('hidden');
  5995. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  5996. if (tbody.dataset.sig === sig) {
  5997. return; // Routes table unchanged! Do not wipe DOM or flicker!
  5998. }
  5999. tbody.dataset.sig = sig;
  6000. tbody.innerHTML = '';
  6001. routes.forEach(r => {
  6002. const tr = document.createElement('tr');
  6003. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6004. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6005. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6006. let flags = '';
  6007. if (r.dynamic) flags += 'D';
  6008. if (r.active) flags += 'A';
  6009. if (r.connect) flags += 'C';
  6010. if (r.static) flags += 'S';
  6011. if (r.ecmp) flags += 'E';
  6012. if (r.multicast) flags += 'M';
  6013. if (r.disabled) flags += 'X';
  6014. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6015. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6016. if (r.check_gateway === 'internet') {
  6017. if (r.health_status === 'online') {
  6018. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6019. healthCell = `
  6020. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  6021. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6022. <span>Internet OK (${ms}ms)</span>
  6023. </span>
  6024. `;
  6025. } else if (r.health_status === 'offline') {
  6026. healthCell = `
  6027. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  6028. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6029. <span>Internet Down</span>
  6030. </span>
  6031. `;
  6032. } else {
  6033. healthCell = `
  6034. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6035. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6036. <span>Checking...</span>
  6037. </span>
  6038. `;
  6039. }
  6040. } else if (r.check_gateway === 'ping') {
  6041. if (r.health_status === 'online') {
  6042. healthCell = `
  6043. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6044. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6045. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6046. </span>
  6047. `;
  6048. } else if (r.health_status === 'offline') {
  6049. healthCell = `
  6050. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6051. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6052. <span>Gateway Dead</span>
  6053. </span>
  6054. `;
  6055. }
  6056. }
  6057. const flagDescriptions = [];
  6058. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6059. if (r.active) flagDescriptions.push('Active (A)');
  6060. if (r.connect) flagDescriptions.push('Connected (C)');
  6061. if (r.static) flagDescriptions.push('Static (S)');
  6062. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6063. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6064. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6065. tr.innerHTML = `
  6066. <td class="py-2.5 px-3 text-center">
  6067. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6068. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6069. }" title="Flags: ${flagDescriptions.join(', ')}">
  6070. ${flags || '-'}
  6071. </span>
  6072. </td>
  6073. <td class="py-2.5 px-3">
  6074. <div class="flex items-center gap-1.5 flex-wrap">
  6075. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6076. ${r.ecmp ? `
  6077. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6078. <span>⚡ ECMP</span>
  6079. </span>
  6080. ` : ''}
  6081. ${r.multicast ? `
  6082. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6083. <span>IGMP</span>
  6084. </span>
  6085. ` : ''}
  6086. </div>
  6087. </td>
  6088. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6089. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  6090. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6091. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6092. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6093. <td class="py-2.5 px-3">${healthCell}</td>
  6094. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6095. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6096. ${r.static ? `
  6097. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  6098. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6099. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6100. ` : `
  6101. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6102. `}
  6103. </td>
  6104. `;
  6105. tbody.appendChild(tr);
  6106. });
  6107. }
  6108. function openAddRouteModal() {
  6109. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6110. document.getElementById('route-modal-id').value = '';
  6111. document.getElementById('route-modal-old-dst').value = '';
  6112. document.getElementById('route-modal-old-gw').value = '';
  6113. document.getElementById('route-modal-old-distance').value = '';
  6114. document.getElementById('route-modal-old-table').value = '';
  6115. document.getElementById('route-modal-old-iface').value = '';
  6116. const dstInput = document.getElementById('route-modal-dst');
  6117. const gwInput = document.getElementById('route-modal-gw');
  6118. const distInput = document.getElementById('route-modal-distance');
  6119. const ifaceSelect = document.getElementById('route-modal-iface');
  6120. const tableSelect = document.getElementById('route-modal-table');
  6121. const commentInput = document.getElementById('route-modal-comment');
  6122. const disCheck = document.getElementById('route-modal-disabled');
  6123. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6124. dstInput.disabled = false;
  6125. dstInput.value = '0.0.0.0/0';
  6126. gwInput.disabled = false;
  6127. gwInput.value = '';
  6128. distInput.disabled = false;
  6129. distInput.value = '1';
  6130. ifaceSelect.disabled = false;
  6131. tableSelect.disabled = false;
  6132. commentInput.disabled = false;
  6133. commentInput.value = '';
  6134. disCheck.disabled = false;
  6135. disCheck.checked = false;
  6136. if (saveBtn) saveBtn.classList.remove('hidden');
  6137. const checkGw = document.getElementById('route-modal-check-gw');
  6138. if (checkGw) checkGw.value = 'internet';
  6139. const checkTarget = document.getElementById('route-modal-check-target');
  6140. if (checkTarget) checkTarget.value = '1.1.1.1';
  6141. const checkInterval = document.getElementById('route-modal-check-interval');
  6142. if (checkInterval) checkInterval.value = '5';
  6143. const checkThresh = document.getElementById('route-modal-check-threshold');
  6144. if (checkThresh) checkThresh.value = '3';
  6145. toggleRouteCheckModeUI();
  6146. populateInterfaceSelect('route-modal-iface');
  6147. // Populate tables
  6148. tableSelect.innerHTML = '';
  6149. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6150. const opt = document.createElement('option');
  6151. opt.value = t.name;
  6152. opt.innerText = t.name;
  6153. if (t.name === 'main') opt.selected = true;
  6154. tableSelect.appendChild(opt);
  6155. });
  6156. document.getElementById('route-modal').classList.remove('hidden');
  6157. }
  6158. function openEditRouteModal(id) {
  6159. const r = (state.routes || []).find(route => route.id === id);
  6160. if (!r) return;
  6161. const isStatic = !!r.static;
  6162. document.getElementById('route-modal-title').innerText = isStatic
  6163. ? `Edit Route: ${r.dst_address}`
  6164. : `Route Properties (Read Only): ${r.dst_address}`;
  6165. document.getElementById('route-modal-id').value = r.id;
  6166. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6167. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6168. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6169. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6170. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6171. const dstInput = document.getElementById('route-modal-dst');
  6172. const gwInput = document.getElementById('route-modal-gw');
  6173. const distInput = document.getElementById('route-modal-distance');
  6174. const ifaceSelect = document.getElementById('route-modal-iface');
  6175. const tableSelect = document.getElementById('route-modal-table');
  6176. const commentInput = document.getElementById('route-modal-comment');
  6177. const disCheck = document.getElementById('route-modal-disabled');
  6178. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6179. dstInput.value = r.dst_address;
  6180. gwInput.value = r.gateway || '';
  6181. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6182. commentInput.value = r.comment || '';
  6183. disCheck.checked = !!r.disabled;
  6184. const checkGw = document.getElementById('route-modal-check-gw');
  6185. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6186. const checkTarget = document.getElementById('route-modal-check-target');
  6187. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6188. const checkInterval = document.getElementById('route-modal-check-interval');
  6189. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6190. const checkThresh = document.getElementById('route-modal-check-threshold');
  6191. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6192. toggleRouteCheckModeUI();
  6193. dstInput.disabled = !isStatic;
  6194. gwInput.disabled = !isStatic;
  6195. distInput.disabled = !isStatic;
  6196. ifaceSelect.disabled = !isStatic;
  6197. tableSelect.disabled = !isStatic;
  6198. commentInput.disabled = !isStatic;
  6199. disCheck.disabled = !isStatic;
  6200. if (checkGw) checkGw.disabled = !isStatic;
  6201. if (checkTarget) checkTarget.disabled = !isStatic;
  6202. if (checkInterval) checkInterval.disabled = !isStatic;
  6203. if (checkThresh) checkThresh.disabled = !isStatic;
  6204. if (saveBtn) {
  6205. if (isStatic) {
  6206. saveBtn.classList.remove('hidden');
  6207. } else {
  6208. saveBtn.classList.add('hidden');
  6209. }
  6210. }
  6211. populateInterfaceSelect('route-modal-iface', r.interface);
  6212. tableSelect.innerHTML = '';
  6213. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6214. const opt = document.createElement('option');
  6215. opt.value = t.name;
  6216. opt.innerText = t.name;
  6217. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6218. tableSelect.appendChild(opt);
  6219. });
  6220. document.getElementById('route-modal').classList.remove('hidden');
  6221. }
  6222. function closeRouteModal() {
  6223. document.getElementById('route-modal').classList.add('hidden');
  6224. }
  6225. function setRouteCheckTarget(ip) {
  6226. const inp = document.getElementById('route-modal-check-target');
  6227. if (inp) inp.value = ip;
  6228. }
  6229. function toggleRouteCheckModeUI() {
  6230. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6231. const targetRow = document.getElementById('route-row-check-target');
  6232. const paramsRow = document.getElementById('route-row-check-params');
  6233. if (mode === 'none') {
  6234. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6235. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6236. } else if (mode === 'ping') {
  6237. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6238. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6239. } else { // internet
  6240. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6241. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6242. }
  6243. }
  6244. async function submitSaveRoute(e) {
  6245. e.preventDefault();
  6246. const id = document.getElementById('route-modal-id').value;
  6247. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6248. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6249. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6250. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6251. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6252. const dst = document.getElementById('route-modal-dst').value.trim();
  6253. const gw = document.getElementById('route-modal-gw').value.trim();
  6254. const table = document.getElementById('route-modal-table').value;
  6255. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6256. const iface = document.getElementById('route-modal-iface').value;
  6257. const comment = document.getElementById('route-modal-comment').value.trim();
  6258. const disabled = document.getElementById('route-modal-disabled').checked;
  6259. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6260. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6261. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6262. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6263. if (!dst) {
  6264. showToast('Error', 'Destination address is required', 'error');
  6265. return;
  6266. }
  6267. if (!gw && !iface) {
  6268. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6269. return;
  6270. }
  6271. const payload = {
  6272. id,
  6273. old_dst_address: oldDst,
  6274. old_gateway: oldGw,
  6275. old_routing_table: oldTable,
  6276. old_interface: oldIface,
  6277. dst_address: dst,
  6278. gateway: gw || iface,
  6279. routing_table: table,
  6280. distance,
  6281. interface: iface,
  6282. comment,
  6283. disabled,
  6284. check_gateway,
  6285. check_target,
  6286. check_interval,
  6287. check_threshold
  6288. };
  6289. if (oldDistStr !== undefined && oldDistStr !== '') {
  6290. payload.old_distance = parseInt(oldDistStr, 10);
  6291. }
  6292. try {
  6293. const res = await fetch(`${API_BASE}/routes`, {
  6294. method: 'POST',
  6295. headers: { 'Content-Type': 'application/json' },
  6296. body: JSON.stringify(payload)
  6297. });
  6298. if (res.ok) {
  6299. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6300. closeRouteModal();
  6301. loadRoutes();
  6302. } else {
  6303. const err = await res.json();
  6304. showToast('Error', err.message || 'Failed to save route', 'error');
  6305. }
  6306. } catch (err) {
  6307. showToast('Error', err.message, 'error');
  6308. }
  6309. }
  6310. async function toggleRouteState(id, disabled) {
  6311. try {
  6312. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6313. method: 'POST',
  6314. headers: { 'Content-Type': 'application/json' },
  6315. body: JSON.stringify({ disabled })
  6316. });
  6317. if (res.ok) loadRoutes();
  6318. } catch (err) {
  6319. showToast('Error', err.message, 'error');
  6320. }
  6321. }
  6322. async function deleteRoute(id) {
  6323. if (!confirm('Are you sure you want to delete this route?')) return;
  6324. try {
  6325. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6326. if (res.ok) {
  6327. showToast('Deleted', 'Route removed', 'success');
  6328. loadRoutes();
  6329. }
  6330. } catch (err) {
  6331. showToast('Error', err.message, 'error');
  6332. }
  6333. }
  6334. // ----------------- Policy Rules (/ip route rule) -----------------
  6335. function renderPolicyRules() {
  6336. const tbody = document.getElementById('rules-table-body');
  6337. const empty = document.getElementById('rules-empty');
  6338. if (!tbody) return;
  6339. const showSystem = document.getElementById('prule-show-system')?.checked;
  6340. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6341. const countBadge = document.getElementById('rules-count-badge');
  6342. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6343. const bRules = document.getElementById('routes-badge-rules');
  6344. if (bRules) bRules.innerText = filtered.length;
  6345. if (filtered.length === 0) {
  6346. empty?.classList.remove('hidden');
  6347. tbody.innerHTML = '';
  6348. return;
  6349. }
  6350. empty?.classList.add('hidden');
  6351. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6352. if (tbody.dataset.sig === sig) return;
  6353. tbody.dataset.sig = sig;
  6354. tbody.innerHTML = '';
  6355. filtered.forEach(pr => {
  6356. const isSys = pr.is_default || pr.is_system;
  6357. const tr = document.createElement('tr');
  6358. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6359. tr.innerHTML = `
  6360. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6361. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6362. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6363. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6364. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6365. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6366. <td class="py-2.5 px-3 text-right font-sans">
  6367. ${!pr.is_default ? `
  6368. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6369. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6370. </td>
  6371. `;
  6372. tbody.appendChild(tr);
  6373. });
  6374. }
  6375. function openAddPolicyRuleModal() {
  6376. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6377. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6378. document.getElementById('prule-modal-mark').value = '';
  6379. document.getElementById('prule-modal-src').value = '';
  6380. document.getElementById('prule-modal-dst').value = '';
  6381. const sel = document.getElementById('prule-modal-table');
  6382. sel.innerHTML = '';
  6383. (state.routingTables || []).forEach(t => {
  6384. const opt = document.createElement('option');
  6385. opt.value = t.name;
  6386. opt.innerText = t.name;
  6387. sel.appendChild(opt);
  6388. });
  6389. document.getElementById('prule-modal').classList.remove('hidden');
  6390. }
  6391. function closePolicyRuleModal() {
  6392. document.getElementById('prule-modal').classList.add('hidden');
  6393. }
  6394. async function submitSavePolicyRule(e) {
  6395. e.preventDefault();
  6396. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6397. const mark = document.getElementById('prule-modal-mark').value.trim();
  6398. const src = document.getElementById('prule-modal-src').value.trim();
  6399. const dst = document.getElementById('prule-modal-dst').value.trim();
  6400. const table = document.getElementById('prule-modal-table').value;
  6401. const action = document.getElementById('prule-modal-action').value;
  6402. try {
  6403. const res = await fetch(`${API_BASE}/routing/rules`, {
  6404. method: 'POST',
  6405. headers: { 'Content-Type': 'application/json' },
  6406. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6407. });
  6408. if (res.ok) {
  6409. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6410. closePolicyRuleModal();
  6411. loadRoutes();
  6412. } else {
  6413. const err = await res.json();
  6414. showToast('Error', err.message, 'error');
  6415. }
  6416. } catch (err) {
  6417. showToast('Error', err.message, 'error');
  6418. }
  6419. }
  6420. async function deletePolicyRule(id) {
  6421. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6422. try {
  6423. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6424. if (res.ok) {
  6425. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6426. loadRoutes();
  6427. }
  6428. } catch (err) {
  6429. showToast('Error', err.message, 'error');
  6430. }
  6431. }
  6432. // ----------------- Routing Tables -----------------
  6433. function renderRoutingTables() {
  6434. const tbody = document.getElementById('tables-table-body');
  6435. if (!tbody) return;
  6436. const tables = state.routingTables || [];
  6437. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6438. if (tbody.dataset.sig === sig) return;
  6439. tbody.dataset.sig = sig;
  6440. tbody.innerHTML = '';
  6441. (state.routingTables || []).forEach(t => {
  6442. const tr = document.createElement('tr');
  6443. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6444. tr.innerHTML = `
  6445. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6446. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6447. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6448. `;
  6449. tbody.appendChild(tr);
  6450. });
  6451. }
  6452. function openAddTableModal() {
  6453. document.getElementById('table-modal-name').value = '';
  6454. document.getElementById('table-modal-id').value = '';
  6455. document.getElementById('table-modal-comment').value = '';
  6456. document.getElementById('table-modal').classList.remove('hidden');
  6457. }
  6458. function closeTableModal() {
  6459. document.getElementById('table-modal').classList.add('hidden');
  6460. }
  6461. async function submitSaveTable(e) {
  6462. e.preventDefault();
  6463. const name = document.getElementById('table-modal-name').value.trim();
  6464. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6465. const comment = document.getElementById('table-modal-comment').value.trim();
  6466. try {
  6467. const res = await fetch(`${API_BASE}/routing/tables`, {
  6468. method: 'POST',
  6469. headers: { 'Content-Type': 'application/json' },
  6470. body: JSON.stringify({ name, table_id: id, comment })
  6471. });
  6472. if (res.ok) {
  6473. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6474. closeTableModal();
  6475. loadRoutes();
  6476. } else {
  6477. const err = await res.json();
  6478. showToast('Error', err.message, 'error');
  6479. }
  6480. } catch (err) {
  6481. showToast('Error', err.message, 'error');
  6482. }
  6483. }
  6484. async function loadDebianConfig() {
  6485. const view = document.getElementById('debian-config-view');
  6486. view.innerText = 'Generating live configuration...';
  6487. try {
  6488. const res = await fetch(`${API_BASE}/debian/config`);
  6489. const data = await res.json();
  6490. view.innerText = data.content || '# Empty config';
  6491. } catch (err) {
  6492. view.innerText = 'Failed to generate Debian network config.';
  6493. }
  6494. }
  6495. async function saveDebianConfig() {
  6496. try {
  6497. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6498. const data = await res.json();
  6499. if (res.ok) {
  6500. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6501. loadDebianConfig();
  6502. }
  6503. } catch (err) {
  6504. showToast('Error', err.message, 'error');
  6505. }
  6506. }
  6507. function showToast(title, message, type = 'info') {
  6508. const container = document.getElementById('toast-container');
  6509. const toast = document.createElement('div');
  6510. const borderColors = {
  6511. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6512. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6513. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6514. };
  6515. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  6516. toast.innerHTML = `
  6517. <div class="flex-1">
  6518. <div class="font-bold text-xs text-white">${title}</div>
  6519. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6520. </div>
  6521. `;
  6522. container.appendChild(toast);
  6523. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6524. setTimeout(() => {
  6525. toast.classList.add('opacity-0', 'translate-y-2');
  6526. setTimeout(() => toast.remove(), 300);
  6527. }, 4000);
  6528. }
  6529. function formatTraffic(bytesPerSec) {
  6530. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6531. const kb = bytesPerSec / 1024;
  6532. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6533. const mb = kb / 1024;
  6534. return `${mb.toFixed(2)} MB/s`;
  6535. }
  6536. function toggleSidebar() {
  6537. const sb = document.getElementById('sidebar');
  6538. sb.classList.toggle('-translate-x-full');
  6539. }
  6540. // ======================== EoIP (Ethernet over IP) ========================
  6541. async function loadEoIP(populate = true) {
  6542. try {
  6543. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6544. const data = await res.json();
  6545. state.eoipTunnels = Array.isArray(data) ? data : [];
  6546. const badge = document.getElementById('eoip-count-badge');
  6547. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6548. const sideBadge = document.getElementById('badge-eoip-count');
  6549. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6550. renderEoIPTunnels();
  6551. } catch (err) {
  6552. console.error('Failed to load EoIP:', err);
  6553. }
  6554. }
  6555. function renderEoIPTunnels() {
  6556. const tbody = document.getElementById('eoip-table-body');
  6557. const empty = document.getElementById('eoip-empty');
  6558. if (!tbody) return;
  6559. tbody.innerHTML = '';
  6560. const tunnels = state.eoipTunnels || [];
  6561. if (tunnels.length === 0) {
  6562. empty?.classList.remove('hidden');
  6563. return;
  6564. }
  6565. empty?.classList.add('hidden');
  6566. tunnels.forEach(t => {
  6567. const tr = document.createElement('tr');
  6568. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6569. tr.innerHTML = `
  6570. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6571. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6572. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6573. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  6574. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6575. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6576. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6577. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6578. <td class="py-2.5 px-3 font-mono text-[11px]">
  6579. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6580. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6581. </td>
  6582. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6583. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6584. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6585. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6586. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6587. </td>
  6588. `;
  6589. tbody.appendChild(tr);
  6590. });
  6591. }
  6592. function openAddEoIPModal() {
  6593. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6594. document.getElementById('eoip-modal-id').value = '';
  6595. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6596. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6597. document.getElementById('eoip-modal-remote').value = '';
  6598. document.getElementById('eoip-modal-ip').value = '';
  6599. document.getElementById('eoip-modal-local').value = '';
  6600. document.getElementById('eoip-modal-mac').value = '';
  6601. document.getElementById('eoip-modal-mtu').value = '1500';
  6602. document.getElementById('eoip-modal-comment').value = '';
  6603. document.getElementById('eoip-modal-clampmss').checked = true;
  6604. document.getElementById('eoip-modal-disabled').checked = false;
  6605. document.getElementById('eoip-modal').classList.remove('hidden');
  6606. }
  6607. function openEditEoIPModal(id) {
  6608. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6609. if (!t) return;
  6610. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6611. document.getElementById('eoip-modal-id').value = t.id;
  6612. document.getElementById('eoip-modal-name').value = t.name;
  6613. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6614. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6615. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6616. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6617. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6618. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6619. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6620. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6621. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6622. document.getElementById('eoip-modal').classList.remove('hidden');
  6623. }
  6624. function closeEoIPModal() {
  6625. document.getElementById('eoip-modal').classList.add('hidden');
  6626. }
  6627. async function submitSaveEoIP(e) {
  6628. e.preventDefault();
  6629. const id = document.getElementById('eoip-modal-id').value;
  6630. const name = document.getElementById('eoip-modal-name').value.trim();
  6631. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6632. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6633. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6634. const local = document.getElementById('eoip-modal-local').value.trim();
  6635. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6636. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6637. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6638. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6639. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6640. try {
  6641. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6642. method: 'POST',
  6643. headers: { 'Content-Type': 'application/json' },
  6644. body: JSON.stringify({
  6645. id,
  6646. name,
  6647. tunnel_id: tunnelId,
  6648. remote_address: remote,
  6649. ip_address: ipAddress,
  6650. local_address: local,
  6651. mac_address: mac,
  6652. mtu,
  6653. clamp_mss: clampMss,
  6654. comment,
  6655. disabled
  6656. })
  6657. });
  6658. if (res.ok) {
  6659. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6660. closeEoIPModal();
  6661. loadEoIP(false);
  6662. fetchData(false);
  6663. } else {
  6664. const err = await res.json();
  6665. showToast('Error', err.message, 'error');
  6666. }
  6667. } catch (err) {
  6668. showToast('Error', err.message, 'error');
  6669. }
  6670. }
  6671. async function toggleEoIPState(id, disabled) {
  6672. try {
  6673. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6674. method: 'POST',
  6675. headers: { 'Content-Type': 'application/json' },
  6676. body: JSON.stringify({ disabled })
  6677. });
  6678. if (res.ok) {
  6679. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6680. loadEoIP(false);
  6681. fetchData(false);
  6682. }
  6683. } catch (err) {
  6684. showToast('Error', err.message, 'error');
  6685. }
  6686. }
  6687. async function deleteEoIP(id) {
  6688. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6689. try {
  6690. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6691. if (res.ok) {
  6692. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6693. loadEoIP(false);
  6694. fetchData(false);
  6695. }
  6696. } catch (err) {
  6697. showToast('Error', err.message, 'error');
  6698. }
  6699. }
  6700. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6701. async function loadAeroTUN(populate = true) {
  6702. try {
  6703. const [tunnelsRes, statsRes] = await Promise.all([
  6704. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6705. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6706. ]);
  6707. if (tunnelsRes.ok) {
  6708. const data = await tunnelsRes.json();
  6709. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6710. }
  6711. if (statsRes.ok) {
  6712. state.aerotunStats = await statsRes.json();
  6713. }
  6714. const countBadge = document.getElementById('aerotun-count-badge');
  6715. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6716. const sideBadge = document.getElementById('badge-aerotun-count');
  6717. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6718. renderAeroTUN();
  6719. } catch (err) {
  6720. console.error('Failed to load AeroTUN:', err);
  6721. }
  6722. }
  6723. function renderAeroTUN() {
  6724. const tbody = document.getElementById('aerotun-table-body');
  6725. const empty = document.getElementById('aerotun-empty');
  6726. // Update summary cards
  6727. const stats = state.aerotunStats || {};
  6728. const tunnels = state.aerotunTunnels || [];
  6729. const statActive = document.getElementById('aerotun-stat-active');
  6730. if (statActive) {
  6731. const activeCount = tunnels.filter(t => t.running).length;
  6732. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6733. }
  6734. const statSaved = document.getElementById('aerotun-stat-saved');
  6735. if (statSaved) {
  6736. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6737. }
  6738. const statRatio = document.getElementById('aerotun-stat-ratio');
  6739. if (statRatio) {
  6740. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6741. }
  6742. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6743. if (statTraffic) {
  6744. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6745. }
  6746. if (!tbody) return;
  6747. tbody.innerHTML = '';
  6748. if (tunnels.length === 0) {
  6749. empty?.classList.remove('hidden');
  6750. return;
  6751. }
  6752. empty?.classList.add('hidden');
  6753. tunnels.forEach(t => {
  6754. const tr = document.createElement('tr');
  6755. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6756. const modeBadge = t.mode === 'server'
  6757. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  6758. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  6759. const endpointInfo = t.mode === 'server'
  6760. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6761. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6762. const compBadge = t.compression
  6763. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6764. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6765. const activePeer = t.active_peer_endpoint
  6766. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6767. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6768. const rawRx = formatBytes(t.rx_bytes || 0);
  6769. const rawTx = formatBytes(t.tx_bytes || 0);
  6770. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6771. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6772. tr.innerHTML = `
  6773. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6774. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6775. <span>${escapeHtml(t.name)}</span>
  6776. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6777. </td>
  6778. <td class="py-2.5 px-3">${modeBadge}</td>
  6779. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6780. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6781. <td class="py-2.5 px-3">${compBadge}</td>
  6782. <td class="py-2.5 px-3">${activePeer}</td>
  6783. <td class="py-2.5 px-3 font-mono text-[11px]">
  6784. <span class="text-emerald-400">↓ ${rawRx}</span>
  6785. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6786. </td>
  6787. <td class="py-2.5 px-3 font-mono text-[11px]">
  6788. <span class="text-slate-400">↓ ${wireRx}</span>
  6789. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6790. </td>
  6791. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6792. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6793. ${t.running
  6794. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6795. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6796. }
  6797. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6798. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6799. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6800. </td>
  6801. `;
  6802. tbody.appendChild(tr);
  6803. });
  6804. }
  6805. function onAeroTUNModeChange() {
  6806. const mode = document.getElementById('aerotun-modal-mode').value;
  6807. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6808. const portInput = document.getElementById('aerotun-modal-port');
  6809. if (mode === 'server') {
  6810. if (!portInput.value) portInput.value = '51830';
  6811. endpointInput.placeholder = 'Optional / learned roaming peer';
  6812. } else {
  6813. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6814. if (!portInput.value) portInput.value = '';
  6815. }
  6816. }
  6817. async function generateAeroTUNKey() {
  6818. try {
  6819. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6820. if (res.ok) {
  6821. const data = await res.json();
  6822. document.getElementById('aerotun-modal-psk').value = data.key;
  6823. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6824. }
  6825. } catch (err) {
  6826. const arr = new Uint8Array(32);
  6827. crypto.getRandomValues(arr);
  6828. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6829. document.getElementById('aerotun-modal-psk').value = hex;
  6830. }
  6831. }
  6832. function openAddAeroTUNModal() {
  6833. const tunnels = state.aerotunTunnels || [];
  6834. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6835. document.getElementById('aerotun-modal-id').value = '';
  6836. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6837. document.getElementById('aerotun-modal-mode').value = 'server';
  6838. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6839. document.getElementById('aerotun-modal-endpoint').value = '';
  6840. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6841. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6842. document.getElementById('aerotun-modal-psk').value = '';
  6843. document.getElementById('aerotun-modal-mtu').value = '1420';
  6844. document.getElementById('aerotun-modal-comment').value = '';
  6845. document.getElementById('aerotun-modal-compression').checked = true;
  6846. document.getElementById('aerotun-modal-defroute').checked = false;
  6847. document.getElementById('aerotun-modal-disabled').checked = false;
  6848. generateAeroTUNKey();
  6849. onAeroTUNModeChange();
  6850. document.getElementById('aerotun-modal').classList.remove('hidden');
  6851. }
  6852. function openEditAeroTUNModal(id) {
  6853. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6854. if (!t) return;
  6855. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6856. document.getElementById('aerotun-modal-id').value = t.id;
  6857. document.getElementById('aerotun-modal-name').value = t.name;
  6858. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6859. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6860. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6861. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6862. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6863. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6864. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6865. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6866. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6867. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6868. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6869. onAeroTUNModeChange();
  6870. document.getElementById('aerotun-modal').classList.remove('hidden');
  6871. }
  6872. function closeAeroTUNModal() {
  6873. document.getElementById('aerotun-modal').classList.add('hidden');
  6874. }
  6875. async function submitSaveAeroTUN(e) {
  6876. e.preventDefault();
  6877. const id = document.getElementById('aerotun-modal-id').value;
  6878. const name = document.getElementById('aerotun-modal-name').value.trim();
  6879. const mode = document.getElementById('aerotun-modal-mode').value;
  6880. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6881. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6882. const local = document.getElementById('aerotun-modal-local').value.trim();
  6883. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6884. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6885. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6886. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6887. const compression = document.getElementById('aerotun-modal-compression').checked;
  6888. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6889. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6890. if (mode === 'client' && !endpoint) {
  6891. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6892. return;
  6893. }
  6894. if (!psk) {
  6895. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6896. return;
  6897. }
  6898. try {
  6899. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6900. method: 'POST',
  6901. headers: { 'Content-Type': 'application/json' },
  6902. body: JSON.stringify({
  6903. id,
  6904. name,
  6905. mode,
  6906. listen_port: port,
  6907. remote_endpoint: endpoint,
  6908. local_address: local,
  6909. peer_address: peer,
  6910. psk,
  6911. mtu,
  6912. compression,
  6913. default_route: defaultRoute,
  6914. comment,
  6915. disabled
  6916. })
  6917. });
  6918. if (res.ok) {
  6919. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6920. closeAeroTUNModal();
  6921. loadAeroTUN(false);
  6922. fetchData(false);
  6923. } else {
  6924. const err = await res.text();
  6925. showToast('Error Saving Tunnel', err, 'error');
  6926. }
  6927. } catch (err) {
  6928. showToast('Network Error', err.message, 'error');
  6929. }
  6930. }
  6931. async function startAeroTUNTunnel(id) {
  6932. try {
  6933. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6934. if (res.ok) {
  6935. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6936. loadAeroTUN(false);
  6937. fetchData(false);
  6938. } else {
  6939. const err = await res.text();
  6940. showToast('Failed to Start', err, 'error');
  6941. }
  6942. } catch (err) {
  6943. showToast('Error', err.message, 'error');
  6944. }
  6945. }
  6946. async function stopAeroTUNTunnel(id) {
  6947. try {
  6948. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6949. if (res.ok) {
  6950. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6951. loadAeroTUN(false);
  6952. fetchData(false);
  6953. } else {
  6954. const err = await res.text();
  6955. showToast('Failed to Stop', err, 'error');
  6956. }
  6957. } catch (err) {
  6958. showToast('Error', err.message, 'error');
  6959. }
  6960. }
  6961. async function toggleAeroTUNState(id, disabled) {
  6962. try {
  6963. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6964. method: 'POST',
  6965. headers: { 'Content-Type': 'application/json' },
  6966. body: JSON.stringify({ disabled })
  6967. });
  6968. if (res.ok) {
  6969. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6970. loadAeroTUN(false);
  6971. fetchData(false);
  6972. }
  6973. } catch (err) {
  6974. showToast('Error', err.message, 'error');
  6975. }
  6976. }
  6977. async function deleteAeroTUN(id) {
  6978. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6979. try {
  6980. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6981. if (res.ok) {
  6982. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6983. loadAeroTUN(false);
  6984. fetchData(false);
  6985. }
  6986. } catch (err) {
  6987. showToast('Error', err.message, 'error');
  6988. }
  6989. }
  6990. // ======================== PPP Central Hub & Servers ========================
  6991. function switchPPPSubTab(tab) {
  6992. state.pppSubTab = tab;
  6993. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6994. tabs.forEach(t => {
  6995. const panel = document.getElementById(`ppp-subtab-${t}`);
  6996. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6997. if (panel) {
  6998. if (t === tab) panel.classList.remove('hidden');
  6999. else panel.classList.add('hidden');
  7000. }
  7001. if (btn) {
  7002. if (t === tab) {
  7003. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7004. } else {
  7005. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7006. }
  7007. }
  7008. });
  7009. const addBtn = document.getElementById('ppp-primary-add-btn');
  7010. if (addBtn) {
  7011. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7012. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7013. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7014. else addBtn.innerHTML = '<span>Save Config</span>';
  7015. }
  7016. if (tab === 'active') loadPPPSessions();
  7017. }
  7018. function openCurrentPPPModal() {
  7019. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7020. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7021. else if (state.pppSubTab === 'active') loadPPPSessions();
  7022. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7023. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7024. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7025. }
  7026. async function loadPPP(populateDropdowns = true) {
  7027. await Promise.all([
  7028. loadPPPSecrets(),
  7029. loadPPPProfiles(),
  7030. loadPPPServers(),
  7031. loadPPPSessions()
  7032. ]);
  7033. }
  7034. async function loadPPPSecrets() {
  7035. try {
  7036. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7037. const data = await res.json();
  7038. state.pppSecrets = Array.isArray(data) ? data : [];
  7039. const b = document.getElementById('ppp-badge-secrets');
  7040. if (b) b.innerText = state.pppSecrets.length;
  7041. const b2 = document.getElementById('secrets-count-badge');
  7042. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7043. renderPPPSecrets();
  7044. } catch (err) {
  7045. console.error('Failed to load PPP secrets:', err);
  7046. }
  7047. }
  7048. function renderPPPSecrets() {
  7049. const tbody = document.getElementById('secrets-table-body');
  7050. const empty = document.getElementById('secrets-empty');
  7051. if (!tbody) return;
  7052. tbody.innerHTML = '';
  7053. const secrets = state.pppSecrets || [];
  7054. if (secrets.length === 0) {
  7055. empty?.classList.remove('hidden');
  7056. return;
  7057. }
  7058. empty?.classList.add('hidden');
  7059. secrets.forEach(s => {
  7060. const tr = document.createElement('tr');
  7061. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7062. tr.innerHTML = `
  7063. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7064. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7065. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7066. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7067. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7068. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7069. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7070. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7071. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  7072. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7073. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7074. </td>
  7075. `;
  7076. tbody.appendChild(tr);
  7077. });
  7078. }
  7079. async function loadPPPProfiles() {
  7080. try {
  7081. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7082. const data = await res.json();
  7083. state.pppProfiles = Array.isArray(data) ? data : [];
  7084. const b = document.getElementById('ppp-badge-profiles');
  7085. if (b) b.innerText = state.pppProfiles.length;
  7086. const b2 = document.getElementById('profiles-count-badge');
  7087. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7088. // Populate profile selects across modals
  7089. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7090. selects.forEach(sid => {
  7091. const el = document.getElementById(sid);
  7092. if (!el) return;
  7093. const cur = el.value;
  7094. el.innerHTML = '';
  7095. state.pppProfiles.forEach(p => {
  7096. const opt = document.createElement('option');
  7097. opt.value = p.name;
  7098. opt.innerText = `${p.name} (${p.remote_address})`;
  7099. if (p.name === cur) opt.selected = true;
  7100. el.appendChild(opt);
  7101. });
  7102. });
  7103. renderPPPProfiles();
  7104. } catch (err) {
  7105. console.error('Failed to load PPP profiles:', err);
  7106. }
  7107. }
  7108. function renderPPPProfiles() {
  7109. const tbody = document.getElementById('profiles-table-body');
  7110. if (!tbody) return;
  7111. tbody.innerHTML = '';
  7112. (state.pppProfiles || []).forEach(p => {
  7113. const isDefault = p.name.startsWith('default');
  7114. const tr = document.createElement('tr');
  7115. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7116. tr.innerHTML = `
  7117. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7118. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7119. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7120. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7121. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7122. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  7123. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7124. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7125. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  7126. </td>
  7127. `;
  7128. tbody.appendChild(tr);
  7129. });
  7130. }
  7131. async function loadPPPServers() {
  7132. try {
  7133. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7134. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7135. fetch(`${API_BASE}/vpn/servers/pptp`),
  7136. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7137. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7138. ]);
  7139. if (pppoeRes.ok) {
  7140. state.pppoeServer = await pppoeRes.json();
  7141. const s = state.pppoeServer;
  7142. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7143. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7144. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7145. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7146. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7147. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7148. const pill = document.getElementById('pppoe-server-status-pill');
  7149. if (pill) {
  7150. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7151. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7152. }
  7153. setDotBadge('ppp-badge-pppoe-state', s.running);
  7154. }
  7155. if (pptpRes.ok) {
  7156. state.pptpServer = await pptpRes.json();
  7157. const s = state.pptpServer;
  7158. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7159. document.getElementById('pptp-server-port').value = s.port || 1723;
  7160. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7161. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7162. const pill = document.getElementById('pptp-server-status-pill');
  7163. if (pill) {
  7164. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7165. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7166. }
  7167. setDotBadge('ppp-badge-pptp-state', s.running);
  7168. }
  7169. if (l2tpRes.ok) {
  7170. state.l2tpServer = await l2tpRes.json();
  7171. const s = state.l2tpServer;
  7172. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7173. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7174. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7175. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7176. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7177. const pill = document.getElementById('l2tp-server-status-pill');
  7178. if (pill) {
  7179. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7180. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7181. }
  7182. setDotBadge('ppp-badge-l2tp-state', s.running);
  7183. }
  7184. if (ipsecRes.ok) {
  7185. state.ipsecServer = await ipsecRes.json();
  7186. const s = state.ipsecServer;
  7187. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7188. if (modalEn) modalEn.checked = !!s.enabled;
  7189. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7190. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7191. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7192. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7193. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7194. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7195. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7196. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7197. const pill = document.getElementById('modal-ipsec-server-status');
  7198. if (pill) {
  7199. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7200. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7201. }
  7202. }
  7203. } catch (err) {
  7204. console.error('Failed to load VPN servers:', err);
  7205. }
  7206. }
  7207. async function loadPPPSessions() {
  7208. try {
  7209. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7210. const data = await res.json();
  7211. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7212. const b = document.getElementById('ppp-badge-active');
  7213. if (b) b.innerText = state.pppActiveSessions.length;
  7214. const sideB = document.getElementById('badge-ppp-sessions');
  7215. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7216. renderPPPSessions();
  7217. } catch (err) {
  7218. console.error('Failed to load active PPP sessions:', err);
  7219. }
  7220. }
  7221. function renderPPPSessions() {
  7222. const tbody = document.getElementById('active-ppp-table-body');
  7223. const empty = document.getElementById('active-ppp-empty');
  7224. if (!tbody) return;
  7225. tbody.innerHTML = '';
  7226. const list = state.pppActiveSessions || [];
  7227. if (list.length === 0) {
  7228. empty?.classList.remove('hidden');
  7229. return;
  7230. }
  7231. empty?.classList.add('hidden');
  7232. list.forEach(s => {
  7233. const tr = document.createElement('tr');
  7234. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7235. tr.innerHTML = `
  7236. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7237. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7238. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7239. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7240. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7241. <td class="py-2.5 px-3 text-[11px]">
  7242. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7243. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7244. </td>
  7245. <td class="py-2.5 px-3 text-right font-sans">
  7246. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7247. </td>
  7248. `;
  7249. tbody.appendChild(tr);
  7250. });
  7251. }
  7252. async function disconnectPPPSession(iface) {
  7253. if (!confirm(`Disconnect session ${iface}?`)) return;
  7254. try {
  7255. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7256. if (res.ok) {
  7257. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7258. loadPPPSessions();
  7259. }
  7260. } catch (err) {
  7261. showToast('Error', err.message, 'error');
  7262. }
  7263. }
  7264. // PPP Secret Modal handlers
  7265. function openAddPPPSecretModal() {
  7266. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7267. document.getElementById('secret-modal-id').value = '';
  7268. document.getElementById('secret-modal-name').value = '';
  7269. document.getElementById('secret-modal-password').value = '';
  7270. document.getElementById('secret-modal-service').value = 'any';
  7271. document.getElementById('secret-modal-profile').value = 'default';
  7272. document.getElementById('secret-modal-local').value = '';
  7273. document.getElementById('secret-modal-remote').value = '';
  7274. document.getElementById('secret-modal-comment').value = '';
  7275. document.getElementById('secret-modal-disabled').checked = false;
  7276. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7277. }
  7278. function openEditPPPSecretModal(id) {
  7279. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7280. if (!s) return;
  7281. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7282. document.getElementById('secret-modal-id').value = s.id;
  7283. document.getElementById('secret-modal-name').value = s.name;
  7284. document.getElementById('secret-modal-password').value = s.password;
  7285. document.getElementById('secret-modal-service').value = s.service || 'any';
  7286. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7287. document.getElementById('secret-modal-local').value = s.local_address || '';
  7288. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7289. document.getElementById('secret-modal-comment').value = s.comment || '';
  7290. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7291. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7292. }
  7293. function closePPPSecretModal() {
  7294. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7295. }
  7296. async function submitSavePPPSecret(e) {
  7297. e.preventDefault();
  7298. const id = document.getElementById('secret-modal-id').value;
  7299. const name = document.getElementById('secret-modal-name').value.trim();
  7300. const password = document.getElementById('secret-modal-password').value.trim();
  7301. const service = document.getElementById('secret-modal-service').value;
  7302. const profile = document.getElementById('secret-modal-profile').value;
  7303. const local = document.getElementById('secret-modal-local').value.trim();
  7304. const remote = document.getElementById('secret-modal-remote').value.trim();
  7305. const comment = document.getElementById('secret-modal-comment').value.trim();
  7306. const disabled = document.getElementById('secret-modal-disabled').checked;
  7307. try {
  7308. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7309. method: 'POST',
  7310. headers: { 'Content-Type': 'application/json' },
  7311. body: JSON.stringify({
  7312. id,
  7313. name,
  7314. password,
  7315. service,
  7316. profile,
  7317. local_address: local,
  7318. remote_address: remote,
  7319. comment,
  7320. disabled
  7321. })
  7322. });
  7323. if (res.ok) {
  7324. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7325. closePPPSecretModal();
  7326. loadPPPSecrets();
  7327. } else {
  7328. const err = await res.json();
  7329. showToast('Error', err.message, 'error');
  7330. }
  7331. } catch (err) {
  7332. showToast('Error', err.message, 'error');
  7333. }
  7334. }
  7335. async function togglePPPSecretState(id, disabled) {
  7336. try {
  7337. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7338. method: 'POST',
  7339. headers: { 'Content-Type': 'application/json' },
  7340. body: JSON.stringify({ disabled })
  7341. });
  7342. if (res.ok) {
  7343. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7344. loadPPPSecrets();
  7345. }
  7346. } catch (err) {
  7347. showToast('Error', err.message, 'error');
  7348. }
  7349. }
  7350. async function deletePPPSecret(id) {
  7351. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7352. try {
  7353. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7354. if (res.ok) {
  7355. showToast('Deleted', 'Secret account removed', 'success');
  7356. loadPPPSecrets();
  7357. }
  7358. } catch (err) {
  7359. showToast('Error', err.message, 'error');
  7360. }
  7361. }
  7362. // PPP Profile Modal handlers
  7363. function openAddPPPProfileModal() {
  7364. document.getElementById('profile-modal-name').value = '';
  7365. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7366. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7367. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7368. document.getElementById('profile-modal-encryption').value = 'required';
  7369. document.getElementById('profile-modal-onlyone').checked = true;
  7370. document.getElementById('profile-modal-comment').value = '';
  7371. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7372. }
  7373. function closePPPProfileModal() {
  7374. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7375. }
  7376. async function submitSavePPPProfile(e) {
  7377. e.preventDefault();
  7378. const name = document.getElementById('profile-modal-name').value.trim();
  7379. const local = document.getElementById('profile-modal-local').value.trim();
  7380. const remote = document.getElementById('profile-modal-remote').value.trim();
  7381. const dns = document.getElementById('profile-modal-dns').value.trim();
  7382. const enc = document.getElementById('profile-modal-encryption').value;
  7383. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7384. const comment = document.getElementById('profile-modal-comment').value.trim();
  7385. try {
  7386. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7387. method: 'POST',
  7388. headers: { 'Content-Type': 'application/json' },
  7389. body: JSON.stringify({
  7390. id: name,
  7391. name,
  7392. local_address: local,
  7393. remote_address: remote,
  7394. dns_servers: dns,
  7395. use_encryption: enc,
  7396. only_one: onlyone,
  7397. comment
  7398. })
  7399. });
  7400. if (res.ok) {
  7401. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7402. closePPPProfileModal();
  7403. loadPPPProfiles();
  7404. } else {
  7405. const err = await res.json();
  7406. showToast('Error', err.message, 'error');
  7407. }
  7408. } catch (err) {
  7409. showToast('Error', err.message, 'error');
  7410. }
  7411. }
  7412. async function deletePPPProfile(name) {
  7413. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7414. try {
  7415. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7416. if (res.ok) {
  7417. showToast('Deleted', 'Profile removed', 'success');
  7418. loadPPPProfiles();
  7419. } else {
  7420. const err = await res.json();
  7421. showToast('Error', err.message, 'error');
  7422. }
  7423. } catch (err) {
  7424. showToast('Error', err.message, 'error');
  7425. }
  7426. }
  7427. // Server Config submissions
  7428. async function savePPPoEServerConfig(e) {
  7429. e.preventDefault();
  7430. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7431. const name = document.getElementById('pppoe-server-name').value.trim();
  7432. const iface = document.getElementById('pppoe-server-iface').value;
  7433. const profile = document.getElementById('pppoe-server-profile').value;
  7434. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7435. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7436. try {
  7437. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7438. method: 'POST',
  7439. headers: { 'Content-Type': 'application/json' },
  7440. body: JSON.stringify({
  7441. enabled,
  7442. service_name: name,
  7443. interface: iface,
  7444. default_profile: profile,
  7445. max_mtu: mtu,
  7446. max_mru: mtu,
  7447. one_session_per_host: onesession
  7448. })
  7449. });
  7450. if (res.ok) {
  7451. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7452. loadPPPServers();
  7453. fetchData(false);
  7454. } else {
  7455. const err = await res.json();
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. } catch (err) {
  7459. showToast('Error', err.message, 'error');
  7460. }
  7461. }
  7462. async function savePPTPServerConfig(e) {
  7463. e.preventDefault();
  7464. const enabled = document.getElementById('pptp-server-enabled').checked;
  7465. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7466. const profile = document.getElementById('pptp-server-profile').value;
  7467. const mppe = document.getElementById('pptp-server-mppe').checked;
  7468. try {
  7469. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7470. method: 'POST',
  7471. headers: { 'Content-Type': 'application/json' },
  7472. body: JSON.stringify({
  7473. enabled,
  7474. port,
  7475. default_profile: profile,
  7476. require_mppe: mppe
  7477. })
  7478. });
  7479. if (res.ok) {
  7480. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7481. loadPPPServers();
  7482. fetchData(false);
  7483. } else {
  7484. const err = await res.json();
  7485. showToast('Error', err.message, 'error');
  7486. }
  7487. } catch (err) {
  7488. showToast('Error', err.message, 'error');
  7489. }
  7490. }
  7491. async function saveL2TPServerConfig(e) {
  7492. e.preventDefault();
  7493. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7494. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7495. const profile = document.getElementById('l2tp-server-profile').value;
  7496. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7497. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7498. try {
  7499. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7500. method: 'POST',
  7501. headers: { 'Content-Type': 'application/json' },
  7502. body: JSON.stringify({
  7503. enabled,
  7504. port,
  7505. default_profile: profile,
  7506. use_ipsec: useipsec,
  7507. ipsec_secret: psk
  7508. })
  7509. });
  7510. if (res.ok) {
  7511. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7512. loadPPPServers();
  7513. fetchData(false);
  7514. } else {
  7515. const err = await res.json();
  7516. showToast('Error', err.message, 'error');
  7517. }
  7518. } catch (err) {
  7519. showToast('Error', err.message, 'error');
  7520. }
  7521. }
  7522. // IPSec Server Modal
  7523. function openIPSecServerModal() {
  7524. loadPPPServers();
  7525. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7526. }
  7527. function closeIPSecServerModal() {
  7528. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7529. }
  7530. async function submitSaveIPSecServer(e) {
  7531. e.preventDefault();
  7532. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7533. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7534. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7535. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7536. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7537. try {
  7538. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7539. method: 'POST',
  7540. headers: { 'Content-Type': 'application/json' },
  7541. body: JSON.stringify({
  7542. enabled,
  7543. preshared_key: psk,
  7544. pool_address: pool,
  7545. dns_servers: dns,
  7546. local_subnet: subnet
  7547. })
  7548. });
  7549. if (res.ok) {
  7550. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7551. closeIPSecServerModal();
  7552. loadPPPServers();
  7553. fetchData(false);
  7554. } else {
  7555. const err = await res.json();
  7556. showToast('Error', err.message, 'error');
  7557. }
  7558. } catch (err) {
  7559. showToast('Error', err.message, 'error');
  7560. }
  7561. }
  7562. // WireGuard Client Config Viewer
  7563. let currentWGClientConf = '';
  7564. async function openWGClientConfModal(iface, clientIP) {
  7565. try {
  7566. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7567. method: 'POST',
  7568. headers: { 'Content-Type': 'application/json' },
  7569. body: JSON.stringify({
  7570. interface: iface,
  7571. address: clientIP || '10.10.0.2/32',
  7572. dns: '1.1.1.1, 8.8.8.8'
  7573. })
  7574. });
  7575. if (res.ok) {
  7576. const data = await res.json();
  7577. currentWGClientConf = data.config;
  7578. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7579. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7580. } else {
  7581. const err = await res.json();
  7582. showToast('Error', err.message, 'error');
  7583. }
  7584. } catch (err) {
  7585. showToast('Error', err.message, 'error');
  7586. }
  7587. }
  7588. function closeWGClientConfModal() {
  7589. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7590. }
  7591. function copyWGClientConf() {
  7592. if (!currentWGClientConf) return;
  7593. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7594. }
  7595. function downloadWGClientConf() {
  7596. if (!currentWGClientConf) return;
  7597. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7598. const a = document.createElement('a');
  7599. a.href = URL.createObjectURL(blob);
  7600. a.download = 'wireguard-client.conf';
  7601. document.body.appendChild(a);
  7602. a.click();
  7603. document.body.removeChild(a);
  7604. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7605. }
  7606. // =========================================================================
  7607. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7608. // =========================================================================
  7609. state.activeDynSubTab = 'bgp-peers';
  7610. state.activeBgpSubTab = 'bgp-peers';
  7611. state.activeOspfTab = 'instances';
  7612. state.bgpInstance = null;
  7613. state.bgpPeers = [];
  7614. state.bgpNets = [];
  7615. state.bgpRoutes = [];
  7616. state.ospfInstance = null;
  7617. state.ospfInstances = [];
  7618. state.ospfAreas = [];
  7619. state.ospfAreaRanges = [];
  7620. state.ospfTemplates = [];
  7621. state.ospfLiveInterfaces = [];
  7622. state.ospfStaticNbrs = [];
  7623. state.ospfNeighbors = [];
  7624. state.ospfLSA = [];
  7625. state.ospfRoutes = [];
  7626. state.selectedOspfRow = {
  7627. instances: null,
  7628. areas: null,
  7629. 'area-ranges': null,
  7630. templates: null,
  7631. interfaces: null,
  7632. 'static-nbrs': null,
  7633. neighbors: null,
  7634. lsa: null,
  7635. };
  7636. state.ospfSort = {
  7637. instances: { col: 'name', asc: true },
  7638. areas: { col: 'name', asc: true },
  7639. ranges: { col: 'area', asc: true },
  7640. templates: { col: 'interfaces', asc: true },
  7641. live_ifaces: { col: 'interface', asc: true },
  7642. snbrs: { col: 'address', asc: true },
  7643. neighbors: { col: 'address', asc: true },
  7644. lsa: { col: 'instance', asc: true },
  7645. };
  7646. function switchBgpSubTab(subTab) {
  7647. state.activeBgpSubTab = subTab;
  7648. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7649. tabs.forEach(t => {
  7650. const el = document.getElementById(`dyn-subtab-${t}`);
  7651. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7652. if (el) el.classList.toggle('hidden', t !== subTab);
  7653. if (btn) {
  7654. if (t === subTab) {
  7655. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7656. } else {
  7657. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7658. }
  7659. }
  7660. });
  7661. }
  7662. function switchOspfTab(tabName) {
  7663. state.activeOspfTab = tabName;
  7664. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7665. tabs.forEach(t => {
  7666. const pane = document.getElementById(`ospf-pane-${t}`);
  7667. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7668. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7669. if (btn) {
  7670. if (t === tabName) {
  7671. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7672. } else {
  7673. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7674. }
  7675. }
  7676. });
  7677. }
  7678. function switchOspfSubTab(tab) {
  7679. // Legacy alias
  7680. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7681. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7682. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7683. else switchOspfTab('instances');
  7684. }
  7685. function switchDynSubTab(subTab) {
  7686. if (subTab.startsWith('bgp')) {
  7687. if (state.activeTab !== 'bgp') navigate('bgp');
  7688. switchBgpSubTab(subTab);
  7689. } else if (subTab.startsWith('ospf')) {
  7690. if (state.activeTab !== 'ospf') navigate('ospf');
  7691. switchOspfTab('instances');
  7692. }
  7693. }
  7694. async function loadDynamicRouting(showToastMsg = false) {
  7695. try {
  7696. const fetchSafeJson = async (url) => {
  7697. try {
  7698. const r = await fetch(url);
  7699. return r.ok ? await r.json() : null;
  7700. } catch (e) {
  7701. return null;
  7702. }
  7703. };
  7704. const [
  7705. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7706. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7707. selectRules, commLists, asLists
  7708. ] = await Promise.all([
  7709. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7710. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7711. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7712. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7713. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7714. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7715. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7716. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7717. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7718. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7719. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7720. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7721. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7722. fetchSafeJson(`${API_BASE}/routing/filters`),
  7723. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7724. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7725. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7726. ]);
  7727. if (sum) state.dynSummary = sum;
  7728. if (bgpInst) state.bgpInstance = bgpInst;
  7729. if (bgpPeers) state.bgpPeers = bgpPeers;
  7730. if (bgpNets) state.bgpNets = bgpNets;
  7731. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7732. if (ospfInsts) state.ospfInstances = ospfInsts;
  7733. if (ospfAreas) state.ospfAreas = ospfAreas;
  7734. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7735. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7736. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7737. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7738. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7739. if (ospfLsa) state.ospfLSA = ospfLsa;
  7740. if (filters) state.routingFilters = filters;
  7741. if (selectRules) state.routingSelectRules = selectRules;
  7742. if (commLists) state.routingCommunityLists = commLists;
  7743. if (asLists) state.routingASLists = asLists;
  7744. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7745. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7746. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7747. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7748. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7749. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7750. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7751. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7752. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7753. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7754. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7755. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7756. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7757. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7758. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7759. } catch (err) {
  7760. console.error('Failed to load dynamic routing:', err);
  7761. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7762. }
  7763. }
  7764. async function loadOspfAll() {
  7765. await loadDynamicRouting(true);
  7766. }
  7767. function renderBgpStatusPill() {
  7768. const pill = document.getElementById('bgp-live-status-pill');
  7769. if (!pill) return;
  7770. const inst = state.bgpInstance;
  7771. if (!inst || !inst.enabled) {
  7772. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7773. pill.innerText = 'BGP DISABLED';
  7774. } else if (inst.running) {
  7775. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7776. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7777. } else {
  7778. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  7779. pill.innerText = 'BGP STARTING...';
  7780. }
  7781. }
  7782. function renderBgpPeers() {
  7783. const tbody = document.getElementById('bgp-peers-table-body');
  7784. if (!tbody) return;
  7785. const empty = document.getElementById('bgp-peers-empty');
  7786. const countBadge = document.getElementById('bgp-peers-count-badge');
  7787. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7788. const peers = state.bgpPeers || [];
  7789. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7790. if (navBadge) navBadge.innerText = peers.length;
  7791. if (peers.length === 0) {
  7792. tbody.innerHTML = '';
  7793. if (empty) empty.classList.remove('hidden');
  7794. return;
  7795. }
  7796. if (empty) empty.classList.add('hidden');
  7797. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7798. if (tbody.dataset.sig === sig) return;
  7799. tbody.dataset.sig = sig;
  7800. tbody.innerHTML = peers.map(p => {
  7801. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7802. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7803. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7804. let stateBadge = '';
  7805. if (p.disabled) {
  7806. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>';
  7807. } else if (p.state === 'Established') {
  7808. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Established</span>';
  7809. } else if (p.state === 'Connect' || p.state === 'Active') {
  7810. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${p.state}</span>`;
  7811. } else {
  7812. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">${p.state || 'Idle'}</span>`;
  7813. }
  7814. return `
  7815. <tr class="hover:bg-slate-800/40 transition">
  7816. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7817. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7818. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7819. <td class="py-2.5 px-3">
  7820. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7821. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7822. </td>
  7823. <td class="py-2.5 px-3">${stateBadge}</td>
  7824. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7825. <td class="py-2.5 px-3 text-slate-300">
  7826. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7827. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7828. </td>
  7829. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7830. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  7831. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  7832. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7833. </td>
  7834. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7835. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7836. <button onclick="toggleBgpPeerState('${p.id}', ${!p.disabled})" class="px-2 py-1 rounded text-[11px] ${p.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  7837. ${p.disabled ? 'Enable' : 'Disable'}
  7838. </button>
  7839. <button onclick="openEditBgpPeerModal('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-purple-300 border border-slate-700">
  7840. Edit
  7841. </button>
  7842. <button onclick="deleteBgpPeer('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7843. Delete
  7844. </button>
  7845. </td>
  7846. </tr>
  7847. `;
  7848. }).join('');
  7849. }
  7850. function renderBgpNetworks() {
  7851. const tbody = document.getElementById('bgp-nets-table-body');
  7852. if (!tbody) return;
  7853. const empty = document.getElementById('bgp-nets-empty');
  7854. const countBadge = document.getElementById('bgp-nets-count-badge');
  7855. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7856. const nets = state.bgpNets || [];
  7857. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7858. if (navBadge) navBadge.innerText = nets.length;
  7859. if (nets.length === 0) {
  7860. tbody.innerHTML = '';
  7861. if (empty) empty.classList.remove('hidden');
  7862. return;
  7863. }
  7864. if (empty) empty.classList.add('hidden');
  7865. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7866. if (tbody.dataset.sig === sig) return;
  7867. tbody.dataset.sig = sig;
  7868. tbody.innerHTML = nets.map(n => `
  7869. <tr class="hover:bg-slate-800/40 transition">
  7870. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7871. <td class="py-2.5 px-3">
  7872. ${n.disabled
  7873. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7874. : '<span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Announcing</span>'}
  7875. </td>
  7876. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7877. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7878. <button onclick="deleteBgpNetwork('${n.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7879. Delete
  7880. </button>
  7881. </td>
  7882. </tr>
  7883. `).join('');
  7884. }
  7885. function renderBgpRoutes() {
  7886. const tbody = document.getElementById('bgp-routes-table-body');
  7887. if (!tbody) return;
  7888. const empty = document.getElementById('bgp-routes-empty');
  7889. const countBadge = document.getElementById('bgp-routes-count-badge');
  7890. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7891. const routes = state.bgpRoutes || [];
  7892. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7893. if (navBadge) navBadge.innerText = routes.length;
  7894. if (routes.length === 0) {
  7895. tbody.innerHTML = '';
  7896. if (empty) empty.classList.remove('hidden');
  7897. return;
  7898. }
  7899. if (empty) empty.classList.add('hidden');
  7900. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7901. if (tbody.dataset.sig === sig) return;
  7902. tbody.dataset.sig = sig;
  7903. tbody.innerHTML = routes.map(r => `
  7904. <tr class="hover:bg-slate-800/40 transition">
  7905. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7906. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7907. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7908. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7909. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7910. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7911. </tr>
  7912. `).join('');
  7913. }
  7914. // =========================================================================
  7915. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7916. // =========================================================================
  7917. function sortOspfTable(tab, col) {
  7918. if (!state.ospfSort) state.ospfSort = {};
  7919. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7920. if (state.ospfSort[tab].col === col) {
  7921. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7922. } else {
  7923. state.ospfSort[tab].col = col;
  7924. state.ospfSort[tab].asc = true;
  7925. }
  7926. const asc = state.ospfSort[tab].asc;
  7927. let list = [];
  7928. if (tab === 'instances') list = state.ospfInstances || [];
  7929. else if (tab === 'areas') list = state.ospfAreas || [];
  7930. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7931. else if (tab === 'templates') list = state.ospfTemplates || [];
  7932. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7933. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7934. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7935. else if (tab === 'lsa') list = state.ospfLSA || [];
  7936. list.sort((a, b) => {
  7937. let valA = a[col] ?? '';
  7938. let valB = b[col] ?? '';
  7939. if (typeof valA === 'number' && typeof valB === 'number') {
  7940. return asc ? valA - valB : valB - valA;
  7941. }
  7942. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7943. });
  7944. if (tab === 'instances') renderOspfInstances();
  7945. else if (tab === 'areas') renderOspfAreas();
  7946. else if (tab === 'ranges') renderOspfAreaRanges();
  7947. else if (tab === 'templates') renderOspfTemplates();
  7948. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7949. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7950. else if (tab === 'neighbors') renderOspfNeighbors();
  7951. else if (tab === 'lsa') renderOspfLSA();
  7952. }
  7953. function selectOspfRow(tab, id) {
  7954. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7955. state.selectedOspfRow[tab] = id;
  7956. if (tab === 'instances') {
  7957. renderOspfInstances();
  7958. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7959. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7960. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7961. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7962. if (btnEn) btnEn.disabled = false;
  7963. if (btnDis) btnDis.disabled = false;
  7964. if (btnRem) btnRem.disabled = false;
  7965. if (btnCom) btnCom.disabled = false;
  7966. } else if (tab === 'areas') {
  7967. renderOspfAreas();
  7968. const btnEn = document.getElementById('btn-ospf-area-enable');
  7969. const btnDis = document.getElementById('btn-ospf-area-disable');
  7970. const btnRem = document.getElementById('btn-ospf-area-remove');
  7971. const btnCom = document.getElementById('btn-ospf-area-comment');
  7972. if (btnEn) btnEn.disabled = false;
  7973. if (btnDis) btnDis.disabled = false;
  7974. if (btnRem) btnRem.disabled = false;
  7975. if (btnCom) btnCom.disabled = false;
  7976. } else if (tab === 'ranges') {
  7977. renderOspfAreaRanges();
  7978. const btnEn = document.getElementById('btn-ospf-range-enable');
  7979. const btnDis = document.getElementById('btn-ospf-range-disable');
  7980. const btnRem = document.getElementById('btn-ospf-range-remove');
  7981. const btnCom = document.getElementById('btn-ospf-range-comment');
  7982. if (btnEn) btnEn.disabled = false;
  7983. if (btnDis) btnDis.disabled = false;
  7984. if (btnRem) btnRem.disabled = false;
  7985. if (btnCom) btnCom.disabled = false;
  7986. } else if (tab === 'templates') {
  7987. renderOspfTemplates();
  7988. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7989. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7990. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7991. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7992. if (btnEn) btnEn.disabled = false;
  7993. if (btnDis) btnDis.disabled = false;
  7994. if (btnRem) btnRem.disabled = false;
  7995. if (btnCom) btnCom.disabled = false;
  7996. } else if (tab === 'snbrs') {
  7997. renderOspfStaticNbrs();
  7998. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7999. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8000. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8001. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8002. if (btnEn) btnEn.disabled = false;
  8003. if (btnDis) btnDis.disabled = false;
  8004. if (btnRem) btnRem.disabled = false;
  8005. if (btnCom) btnCom.disabled = false;
  8006. }
  8007. }
  8008. // TAB 1: INSTANCES
  8009. function renderOspfInstances() {
  8010. const tbody = document.getElementById('ospf-instances-table-body');
  8011. if (!tbody) return;
  8012. const countEl = document.getElementById('ospf-instances-footer-count');
  8013. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8014. let list = state.ospfInstances || [];
  8015. if (filter) {
  8016. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8017. }
  8018. if (countEl) countEl.innerText = list.length;
  8019. const selId = state.selectedOspfRow?.instances;
  8020. tbody.innerHTML = list.map((inst, idx) => {
  8021. const isSel = inst.id === selId;
  8022. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8023. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8024. return `
  8025. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8026. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8027. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8028. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8029. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8030. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8031. </td>
  8032. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8033. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8034. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8035. </tr>
  8036. `;
  8037. }).join('');
  8038. }
  8039. // TAB 2: AREAS
  8040. function renderOspfAreas() {
  8041. const tbody = document.getElementById('ospf-areas-table-body');
  8042. if (!tbody) return;
  8043. const countEl = document.getElementById('ospf-areas-footer-count');
  8044. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8045. let list = state.ospfAreas || [];
  8046. if (filter) {
  8047. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8048. }
  8049. if (countEl) countEl.innerText = list.length;
  8050. const selId = state.selectedOspfRow?.areas;
  8051. tbody.innerHTML = list.map((a, idx) => {
  8052. const isSel = a.id === selId;
  8053. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8054. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8055. return `
  8056. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8057. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8058. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8059. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8060. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8061. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8062. </td>
  8063. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8064. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8065. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8066. </tr>
  8067. `;
  8068. }).join('');
  8069. }
  8070. // TAB 3: AREA RANGES
  8071. function renderOspfAreaRanges() {
  8072. const tbody = document.getElementById('ospf-ranges-table-body');
  8073. if (!tbody) return;
  8074. const countEl = document.getElementById('ospf-ranges-footer-count');
  8075. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8076. let list = state.ospfAreaRanges || [];
  8077. if (filter) {
  8078. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8079. }
  8080. if (countEl) countEl.innerText = list.length;
  8081. const selId = state.selectedOspfRow?.['area-ranges'];
  8082. tbody.innerHTML = list.map((r, idx) => {
  8083. const isSel = r.id === selId;
  8084. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8085. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8086. return `
  8087. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8088. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8089. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8090. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8091. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8092. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8093. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8094. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8095. </tr>
  8096. `;
  8097. }).join('');
  8098. }
  8099. // TAB 4: INTERFACE TEMPLATES
  8100. function renderOspfTemplates() {
  8101. const tbody = document.getElementById('ospf-templates-table-body');
  8102. if (!tbody) return;
  8103. const countEl = document.getElementById('ospf-templates-footer-count');
  8104. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8105. let list = state.ospfTemplates || [];
  8106. if (filter) {
  8107. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8108. }
  8109. if (countEl) countEl.innerText = list.length;
  8110. const selId = state.selectedOspfRow?.templates;
  8111. tbody.innerHTML = list.map((t, idx) => {
  8112. const isSel = t.id === selId;
  8113. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8114. const ifaces = t.interfaces || t.interface || 'all';
  8115. const nets = t.networks || t.network || '';
  8116. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8117. return `
  8118. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8119. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8120. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8121. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8122. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8123. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8124. </td>
  8125. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8126. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8127. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8128. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8129. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8130. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8131. </tr>
  8132. `;
  8133. }).join('');
  8134. }
  8135. // TAB 5: LIVE INTERFACES
  8136. function renderOspfLiveInterfaces() {
  8137. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8138. if (!tbody) return;
  8139. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8140. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8141. let list = state.ospfLiveInterfaces || [];
  8142. if (filter) {
  8143. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8144. }
  8145. if (countEl) countEl.innerText = list.length;
  8146. tbody.innerHTML = list.map(i => `
  8147. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8148. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8149. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8150. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8151. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8152. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8153. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8154. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8155. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8156. </tr>
  8157. `).join('');
  8158. }
  8159. // TAB 6: STATIC NEIGHBORS
  8160. function renderOspfStaticNbrs() {
  8161. const tbody = document.getElementById('ospf-snbrs-table-body');
  8162. if (!tbody) return;
  8163. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8164. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8165. let list = state.ospfStaticNbrs || [];
  8166. if (filter) {
  8167. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8168. }
  8169. if (countEl) countEl.innerText = list.length;
  8170. const selId = state.selectedOspfRow?.['static-nbrs'];
  8171. tbody.innerHTML = list.map((n, idx) => {
  8172. const isSel = n.id === selId;
  8173. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8174. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8175. return `
  8176. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8177. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8178. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8179. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8180. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8181. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8182. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8183. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8184. </tr>
  8185. `;
  8186. }).join('');
  8187. }
  8188. // TAB 7: LIVE NEIGHBORS
  8189. function renderOspfNeighbors() {
  8190. const tbody = document.getElementById('ospf-neighbors-table-body');
  8191. if (!tbody) return;
  8192. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8193. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8194. let list = state.ospfNeighbors || [];
  8195. if (filter) {
  8196. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8197. }
  8198. if (countEl) countEl.innerText = list.length;
  8199. tbody.innerHTML = list.map(n => `
  8200. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8201. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8202. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8203. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8204. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8205. </td>
  8206. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8207. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8208. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8209. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8210. </tr>
  8211. `).join('');
  8212. }
  8213. // TAB 8: LINK-STATE DATABASE (LSA)
  8214. function renderOspfLSA() {
  8215. const tbody = document.getElementById('ospf-lsa-table-body');
  8216. if (!tbody) return;
  8217. const countEl = document.getElementById('ospf-lsa-footer-count');
  8218. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8219. let list = state.ospfLSA || [];
  8220. if (filter) {
  8221. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8222. }
  8223. if (countEl) countEl.innerText = list.length;
  8224. tbody.innerHTML = list.map(l => `
  8225. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8226. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8227. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8228. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8229. </td>
  8230. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8231. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8232. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8233. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8234. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8235. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8236. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8237. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8238. </tr>
  8239. `).join('');
  8240. }
  8241. function renderOspfStatusPill() {
  8242. // Maintained for backward compatibility
  8243. const pill = document.getElementById('ospf-live-status-pill');
  8244. if (!pill) return;
  8245. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-indigo-950 text-indigo-300 border border-indigo-800/60 font-semibold';
  8246. pill.innerText = 'OSPF ACTIVE';
  8247. }
  8248. function renderOspfInterfaces() {
  8249. renderOspfTemplates();
  8250. }
  8251. function renderOspfRoutes() {
  8252. // Routes retained in background
  8253. }
  8254. // BGP Modals & Actions
  8255. function openBgpInstanceModal() {
  8256. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8257. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8258. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8259. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8260. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8261. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8262. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8263. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8264. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8265. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8266. }
  8267. function closeBgpInstanceModal() {
  8268. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8269. }
  8270. async function submitBgpInstance(e) {
  8271. e.preventDefault();
  8272. const payload = {
  8273. enabled: document.getElementById('modal-bgp-enabled').checked,
  8274. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8275. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8276. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8277. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8278. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8279. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8280. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8281. };
  8282. try {
  8283. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8284. method: 'POST',
  8285. headers: { 'Content-Type': 'application/json' },
  8286. body: JSON.stringify(payload)
  8287. });
  8288. if (res.ok) {
  8289. closeBgpInstanceModal();
  8290. showToast('Success', 'BGP instance configuration updated', 'success');
  8291. loadDynamicRouting();
  8292. } else {
  8293. const err = await res.json();
  8294. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8295. }
  8296. } catch (err) {
  8297. showToast('Error', err.message, 'error');
  8298. }
  8299. }
  8300. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8301. function switchBgpPeerModalTab(tab) {
  8302. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8303. tabs.forEach(t => {
  8304. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8305. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8306. if (t === tab) {
  8307. if (pane) pane.classList.remove('hidden');
  8308. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8309. } else {
  8310. if (pane) pane.classList.add('hidden');
  8311. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8312. }
  8313. });
  8314. }
  8315. function addOutputNetworkRow(val = '') {
  8316. const container = document.getElementById('modal-bgp-output-networks-container');
  8317. if (!container) return;
  8318. const row = document.createElement('div');
  8319. row.className = 'flex items-center gap-2 output-net-row';
  8320. row.innerHTML = `
  8321. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  8322. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  8323. `;
  8324. container.appendChild(row);
  8325. }
  8326. function parseBgpTime(val) {
  8327. if (!val) return 0;
  8328. val = String(val).trim();
  8329. if (val.includes(':')) {
  8330. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8331. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8332. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8333. }
  8334. return parseInt(val, 10) || 0;
  8335. }
  8336. function formatBgpTime(secs) {
  8337. if (!secs || secs <= 0) return '00:00:00';
  8338. const h = Math.floor(secs / 3600);
  8339. const m = Math.floor((secs % 3600) / 60);
  8340. const s = secs % 60;
  8341. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8342. }
  8343. function populateBgpRoutingTables() {
  8344. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8345. if (!sel) return;
  8346. const cur = sel.value || 'main';
  8347. sel.innerHTML = '<option value="main">main</option>';
  8348. (state.routingTables || []).forEach(t => {
  8349. if (t.name !== 'main') {
  8350. const opt = document.createElement('option');
  8351. opt.value = t.name;
  8352. opt.innerText = t.name;
  8353. sel.appendChild(opt);
  8354. }
  8355. });
  8356. sel.value = cur;
  8357. }
  8358. function openAddBgpPeerModal() {
  8359. document.getElementById('bgp-peer-form').reset();
  8360. document.getElementById('modal-bgp-peer-id').value = '';
  8361. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8362. // General Tab
  8363. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8364. document.getElementById('modal-bgp-peer-comment').value = '';
  8365. document.getElementById('modal-bgp-peer-name').value = '';
  8366. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8367. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8368. document.getElementById('modal-bgp-peer-local-as').value = '';
  8369. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8370. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8371. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8372. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8373. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8374. document.getElementById('modal-bgp-peer-router-id').value = '';
  8375. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8376. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8377. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8378. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8379. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8380. document.getElementById('modal-bgp-peer-local-port').value = '';
  8381. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8382. document.getElementById('modal-bgp-peer-password').value = '';
  8383. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8384. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8385. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8386. document.getElementById('modal-bgp-peer-connect').checked = true;
  8387. document.getElementById('modal-bgp-peer-listen').checked = true;
  8388. // Extra Tab
  8389. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8390. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8391. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8392. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8393. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8394. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8395. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8396. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8397. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8398. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8399. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8400. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8401. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8402. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8403. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8404. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8405. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8406. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8407. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8408. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8409. // Attributes Tab
  8410. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8411. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8412. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8413. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8414. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8415. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8416. // Filter Tab
  8417. populateFilterChainsDatalist();
  8418. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8419. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8420. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8421. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8422. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8423. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8424. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8425. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8426. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8427. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8428. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8429. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8430. populateBgpRoutingTables();
  8431. const container = document.getElementById('modal-bgp-output-networks-container');
  8432. if (container) {
  8433. container.innerHTML = '';
  8434. addOutputNetworkRow('');
  8435. }
  8436. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8437. if (removeBtn) removeBtn.classList.add('hidden');
  8438. switchBgpPeerModalTab('general');
  8439. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8440. }
  8441. function populateFilterChainsDatalist() {
  8442. const dl = document.getElementById('filter-chains-list');
  8443. if (!dl) return;
  8444. const chains = new Set();
  8445. (state.routingFilters || []).forEach(f => {
  8446. if (f.chain) chains.add(f.chain);
  8447. });
  8448. if (chains.size === 0) {
  8449. chains.add('awmn');
  8450. chains.add('bgp-in');
  8451. chains.add('bgp-out');
  8452. }
  8453. dl.innerHTML = '';
  8454. chains.forEach(c => {
  8455. const opt = document.createElement('option');
  8456. opt.value = c;
  8457. dl.appendChild(opt);
  8458. });
  8459. }
  8460. function openEditBgpPeerModal(id) {
  8461. const p = (state.bgpPeers || []).find(item => item.id === id);
  8462. if (!p) return;
  8463. populateBgpRoutingTables();
  8464. populateFilterChainsDatalist();
  8465. document.getElementById('modal-bgp-peer-id').value = p.id;
  8466. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8467. // General Tab
  8468. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8469. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8470. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8471. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8472. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8473. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8474. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8475. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8476. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8477. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8478. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8479. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8480. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8481. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8482. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8483. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8484. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8485. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8486. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8487. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8488. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8489. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8490. // Extra Tab
  8491. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8492. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8493. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8494. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8495. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8496. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8497. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8498. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8499. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8500. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8501. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8502. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8503. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8504. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8505. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8506. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8507. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8508. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8509. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8510. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8511. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8512. // Attributes Tab
  8513. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8514. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8515. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8516. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8517. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8518. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8519. // Filter Tab
  8520. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8521. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8522. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8523. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8524. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8525. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8526. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8527. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8528. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8529. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8530. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8531. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8532. // Output Networks
  8533. const container = document.getElementById('modal-bgp-output-networks-container');
  8534. if (container) {
  8535. container.innerHTML = '';
  8536. if (p.output_networks && p.output_networks.length > 0) {
  8537. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8538. } else {
  8539. addOutputNetworkRow('');
  8540. }
  8541. }
  8542. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8543. if (removeBtn) removeBtn.classList.remove('hidden');
  8544. switchBgpPeerModalTab('general');
  8545. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8546. }
  8547. function copyCurrentBgpPeer() {
  8548. document.getElementById('modal-bgp-peer-id').value = '';
  8549. const nameEl = document.getElementById('modal-bgp-peer-name');
  8550. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8551. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8552. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8553. if (removeBtn) removeBtn.classList.add('hidden');
  8554. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8555. }
  8556. function removeCurrentBgpPeer() {
  8557. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8558. if (!id) return;
  8559. deleteBgpPeer(id);
  8560. closeBgpPeerModal();
  8561. }
  8562. function closeBgpPeerModal() {
  8563. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8564. }
  8565. function getBgpPeerFormData() {
  8566. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8567. const outputNetworks = [];
  8568. netInputs.forEach(inp => {
  8569. const v = inp.value.trim();
  8570. if (v) outputNetworks.push(v);
  8571. });
  8572. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8573. return {
  8574. id: document.getElementById('modal-bgp-peer-id').value,
  8575. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8576. enabled: enabled,
  8577. disabled: !enabled,
  8578. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8579. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8580. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8581. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8582. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8583. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8584. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8585. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8586. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8587. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8588. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8589. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8590. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8591. password: document.getElementById('modal-bgp-peer-password').value,
  8592. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8593. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8594. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8595. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8596. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8597. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8598. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8599. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8600. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8601. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8602. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8603. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8604. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8605. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8606. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8607. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8608. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8609. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8610. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8611. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8612. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8613. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8614. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8615. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8616. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8617. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8618. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8619. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8620. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8621. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8622. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8623. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8624. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8625. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8626. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8627. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8628. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8629. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8630. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8631. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8632. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8633. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8634. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8635. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8636. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8637. output_networks: outputNetworks
  8638. };
  8639. }
  8640. async function submitBgpPeer(e) {
  8641. if (e) e.preventDefault();
  8642. const payload = getBgpPeerFormData();
  8643. try {
  8644. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8645. method: 'POST',
  8646. headers: { 'Content-Type': 'application/json' },
  8647. body: JSON.stringify(payload)
  8648. });
  8649. if (res.ok) {
  8650. closeBgpPeerModal();
  8651. showToast('Success', 'BGP Connection saved', 'success');
  8652. loadDynamicRouting();
  8653. } else {
  8654. const err = await res.json();
  8655. showToast('Error', err.error || 'Failed to save peer', 'error');
  8656. }
  8657. } catch (err) {
  8658. showToast('Error', err.message, 'error');
  8659. }
  8660. }
  8661. async function applyBgpPeerModal(e) {
  8662. if (e) e.preventDefault();
  8663. const payload = getBgpPeerFormData();
  8664. try {
  8665. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8666. method: 'POST',
  8667. headers: { 'Content-Type': 'application/json' },
  8668. body: JSON.stringify(payload)
  8669. });
  8670. if (res.ok) {
  8671. const data = await res.json();
  8672. if (data.peer && data.peer.id) {
  8673. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8674. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8675. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8676. }
  8677. showToast('Applied', 'BGP Connection applied', 'success');
  8678. loadDynamicRouting();
  8679. } else {
  8680. const err = await res.json();
  8681. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8682. }
  8683. } catch (err) {
  8684. showToast('Error', err.message, 'error');
  8685. }
  8686. }
  8687. async function deleteBgpPeer(id) {
  8688. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8689. try {
  8690. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8691. if (res.ok) {
  8692. showToast('Deleted', 'BGP peer removed', 'success');
  8693. loadDynamicRouting();
  8694. }
  8695. } catch (err) {
  8696. showToast('Error', err.message, 'error');
  8697. }
  8698. }
  8699. async function toggleBgpPeerState(id, disabled) {
  8700. try {
  8701. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8702. method: 'POST',
  8703. headers: { 'Content-Type': 'application/json' },
  8704. body: JSON.stringify({ disabled })
  8705. });
  8706. if (res.ok) {
  8707. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8708. loadDynamicRouting();
  8709. }
  8710. } catch (err) {
  8711. showToast('Error', err.message, 'error');
  8712. }
  8713. }
  8714. function openAddBgpNetworkModal() {
  8715. document.getElementById('bgp-network-form').reset();
  8716. document.getElementById('modal-bgp-net-id').value = '';
  8717. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8718. }
  8719. function closeBgpNetworkModal() {
  8720. document.getElementById('bgp-network-modal').classList.add('hidden');
  8721. }
  8722. async function submitBgpNetwork(e) {
  8723. e.preventDefault();
  8724. const payload = {
  8725. id: document.getElementById('modal-bgp-net-id').value,
  8726. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8727. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8728. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8729. };
  8730. try {
  8731. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8732. method: 'POST',
  8733. headers: { 'Content-Type': 'application/json' },
  8734. body: JSON.stringify(payload)
  8735. });
  8736. if (res.ok) {
  8737. closeBgpNetworkModal();
  8738. showToast('Success', 'BGP network advertisement saved', 'success');
  8739. loadDynamicRouting();
  8740. } else {
  8741. const err = await res.json();
  8742. showToast('Error', err.error || 'Failed to save network', 'error');
  8743. }
  8744. } catch (err) {
  8745. showToast('Error', err.message, 'error');
  8746. }
  8747. }
  8748. async function deleteBgpNetwork(id) {
  8749. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8750. try {
  8751. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8752. if (res.ok) {
  8753. showToast('Deleted', 'Network advertisement removed', 'success');
  8754. loadDynamicRouting();
  8755. }
  8756. } catch (err) {
  8757. showToast('Error', err.message, 'error');
  8758. }
  8759. }
  8760. // =========================================================================
  8761. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8762. // =========================================================================
  8763. // --- 1. OSPF INSTANCE ---
  8764. function openOspfInstanceModal(id = null) {
  8765. const isEdit = !!id;
  8766. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8767. id: '',
  8768. name: 'Default',
  8769. version: 2,
  8770. vrf: 'main',
  8771. router_id: '192.168.131.56',
  8772. routing_table: 'main',
  8773. enabled: true,
  8774. redistribute_connected: false,
  8775. redistribute_static: true,
  8776. redistribute_bgp: false,
  8777. comment: ''
  8778. };
  8779. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8780. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8781. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8782. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8783. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8784. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8785. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8786. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8787. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8788. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8789. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8790. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8791. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8792. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8793. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8794. }
  8795. function openEditOspfInstanceModal(id) {
  8796. openOspfInstanceModal(id);
  8797. }
  8798. function closeOspfInstanceModal() {
  8799. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8800. }
  8801. async function submitOspfInstance(e) {
  8802. if (e) e.preventDefault();
  8803. const payload = {
  8804. id: document.getElementById('modal-ospf-inst-id').value,
  8805. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8806. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8807. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8808. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8809. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8810. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8811. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8812. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8813. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8814. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8815. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8816. };
  8817. try {
  8818. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8819. method: 'POST',
  8820. headers: { 'Content-Type': 'application/json' },
  8821. body: JSON.stringify(payload)
  8822. });
  8823. if (res.ok) {
  8824. closeOspfInstanceModal();
  8825. showToast('Saved', 'OSPF instance updated', 'success');
  8826. loadDynamicRouting();
  8827. } else {
  8828. const err = await res.json();
  8829. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8830. }
  8831. } catch (err) {
  8832. showToast('Error', err.message, 'error');
  8833. }
  8834. }
  8835. function applyOspfInstanceForm() {
  8836. submitOspfInstance(null);
  8837. }
  8838. function copyOspfInstance() {
  8839. document.getElementById('modal-ospf-inst-id').value = '';
  8840. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8841. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8842. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8843. }
  8844. async function deleteCurrentOspfInstance() {
  8845. const id = document.getElementById('modal-ospf-inst-id').value;
  8846. if (!id) return;
  8847. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8848. try {
  8849. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8850. if (res.ok) {
  8851. closeOspfInstanceModal();
  8852. showToast('Removed', 'OSPF instance deleted', 'success');
  8853. loadDynamicRouting();
  8854. }
  8855. } catch (err) {
  8856. showToast('Error', err.message, 'error');
  8857. }
  8858. }
  8859. async function enableSelectedOspfInstance() {
  8860. const id = state.selectedOspfRow?.instances;
  8861. if (!id) return;
  8862. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8863. method: 'POST',
  8864. headers: { 'Content-Type': 'application/json' },
  8865. body: JSON.stringify({ disabled: false })
  8866. });
  8867. loadDynamicRouting();
  8868. }
  8869. async function disableSelectedOspfInstance() {
  8870. const id = state.selectedOspfRow?.instances;
  8871. if (!id) return;
  8872. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8873. method: 'POST',
  8874. headers: { 'Content-Type': 'application/json' },
  8875. body: JSON.stringify({ disabled: true })
  8876. });
  8877. loadDynamicRouting();
  8878. }
  8879. async function removeSelectedOspfInstance() {
  8880. const id = state.selectedOspfRow?.instances;
  8881. if (!id) return;
  8882. if (!confirm('Delete selected OSPF instance?')) return;
  8883. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8884. loadDynamicRouting();
  8885. }
  8886. async function promptCommentOspfInstance() {
  8887. const id = state.selectedOspfRow?.instances;
  8888. if (!id) return;
  8889. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8890. if (!inst) return;
  8891. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8892. if (comment === null) return;
  8893. inst.comment = comment;
  8894. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8895. method: 'POST',
  8896. headers: { 'Content-Type': 'application/json' },
  8897. body: JSON.stringify(inst)
  8898. });
  8899. loadDynamicRouting();
  8900. }
  8901. // --- 2. OSPF AREA ---
  8902. function populateOspfAreaDropdowns() {
  8903. const instSelect = document.getElementById('modal-ospf-area-instance');
  8904. if (instSelect) {
  8905. const cur = instSelect.value;
  8906. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8907. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8908. if (cur) instSelect.value = cur;
  8909. }
  8910. }
  8911. function openOspfAreaModal(id = null) {
  8912. const isEdit = !!id;
  8913. populateOspfAreaDropdowns();
  8914. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8915. id: '',
  8916. name: 'Default',
  8917. instance: 'Default',
  8918. area_id: '0.0.0.0',
  8919. area_type: 'default',
  8920. default_cost: 1,
  8921. no_summaries: false,
  8922. disabled: false,
  8923. comment: ''
  8924. };
  8925. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8926. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8927. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8928. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8929. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8930. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8931. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8932. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8933. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8934. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8935. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8936. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8937. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8938. }
  8939. function openEditOspfAreaModal(id) {
  8940. openOspfAreaModal(id);
  8941. }
  8942. function closeOspfAreaModal() {
  8943. document.getElementById('ospf-area-modal').classList.add('hidden');
  8944. }
  8945. async function submitOspfArea(e) {
  8946. if (e) e.preventDefault();
  8947. const payload = {
  8948. id: document.getElementById('modal-ospf-area-id').value,
  8949. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8950. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8951. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8952. area_type: document.getElementById('modal-ospf-area-type').value,
  8953. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8954. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8955. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8956. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8957. };
  8958. try {
  8959. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8960. method: 'POST',
  8961. headers: { 'Content-Type': 'application/json' },
  8962. body: JSON.stringify(payload)
  8963. });
  8964. if (res.ok) {
  8965. closeOspfAreaModal();
  8966. showToast('Saved', 'OSPF area saved', 'success');
  8967. loadDynamicRouting();
  8968. } else {
  8969. const err = await res.json();
  8970. showToast('Error', err.error || 'Failed to save area', 'error');
  8971. }
  8972. } catch (err) {
  8973. showToast('Error', err.message, 'error');
  8974. }
  8975. }
  8976. function applyOspfAreaForm() {
  8977. submitOspfArea(null);
  8978. }
  8979. function copyOspfArea() {
  8980. document.getElementById('modal-ospf-area-id').value = '';
  8981. document.getElementById('modal-ospf-area-name').value += '-copy';
  8982. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8983. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8984. }
  8985. async function deleteCurrentOspfArea() {
  8986. const id = document.getElementById('modal-ospf-area-id').value;
  8987. if (!id) return;
  8988. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8989. try {
  8990. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8991. if (res.ok) {
  8992. closeOspfAreaModal();
  8993. showToast('Removed', 'OSPF area deleted', 'success');
  8994. loadDynamicRouting();
  8995. }
  8996. } catch (err) {
  8997. showToast('Error', err.message, 'error');
  8998. }
  8999. }
  9000. async function enableSelectedOspfArea() {
  9001. const id = state.selectedOspfRow?.areas;
  9002. if (!id) return;
  9003. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9004. method: 'POST',
  9005. headers: { 'Content-Type': 'application/json' },
  9006. body: JSON.stringify({ disabled: false })
  9007. });
  9008. loadDynamicRouting();
  9009. }
  9010. async function disableSelectedOspfArea() {
  9011. const id = state.selectedOspfRow?.areas;
  9012. if (!id) return;
  9013. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9014. method: 'POST',
  9015. headers: { 'Content-Type': 'application/json' },
  9016. body: JSON.stringify({ disabled: true })
  9017. });
  9018. loadDynamicRouting();
  9019. }
  9020. async function removeSelectedOspfArea() {
  9021. const id = state.selectedOspfRow?.areas;
  9022. if (!id) return;
  9023. if (!confirm('Delete selected OSPF area?')) return;
  9024. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9025. loadDynamicRouting();
  9026. }
  9027. async function promptCommentOspfArea() {
  9028. const id = state.selectedOspfRow?.areas;
  9029. if (!id) return;
  9030. const area = (state.ospfAreas || []).find(a => a.id === id);
  9031. if (!area) return;
  9032. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9033. if (comment === null) return;
  9034. area.comment = comment;
  9035. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9036. method: 'POST',
  9037. headers: { 'Content-Type': 'application/json' },
  9038. body: JSON.stringify(area)
  9039. });
  9040. loadDynamicRouting();
  9041. }
  9042. // --- 3. OSPF AREA RANGE ---
  9043. function populateAreaRangeDropdowns() {
  9044. const select = document.getElementById('modal-ospf-range-area');
  9045. if (select) {
  9046. const cur = select.value;
  9047. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9048. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9049. if (cur) select.value = cur;
  9050. }
  9051. }
  9052. function openOspfAreaRangeModal(id = null) {
  9053. const isEdit = !!id;
  9054. populateAreaRangeDropdowns();
  9055. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9056. id: '',
  9057. area: 'Default',
  9058. prefix: '',
  9059. cost: 1,
  9060. advertise: true,
  9061. disabled: false,
  9062. comment: ''
  9063. };
  9064. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9065. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9066. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9067. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9068. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9069. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9070. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9071. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9072. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9073. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9074. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9075. }
  9076. function openEditOspfAreaRangeModal(id) {
  9077. openOspfAreaRangeModal(id);
  9078. }
  9079. function closeOspfAreaRangeModal() {
  9080. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9081. }
  9082. async function submitOspfAreaRange(e) {
  9083. if (e) e.preventDefault();
  9084. const payload = {
  9085. id: document.getElementById('modal-ospf-range-id').value,
  9086. area: document.getElementById('modal-ospf-range-area').value,
  9087. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9088. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9089. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9090. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9091. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9092. };
  9093. try {
  9094. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9095. method: 'POST',
  9096. headers: { 'Content-Type': 'application/json' },
  9097. body: JSON.stringify(payload)
  9098. });
  9099. if (res.ok) {
  9100. closeOspfAreaRangeModal();
  9101. showToast('Saved', 'Area range saved', 'success');
  9102. loadDynamicRouting();
  9103. } else {
  9104. const err = await res.json();
  9105. showToast('Error', err.error || 'Failed to save area range', 'error');
  9106. }
  9107. } catch (err) {
  9108. showToast('Error', err.message, 'error');
  9109. }
  9110. }
  9111. function applyOspfAreaRangeForm() {
  9112. submitOspfAreaRange(null);
  9113. }
  9114. async function deleteCurrentOspfAreaRange() {
  9115. const id = document.getElementById('modal-ospf-range-id').value;
  9116. if (!id) return;
  9117. if (!confirm('Delete this area range?')) return;
  9118. try {
  9119. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9120. closeOspfAreaRangeModal();
  9121. showToast('Removed', 'Area range removed', 'success');
  9122. loadDynamicRouting();
  9123. } catch (err) {
  9124. showToast('Error', err.message, 'error');
  9125. }
  9126. }
  9127. async function enableSelectedOspfAreaRange() {
  9128. const id = state.selectedOspfRow?.['area-ranges'];
  9129. if (!id) return;
  9130. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9131. if (!r) return;
  9132. r.disabled = false;
  9133. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9134. loadDynamicRouting();
  9135. }
  9136. async function disableSelectedOspfAreaRange() {
  9137. const id = state.selectedOspfRow?.['area-ranges'];
  9138. if (!id) return;
  9139. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9140. if (!r) return;
  9141. r.disabled = true;
  9142. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9143. loadDynamicRouting();
  9144. }
  9145. async function removeSelectedOspfAreaRange() {
  9146. const id = state.selectedOspfRow?.['area-ranges'];
  9147. if (!id) return;
  9148. if (!confirm('Delete selected area range?')) return;
  9149. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9150. loadDynamicRouting();
  9151. }
  9152. async function promptCommentOspfAreaRange() {
  9153. const id = state.selectedOspfRow?.['area-ranges'];
  9154. if (!id) return;
  9155. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9156. if (!r) return;
  9157. const comment = prompt('Enter comment for area range:', r.comment || '');
  9158. if (comment === null) return;
  9159. r.comment = comment;
  9160. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9161. loadDynamicRouting();
  9162. }
  9163. // --- 4. OSPF INTERFACE TEMPLATE ---
  9164. function switchOspfTemplateTab(tab) {
  9165. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9166. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9167. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9168. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9169. if (tab === 'general') {
  9170. if (tabGen) tabGen.classList.remove('hidden');
  9171. if (tabAuth) tabAuth.classList.add('hidden');
  9172. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9173. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9174. } else {
  9175. if (tabGen) tabGen.classList.add('hidden');
  9176. if (tabAuth) tabAuth.classList.remove('hidden');
  9177. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9178. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9179. }
  9180. }
  9181. function populateTemplateAreaDropdowns() {
  9182. const select = document.getElementById('modal-ospf-tmpl-area');
  9183. if (select) {
  9184. const cur = select.value;
  9185. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9186. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9187. if (cur) select.value = cur;
  9188. }
  9189. }
  9190. function openOspfTemplateModal(id = null) {
  9191. const isEdit = !!id;
  9192. populateTemplateAreaDropdowns();
  9193. switchOspfTemplateTab('general');
  9194. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9195. id: '',
  9196. interfaces: '',
  9197. area: 'Default',
  9198. networks: '',
  9199. network_type: 'broadcast',
  9200. cost: 1,
  9201. priority: 128,
  9202. passive: false,
  9203. hello_interval: 10,
  9204. dead_interval: 40,
  9205. auth: 'none',
  9206. auth_key: '',
  9207. disabled: false,
  9208. comment: ''
  9209. };
  9210. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9211. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9212. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9213. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9214. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9215. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9216. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9217. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9218. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9219. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9220. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9221. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9222. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9223. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9224. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9225. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9226. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9227. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9228. }
  9229. function openEditOspfTemplateModal(id) {
  9230. openOspfTemplateModal(id);
  9231. }
  9232. function closeOspfTemplateModal() {
  9233. document.getElementById('ospf-template-modal').classList.add('hidden');
  9234. }
  9235. async function submitOspfTemplate(e) {
  9236. if (e) e.preventDefault();
  9237. const payload = {
  9238. id: document.getElementById('modal-ospf-tmpl-id').value,
  9239. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9240. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9241. area: document.getElementById('modal-ospf-tmpl-area').value,
  9242. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9243. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9244. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9245. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9246. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9247. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9248. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9249. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9250. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9251. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9252. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9253. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9254. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9255. };
  9256. try {
  9257. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9258. method: 'POST',
  9259. headers: { 'Content-Type': 'application/json' },
  9260. body: JSON.stringify(payload)
  9261. });
  9262. if (res.ok) {
  9263. closeOspfTemplateModal();
  9264. showToast('Saved', 'Interface template saved', 'success');
  9265. loadDynamicRouting();
  9266. } else {
  9267. const err = await res.json();
  9268. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9269. }
  9270. } catch (err) {
  9271. showToast('Error', err.message, 'error');
  9272. }
  9273. }
  9274. function applyOspfTemplateForm() {
  9275. submitOspfTemplate(null);
  9276. }
  9277. function copyOspfTemplate() {
  9278. document.getElementById('modal-ospf-tmpl-id').value = '';
  9279. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9280. showToast('Copied', 'Duplicated as new template', 'info');
  9281. }
  9282. async function deleteCurrentOspfTemplate() {
  9283. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9284. if (!id) return;
  9285. if (!confirm('Delete this interface template?')) return;
  9286. try {
  9287. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9288. closeOspfTemplateModal();
  9289. showToast('Removed', 'Interface template deleted', 'success');
  9290. loadDynamicRouting();
  9291. } catch (err) {
  9292. showToast('Error', err.message, 'error');
  9293. }
  9294. }
  9295. async function enableSelectedOspfTemplate() {
  9296. const id = state.selectedOspfRow?.templates;
  9297. if (!id) return;
  9298. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9299. method: 'POST',
  9300. headers: { 'Content-Type': 'application/json' },
  9301. body: JSON.stringify({ disabled: false })
  9302. });
  9303. loadDynamicRouting();
  9304. }
  9305. async function disableSelectedOspfTemplate() {
  9306. const id = state.selectedOspfRow?.templates;
  9307. if (!id) return;
  9308. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9309. method: 'POST',
  9310. headers: { 'Content-Type': 'application/json' },
  9311. body: JSON.stringify({ disabled: true })
  9312. });
  9313. loadDynamicRouting();
  9314. }
  9315. async function removeSelectedOspfTemplate() {
  9316. const id = state.selectedOspfRow?.templates;
  9317. if (!id) return;
  9318. if (!confirm('Delete selected interface template?')) return;
  9319. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9320. loadDynamicRouting();
  9321. }
  9322. async function promptCommentOspfTemplate() {
  9323. const id = state.selectedOspfRow?.templates;
  9324. if (!id) return;
  9325. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9326. if (!tmpl) return;
  9327. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9328. if (comment === null) return;
  9329. tmpl.comment = comment;
  9330. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9331. method: 'POST',
  9332. headers: { 'Content-Type': 'application/json' },
  9333. body: JSON.stringify(tmpl)
  9334. });
  9335. loadDynamicRouting();
  9336. }
  9337. // --- 5. OSPF STATIC NEIGHBOR ---
  9338. function populateStaticNbrAreaDropdowns() {
  9339. const select = document.getElementById('modal-ospf-snbr-area');
  9340. if (select) {
  9341. const cur = select.value;
  9342. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9343. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9344. if (cur) select.value = cur;
  9345. }
  9346. }
  9347. function openOspfStaticNbrModal(id = null) {
  9348. const isEdit = !!id;
  9349. populateStaticNbrAreaDropdowns();
  9350. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9351. id: '',
  9352. address: '',
  9353. area: 'Default',
  9354. poll_interval: 120,
  9355. cost: 1,
  9356. disabled: false,
  9357. comment: ''
  9358. };
  9359. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9360. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9361. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9362. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9363. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9364. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9365. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9366. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9367. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9368. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9369. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9370. }
  9371. function openEditOspfStaticNbrModal(id) {
  9372. openOspfStaticNbrModal(id);
  9373. }
  9374. function closeOspfStaticNbrModal() {
  9375. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9376. }
  9377. async function submitOspfStaticNbr(e) {
  9378. if (e) e.preventDefault();
  9379. const payload = {
  9380. id: document.getElementById('modal-ospf-snbr-id').value,
  9381. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9382. area: document.getElementById('modal-ospf-snbr-area').value,
  9383. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9384. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9385. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9386. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9387. };
  9388. try {
  9389. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9390. method: 'POST',
  9391. headers: { 'Content-Type': 'application/json' },
  9392. body: JSON.stringify(payload)
  9393. });
  9394. if (res.ok) {
  9395. closeOspfStaticNbrModal();
  9396. showToast('Saved', 'Static neighbor saved', 'success');
  9397. loadDynamicRouting();
  9398. } else {
  9399. const err = await res.json();
  9400. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9401. }
  9402. } catch (err) {
  9403. showToast('Error', err.message, 'error');
  9404. }
  9405. }
  9406. function applyOspfStaticNbrForm() {
  9407. submitOspfStaticNbr(null);
  9408. }
  9409. async function deleteCurrentOspfStaticNbr() {
  9410. const id = document.getElementById('modal-ospf-snbr-id').value;
  9411. if (!id) return;
  9412. if (!confirm('Delete this static neighbor?')) return;
  9413. try {
  9414. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9415. closeOspfStaticNbrModal();
  9416. showToast('Removed', 'Static neighbor removed', 'success');
  9417. loadDynamicRouting();
  9418. } catch (err) {
  9419. showToast('Error', err.message, 'error');
  9420. }
  9421. }
  9422. async function enableSelectedOspfStaticNbr() {
  9423. const id = state.selectedOspfRow?.['static-nbrs'];
  9424. if (!id) return;
  9425. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9426. if (!n) return;
  9427. n.disabled = false;
  9428. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9429. loadDynamicRouting();
  9430. }
  9431. async function disableSelectedOspfStaticNbr() {
  9432. const id = state.selectedOspfRow?.['static-nbrs'];
  9433. if (!id) return;
  9434. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9435. if (!n) return;
  9436. n.disabled = true;
  9437. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9438. loadDynamicRouting();
  9439. }
  9440. async function removeSelectedOspfStaticNbr() {
  9441. const id = state.selectedOspfRow?.['static-nbrs'];
  9442. if (!id) return;
  9443. if (!confirm('Delete selected static neighbor?')) return;
  9444. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9445. loadDynamicRouting();
  9446. }
  9447. async function promptCommentOspfStaticNbr() {
  9448. const id = state.selectedOspfRow?.['static-nbrs'];
  9449. if (!id) return;
  9450. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9451. if (!n) return;
  9452. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9453. if (comment === null) return;
  9454. n.comment = comment;
  9455. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9456. loadDynamicRouting();
  9457. }
  9458. // Backward-compat aliases
  9459. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9460. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9461. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9462. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9463. function deleteOspfInterface(id) {
  9464. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9465. }
  9466. function toggleOspfInterfaceState(id, disabled) {
  9467. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9468. method: 'POST',
  9469. headers: { 'Content-Type': 'application/json' },
  9470. body: JSON.stringify({ disabled })
  9471. }).then(() => loadDynamicRouting());
  9472. }
  9473. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9474. function deleteOspfArea(id) {
  9475. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9476. }
  9477. // ============================================================================
  9478. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9479. // ============================================================================
  9480. function switchBridgeSubTab(tab) {
  9481. state.bridgeSubTab = tab;
  9482. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9483. tabs.forEach(t => {
  9484. const panel = document.getElementById(`bridge-subtab-${t}`);
  9485. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9486. if (panel) {
  9487. if (t === tab) panel.classList.remove('hidden');
  9488. else panel.classList.add('hidden');
  9489. }
  9490. if (btn) {
  9491. if (t === tab) {
  9492. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg bg-slate-800 text-white shadow-sm transition flex items-center gap-2';
  9493. } else {
  9494. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  9495. }
  9496. }
  9497. });
  9498. const addBtn = document.getElementById('bridge-top-action-btn');
  9499. if (addBtn) {
  9500. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9501. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9502. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9503. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9504. }
  9505. if (tab === 'hosts') loadBridgeHosts();
  9506. setTimeout(initTableSorting, 50);
  9507. }
  9508. function openCurrentBridgeModal() {
  9509. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9510. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9511. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9512. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9513. }
  9514. async function loadBridge() {
  9515. try {
  9516. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9517. fetch(`${API_BASE}/bridge/bridges`),
  9518. fetch(`${API_BASE}/bridge/ports`),
  9519. fetch(`${API_BASE}/bridge/vlans`),
  9520. fetch(`${API_BASE}/bridge/summary`),
  9521. fetch(`${API_BASE}/vpn/eoip`),
  9522. fetch(`${API_BASE}/vlans`)
  9523. ]);
  9524. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9525. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9526. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9527. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9528. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9529. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9530. // Badges & Stats
  9531. const bBridges = document.getElementById('bridge-badge-bridges');
  9532. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9533. const bPorts = document.getElementById('bridge-badge-ports');
  9534. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9535. const bVlans = document.getElementById('bridge-badge-vlans');
  9536. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9537. const bHosts = document.getElementById('bridge-badge-hosts');
  9538. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9539. const sBr = document.getElementById('bridge-stat-bridges');
  9540. if (sBr) sBr.innerText = (state.bridges || []).length;
  9541. const sPorts = document.getElementById('bridge-stat-ports');
  9542. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9543. const sHosts = document.getElementById('bridge-stat-hosts');
  9544. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9545. renderBridges();
  9546. renderBridgePorts();
  9547. renderBridgeVLANs();
  9548. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9549. } catch (err) {
  9550. console.error('Failed to load bridge subsystem:', err);
  9551. }
  9552. }
  9553. // ----------------- Bridges -----------------
  9554. function renderBridges() {
  9555. const tbody = document.getElementById('bridge-table-body');
  9556. const empty = document.getElementById('bridge-empty-bridges');
  9557. const countBadge = document.getElementById('bridge-count-badge');
  9558. if (!tbody) return;
  9559. tbody.innerHTML = '';
  9560. const bridges = state.bridges || [];
  9561. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9562. if (bridges.length === 0) {
  9563. empty?.classList.remove('hidden');
  9564. return;
  9565. }
  9566. empty?.classList.add('hidden');
  9567. bridges.forEach((b, idx) => {
  9568. const tr = document.createElement('tr');
  9569. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9570. // Format IP addresses pill list
  9571. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9572. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9573. ipsHtml = b.ip_addresses.map(ip => `
  9574. <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono bg-sky-950/80 border border-sky-800/40 text-sky-300">
  9575. <span>${ip}</span>
  9576. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9577. </span>
  9578. `).join(' ');
  9579. }
  9580. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9581. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9582. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9583. tr.innerHTML = `
  9584. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9585. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9586. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9587. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9588. </td>
  9589. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9590. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9591. <td class="py-2.5 px-3">
  9592. <span class="px-1.5 py-0.5 rounded text-[10px] font-bold ${b.stp === 'none' ? 'bg-slate-800 text-slate-400' : 'bg-sky-950 text-sky-300 border border-sky-800/40'} uppercase">${b.stp}</span>
  9593. </td>
  9594. <td class="py-2.5 px-3 text-center">
  9595. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9596. </td>
  9597. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9598. <td class="py-2.5 px-3">
  9599. <span class="px-2 py-0.5 rounded-full text-[10px] font-bold ${b.ports_count > 0 ? 'bg-sky-950 text-sky-400 border border-sky-800/40' : 'bg-slate-800 text-slate-500'} font-mono">${b.ports_count}</span>
  9600. </td>
  9601. <td class="py-2.5 px-3">
  9602. <div class="flex items-center gap-1.5 flex-wrap">
  9603. ${ipsHtml}
  9604. <button onclick="openAddBridgeIPModal('${b.id}', '${b.name}')" class="px-1.5 py-0.2 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 font-sans" title="Add IP to Bridge">+ IP</button>
  9605. </div>
  9606. </td>
  9607. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9608. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9609. </td>
  9610. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9611. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9612. <button onclick="toggleBridgeState('${b.id}', ${!b.disabled})" class="text-xs ${b.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${b.disabled ? 'Enable' : 'Disable'}</button>
  9613. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9614. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9615. </td>
  9616. `;
  9617. tbody.appendChild(tr);
  9618. });
  9619. }
  9620. function openAddBridgeModal() {
  9621. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9622. document.getElementById('bridge-modal-id').value = '';
  9623. document.getElementById('bridge-modal-name').value = 'bridge1';
  9624. document.getElementById('bridge-modal-name').disabled = false;
  9625. document.getElementById('bridge-modal-mtu').value = '1500';
  9626. document.getElementById('bridge-modal-mac').value = '';
  9627. document.getElementById('bridge-modal-stp').value = 'rstp';
  9628. document.getElementById('bridge-modal-priority').value = '32768';
  9629. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9630. document.getElementById('bridge-modal-pvid').value = '1';
  9631. document.getElementById('bridge-modal-fastforward').checked = true;
  9632. document.getElementById('bridge-modal-comment').value = '';
  9633. document.getElementById('bridge-modal-disabled').checked = false;
  9634. toggleBridgeModalVlanFiltering();
  9635. document.getElementById('bridge-modal').classList.remove('hidden');
  9636. }
  9637. function openEditBridgeModal(id) {
  9638. const b = (state.bridges || []).find(x => x.id === id);
  9639. if (!b) return;
  9640. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9641. document.getElementById('bridge-modal-id').value = b.id;
  9642. document.getElementById('bridge-modal-name').value = b.name;
  9643. document.getElementById('bridge-modal-name').disabled = true;
  9644. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9645. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9646. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9647. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9648. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9649. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9650. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9651. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9652. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9653. toggleBridgeModalVlanFiltering();
  9654. document.getElementById('bridge-modal').classList.remove('hidden');
  9655. }
  9656. function closeBridgeModal() {
  9657. document.getElementById('bridge-modal').classList.add('hidden');
  9658. }
  9659. function toggleBridgeModalVlanFiltering() {
  9660. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9661. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9662. if (pvidBox) {
  9663. if (chk) pvidBox.classList.remove('opacity-40');
  9664. else pvidBox.classList.add('opacity-40');
  9665. }
  9666. }
  9667. async function submitSaveBridge(e) {
  9668. e.preventDefault();
  9669. const id = document.getElementById('bridge-modal-id').value;
  9670. const name = document.getElementById('bridge-modal-name').value.trim();
  9671. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9672. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9673. const stp = document.getElementById('bridge-modal-stp').value;
  9674. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9675. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9676. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9677. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9678. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9679. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9680. try {
  9681. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9682. method: 'POST',
  9683. headers: { 'Content-Type': 'application/json' },
  9684. body: JSON.stringify({
  9685. id,
  9686. name,
  9687. mtu,
  9688. mac_address: mac,
  9689. stp,
  9690. priority,
  9691. vlan_filtering: vlanFiltering,
  9692. pvid,
  9693. fast_forward: fastForward,
  9694. comment,
  9695. disabled
  9696. })
  9697. });
  9698. if (res.ok) {
  9699. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9700. closeBridgeModal();
  9701. loadBridge();
  9702. fetchData(false);
  9703. } else {
  9704. const err = await res.json();
  9705. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9706. }
  9707. } catch (err) {
  9708. showToast('Error', err.message, 'error');
  9709. }
  9710. }
  9711. async function toggleBridgeState(id, disabled) {
  9712. try {
  9713. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9714. method: 'POST',
  9715. headers: { 'Content-Type': 'application/json' },
  9716. body: JSON.stringify({ disabled })
  9717. });
  9718. if (res.ok) {
  9719. loadBridge();
  9720. fetchData(false);
  9721. }
  9722. } catch (err) {
  9723. showToast('Error', err.message, 'error');
  9724. }
  9725. }
  9726. async function deleteBridge(id) {
  9727. const b = (state.bridges || []).find(x => x.id === id);
  9728. const name = b ? b.name : id;
  9729. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9730. try {
  9731. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9732. if (res.ok) {
  9733. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9734. loadBridge();
  9735. fetchData(false);
  9736. } else {
  9737. const err = await res.json();
  9738. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9739. }
  9740. } catch (err) {
  9741. showToast('Error', err.message, 'error');
  9742. }
  9743. }
  9744. // ----------------- Bridge IP Assignments -----------------
  9745. function openAddBridgeIPModal(id, name) {
  9746. document.getElementById('bridge-ip-modal-id').value = id;
  9747. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9748. document.getElementById('bridge-ip-modal-cidr').value = '';
  9749. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9750. }
  9751. function closeBridgeIPModal() {
  9752. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9753. }
  9754. async function submitAddBridgeIP(e) {
  9755. e.preventDefault();
  9756. const id = document.getElementById('bridge-ip-modal-id').value;
  9757. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9758. try {
  9759. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9760. method: 'POST',
  9761. headers: { 'Content-Type': 'application/json' },
  9762. body: JSON.stringify({ ip })
  9763. });
  9764. if (res.ok) {
  9765. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9766. closeBridgeIPModal();
  9767. loadBridge();
  9768. fetchData(false);
  9769. } else {
  9770. const err = await res.json();
  9771. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9772. }
  9773. } catch (err) {
  9774. showToast('Error', err.message, 'error');
  9775. }
  9776. }
  9777. async function deleteBridgeIP(id, ip) {
  9778. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9779. try {
  9780. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9781. method: 'DELETE',
  9782. headers: { 'Content-Type': 'application/json' },
  9783. body: JSON.stringify({ ip })
  9784. });
  9785. if (res.ok) {
  9786. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9787. loadBridge();
  9788. fetchData(false);
  9789. }
  9790. } catch (err) {
  9791. showToast('Error', err.message, 'error');
  9792. }
  9793. }
  9794. // ----------------- Bridge Ports -----------------
  9795. function renderBridgePorts() {
  9796. const tbody = document.getElementById('bridge-ports-table-body');
  9797. const empty = document.getElementById('bridge-empty-ports');
  9798. const countBadge = document.getElementById('bridge-ports-count-badge');
  9799. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9800. if (!tbody) return;
  9801. tbody.innerHTML = '';
  9802. // Update filter select
  9803. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9804. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9805. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9806. if (ports.length === 0) {
  9807. empty?.classList.remove('hidden');
  9808. return;
  9809. }
  9810. empty?.classList.add('hidden');
  9811. ports.forEach((p, idx) => {
  9812. const tr = document.createElement('tr');
  9813. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9814. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9815. tr.innerHTML = `
  9816. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9817. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9818. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9819. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9820. </td>
  9821. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9822. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9823. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9824. <td class="py-2.5 px-3 text-center">${p.ingress_filtering ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  9825. <td class="py-2.5 px-3">
  9826. ${p.horizon > 0 ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">domain ${p.horizon}</span>` : '<span class="text-slate-500">none</span>'}
  9827. </td>
  9828. <td class="py-2.5 px-3">
  9829. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${p.status === 'forwarding' ? 'bg-emerald-950 text-emerald-400 border border-emerald-800/40' : 'bg-slate-800 text-slate-400'} uppercase font-mono">${p.status}</span>
  9830. </td>
  9831. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9832. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9833. <button onclick="toggleBridgePortState('${p.id}', ${!p.disabled})" class="text-xs ${p.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${p.disabled ? 'Enable' : 'Disable'}</button>
  9834. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9835. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9836. </td>
  9837. `;
  9838. tbody.appendChild(tr);
  9839. });
  9840. }
  9841. function openAddBridgePortModal() {
  9842. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9843. document.getElementById('bridge-port-modal-id').value = '';
  9844. populateBridgeSelect('bridge-port-modal-bridge');
  9845. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9846. document.getElementById('bridge-port-modal-pvid').value = '1';
  9847. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9848. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9849. document.getElementById('bridge-port-modal-horizon').value = '0';
  9850. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9851. document.getElementById('bridge-port-modal-priority').value = '128';
  9852. document.getElementById('bridge-port-modal-learn').checked = true;
  9853. document.getElementById('bridge-port-modal-comment').value = '';
  9854. document.getElementById('bridge-port-modal-disabled').checked = false;
  9855. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9856. }
  9857. function openEditBridgePortModal(id) {
  9858. const p = (state.bridgePorts || []).find(x => x.id === id);
  9859. if (!p) return;
  9860. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9861. document.getElementById('bridge-port-modal-id').value = p.id;
  9862. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9863. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9864. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9865. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9866. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9867. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9868. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9869. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9870. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9871. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9872. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9873. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9874. }
  9875. function closeBridgePortModal() {
  9876. document.getElementById('bridge-port-modal').classList.add('hidden');
  9877. }
  9878. async function submitSaveBridgePort(e) {
  9879. e.preventDefault();
  9880. const id = document.getElementById('bridge-port-modal-id').value;
  9881. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9882. const iface = document.getElementById('bridge-port-modal-interface').value;
  9883. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9884. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9885. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9886. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9887. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9888. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9889. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9890. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9891. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9892. try {
  9893. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9894. method: 'POST',
  9895. headers: { 'Content-Type': 'application/json' },
  9896. body: JSON.stringify({
  9897. id,
  9898. bridge,
  9899. interface: iface,
  9900. pvid,
  9901. frame_types: frameTypes,
  9902. ingress_filtering: ingressFiltering,
  9903. horizon,
  9904. path_cost: pathCost,
  9905. priority,
  9906. learn,
  9907. comment,
  9908. disabled
  9909. })
  9910. });
  9911. if (res.ok) {
  9912. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9913. closeBridgePortModal();
  9914. loadBridge();
  9915. fetchData(false);
  9916. } else {
  9917. const err = await res.json();
  9918. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9919. }
  9920. } catch (err) {
  9921. showToast('Error', err.message, 'error');
  9922. }
  9923. }
  9924. async function toggleBridgePortState(id, disabled) {
  9925. try {
  9926. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9927. method: 'POST',
  9928. headers: { 'Content-Type': 'application/json' },
  9929. body: JSON.stringify({ disabled })
  9930. });
  9931. if (res.ok) {
  9932. loadBridge();
  9933. fetchData(false);
  9934. }
  9935. } catch (err) {
  9936. showToast('Error', err.message, 'error');
  9937. }
  9938. }
  9939. async function deleteBridgePort(id) {
  9940. const p = (state.bridgePorts || []).find(x => x.id === id);
  9941. const iface = p ? p.interface : id;
  9942. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9943. try {
  9944. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9945. if (res.ok) {
  9946. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9947. loadBridge();
  9948. fetchData(false);
  9949. }
  9950. } catch (err) {
  9951. showToast('Error', err.message, 'error');
  9952. }
  9953. }
  9954. // ----------------- Bridge VLANs -----------------
  9955. function renderBridgeVLANs() {
  9956. const tbody = document.getElementById('bridge-vlans-table-body');
  9957. const empty = document.getElementById('bridge-empty-vlans');
  9958. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9959. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9960. if (!tbody) return;
  9961. tbody.innerHTML = '';
  9962. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9963. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9964. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9965. if (vlans.length === 0) {
  9966. empty?.classList.remove('hidden');
  9967. return;
  9968. }
  9969. empty?.classList.add('hidden');
  9970. vlans.forEach((v, idx) => {
  9971. const tr = document.createElement('tr');
  9972. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9973. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9974. ? v.tagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/80 border border-cyan-800/40 text-cyan-300 font-mono">${p}</span>`).join(' ')
  9975. : '<span class="text-slate-600">none</span>';
  9976. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9977. ? v.untagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700/60 text-slate-300 font-mono">${p}</span>`).join(' ')
  9978. : '<span class="text-slate-600">none</span>';
  9979. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9980. tr.innerHTML = `
  9981. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9982. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9983. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9984. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9985. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9986. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9987. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9988. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9989. <button onclick="toggleBridgeVLANState('${v.id}', ${!v.disabled})" class="text-xs ${v.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${v.disabled ? 'Enable' : 'Disable'}</button>
  9990. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9991. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9992. </td>
  9993. `;
  9994. tbody.appendChild(tr);
  9995. });
  9996. }
  9997. function openAddBridgeVLANModal() {
  9998. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9999. document.getElementById('bridge-vlan-modal-id').value = '';
  10000. populateBridgeSelect('bridge-vlan-modal-bridge');
  10001. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10002. document.getElementById('bridge-vlan-modal-comment').value = '';
  10003. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10004. updateBridgeVlanPortCheckboxes();
  10005. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10006. }
  10007. function openEditBridgeVLANModal(id) {
  10008. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10009. if (!v) return;
  10010. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10011. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10012. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10013. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10014. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10015. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10016. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10017. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10018. }
  10019. function closeBridgeVlanModal() {
  10020. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10021. }
  10022. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10023. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10024. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10025. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10026. if (!taggedBox || !untaggedBox) return;
  10027. // Ports belonging to the selected bridge
  10028. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10029. if (memberPorts.length === 0) {
  10030. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10031. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10032. return;
  10033. }
  10034. taggedBox.innerHTML = memberPorts.map(p => `
  10035. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10036. <input type="checkbox" name="bvlan-tagged" value="${p.interface}" ${taggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-cyan-500">
  10037. <span>${p.interface}</span>
  10038. </label>
  10039. `).join('');
  10040. untaggedBox.innerHTML = memberPorts.map(p => `
  10041. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10042. <input type="checkbox" name="bvlan-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  10043. <span>${p.interface}</span>
  10044. </label>
  10045. `).join('');
  10046. }
  10047. async function submitSaveBridgeVLAN(e) {
  10048. e.preventDefault();
  10049. const id = document.getElementById('bridge-vlan-modal-id').value;
  10050. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10051. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10052. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10053. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10054. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10055. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10056. try {
  10057. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10058. method: 'POST',
  10059. headers: { 'Content-Type': 'application/json' },
  10060. body: JSON.stringify({
  10061. id,
  10062. bridge,
  10063. vlan_ids: vlanIDs,
  10064. tagged,
  10065. untagged,
  10066. comment,
  10067. disabled
  10068. })
  10069. });
  10070. if (res.ok) {
  10071. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10072. closeBridgeVlanModal();
  10073. loadBridge();
  10074. } else {
  10075. const err = await res.json();
  10076. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10077. }
  10078. } catch (err) {
  10079. showToast('Error', err.message, 'error');
  10080. }
  10081. }
  10082. async function toggleBridgeVLANState(id, disabled) {
  10083. try {
  10084. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10085. method: 'POST',
  10086. headers: { 'Content-Type': 'application/json' },
  10087. body: JSON.stringify({ disabled })
  10088. });
  10089. if (res.ok) loadBridge();
  10090. } catch (err) {
  10091. showToast('Error', err.message, 'error');
  10092. }
  10093. }
  10094. async function deleteBridgeVLAN(id) {
  10095. if (!confirm('Delete this bridge VLAN entry?')) return;
  10096. try {
  10097. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10098. if (res.ok) {
  10099. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10100. loadBridge();
  10101. }
  10102. } catch (err) {
  10103. showToast('Error', err.message, 'error');
  10104. }
  10105. }
  10106. // ----------------- Hosts / MAC Table -----------------
  10107. async function loadBridgeHosts() {
  10108. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10109. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10110. try {
  10111. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10112. const res = await fetch(url);
  10113. if (res.ok) {
  10114. state.bridgeHosts = await res.json();
  10115. renderBridgeHosts();
  10116. }
  10117. } catch (err) {
  10118. console.error('Failed to load bridge hosts:', err);
  10119. }
  10120. }
  10121. function renderBridgeHosts() {
  10122. const tbody = document.getElementById('bridge-hosts-table-body');
  10123. const empty = document.getElementById('bridge-empty-hosts');
  10124. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10125. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10126. if (!tbody) return;
  10127. tbody.innerHTML = '';
  10128. const hosts = (state.bridgeHosts || []).filter(h => {
  10129. if (!search) return true;
  10130. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10131. });
  10132. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10133. if (hosts.length === 0) {
  10134. empty?.classList.remove('hidden');
  10135. return;
  10136. }
  10137. empty?.classList.add('hidden');
  10138. hosts.forEach(h => {
  10139. const tr = document.createElement('tr');
  10140. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10141. let flagBadges = '';
  10142. if (h.local) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-sky-950 text-sky-400 border border-sky-800/40 font-mono font-bold mr-1" title="Local router interface MAC">L</span>';
  10143. if (h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-purple-950 text-purple-400 border border-purple-800/40 font-mono font-bold mr-1" title="Static entry">S</span>';
  10144. if (!h.local && !h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-emerald-950 text-emerald-400 border border-emerald-800/40 font-mono font-bold mr-1" title="Dynamically learned">D</span>';
  10145. tr.innerHTML = `
  10146. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10147. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10148. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10149. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10150. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10151. <td class="py-2.5 px-3">${flagBadges}</td>
  10152. `;
  10153. tbody.appendChild(tr);
  10154. });
  10155. }
  10156. async function flushBridgeHosts() {
  10157. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10158. if (!selBridge) {
  10159. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10160. return;
  10161. }
  10162. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10163. try {
  10164. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10165. method: 'POST',
  10166. headers: { 'Content-Type': 'application/json' },
  10167. body: JSON.stringify({ bridge: selBridge })
  10168. });
  10169. if (res.ok) {
  10170. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10171. loadBridgeHosts();
  10172. }
  10173. } catch (err) {
  10174. showToast('Error', err.message, 'error');
  10175. }
  10176. }
  10177. // ----------------- Helpers -----------------
  10178. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10179. const sel = document.getElementById(selectId);
  10180. if (!sel) return;
  10181. const prevVal = currentVal || sel.value;
  10182. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10183. (state.bridges || []).forEach(b => {
  10184. const opt = document.createElement('option');
  10185. opt.value = b.name;
  10186. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10187. if (b.name === prevVal) opt.selected = true;
  10188. sel.appendChild(opt);
  10189. });
  10190. }
  10191. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10192. const sel = document.getElementById(selectId);
  10193. if (!sel) return;
  10194. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10195. // 1. Physical Interfaces
  10196. const grpPhys = document.createElement('optgroup');
  10197. grpPhys.label = 'Physical Interfaces';
  10198. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10199. const opt = document.createElement('option');
  10200. opt.value = i.name;
  10201. opt.innerText = `${i.name} (${i.role || i.type})`;
  10202. if (i.name === currentVal) opt.selected = true;
  10203. grpPhys.appendChild(opt);
  10204. });
  10205. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10206. // 2. VLAN Sub-interfaces
  10207. const grpVlans = document.createElement('optgroup');
  10208. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10209. (state.vlans || []).forEach(v => {
  10210. const opt = document.createElement('option');
  10211. opt.value = v.name;
  10212. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10213. if (v.name === currentVal) opt.selected = true;
  10214. grpVlans.appendChild(opt);
  10215. });
  10216. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10217. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10218. const grpEoip = document.createElement('optgroup');
  10219. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10220. (state.eoipTunnels || []).forEach(t => {
  10221. const opt = document.createElement('option');
  10222. opt.value = t.name;
  10223. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10224. if (t.name === currentVal) opt.selected = true;
  10225. grpEoip.appendChild(opt);
  10226. });
  10227. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10228. }
  10229. // -------------------------------------------------------------
  10230. // RouterOS v7 Routing Filters Management (/routing filter)
  10231. // -------------------------------------------------------------
  10232. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10233. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10234. if (!state.rfSort) state.rfSort = {};
  10235. function switchRoutingFilterTab(tab) {
  10236. state.activeRoutingFilterTab = tab;
  10237. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10238. tabs.forEach(t => {
  10239. const btn = document.getElementById(`tab-rf-${t}`);
  10240. const content = document.getElementById(`tab-content-rf-${t}`);
  10241. if (btn) {
  10242. if (t === tab) {
  10243. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  10244. } else {
  10245. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10246. }
  10247. }
  10248. if (content) {
  10249. if (t === tab) content.classList.remove('hidden');
  10250. else content.classList.add('hidden');
  10251. }
  10252. });
  10253. const chainContainer = document.getElementById('rf-chain-filter-container');
  10254. if (chainContainer) {
  10255. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10256. else chainContainer.classList.add('hidden');
  10257. }
  10258. renderRoutingFilters();
  10259. }
  10260. function selectFilterRow(tab, id) {
  10261. if (state.selectedFilterRow[tab] === id) {
  10262. delete state.selectedFilterRow[tab];
  10263. } else {
  10264. state.selectedFilterRow[tab] = id;
  10265. }
  10266. if (tab === 'rules') renderRoutingFilterRules();
  10267. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10268. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10269. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10270. }
  10271. function openRoutingFilterNewModal() {
  10272. const tab = state.activeRoutingFilterTab || 'rules';
  10273. if (tab === 'rules') openAddRoutingFilterModal();
  10274. else if (tab === 'select-rules') openAddSelectRuleModal();
  10275. else if (tab === 'community-lists') openAddCommunityListModal();
  10276. else if (tab === 'as-lists') openAddASListModal();
  10277. }
  10278. function toggleSelectedRoutingFilter(disabled) {
  10279. const tab = state.activeRoutingFilterTab || 'rules';
  10280. const id = state.selectedFilterRow[tab];
  10281. if (!id) {
  10282. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10283. return;
  10284. }
  10285. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10286. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10287. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10288. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10289. }
  10290. function removeSelectedRoutingFilter() {
  10291. const tab = state.activeRoutingFilterTab || 'rules';
  10292. const id = state.selectedFilterRow[tab];
  10293. if (!id) {
  10294. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10295. return;
  10296. }
  10297. if (tab === 'rules') deleteRoutingFilter(id);
  10298. else if (tab === 'select-rules') deleteSelectRule(id);
  10299. else if (tab === 'community-lists') deleteCommunityList(id);
  10300. else if (tab === 'as-lists') deleteASList(id);
  10301. }
  10302. function searchRoutingFilters(q) {
  10303. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10304. renderRoutingFilters();
  10305. }
  10306. function sortFilterTable(tab, col) {
  10307. if (!state.rfSort) state.rfSort = {};
  10308. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10309. if (state.rfSort[tab].col === col) {
  10310. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10311. } else {
  10312. state.rfSort[tab].col = col;
  10313. state.rfSort[tab].asc = true;
  10314. }
  10315. const asc = state.rfSort[tab].asc;
  10316. let list = [];
  10317. if (tab === 'rules') list = state.routingFilters || [];
  10318. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10319. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10320. else if (tab === 'as-lists') list = state.routingASLists || [];
  10321. list.sort((a, b) => {
  10322. let valA = a[col] ?? '';
  10323. let valB = b[col] ?? '';
  10324. if (col === 'flags') {
  10325. valA = a.disabled ? 'X' : 'A';
  10326. valB = b.disabled ? 'X' : 'A';
  10327. }
  10328. if (typeof valA === 'number' && typeof valB === 'number') {
  10329. return asc ? valA - valB : valB - valA;
  10330. }
  10331. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10332. });
  10333. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10334. allCols.forEach(c => {
  10335. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10336. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10337. });
  10338. if (tab === 'rules') renderRoutingFilterRules();
  10339. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10340. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10341. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10342. }
  10343. function renderRoutingFilters() {
  10344. const navBadge = document.getElementById('badge-filters-count');
  10345. const allRules = state.routingFilters || [];
  10346. if (navBadge) navBadge.innerText = allRules.length;
  10347. // Populate chain filter select options and datalist
  10348. const chainSelect = document.getElementById('routing-filter-chain-select');
  10349. const chainDatalist = document.getElementById('dl-routing-chains');
  10350. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10351. if (chainSelect) {
  10352. const currentVal = state.filterChainSelected || 'all';
  10353. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10354. uniqueChains.map(ch => {
  10355. const count = allRules.filter(r => r.chain === ch).length;
  10356. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10357. }).join('');
  10358. chainSelect.value = currentVal;
  10359. }
  10360. if (chainDatalist) {
  10361. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10362. }
  10363. renderRoutingFilterRules();
  10364. renderRoutingFilterSelectRules();
  10365. renderRoutingFilterCommunityLists();
  10366. renderRoutingFilterASLists();
  10367. }
  10368. function filterRoutingFiltersByChain(chain) {
  10369. state.filterChainSelected = chain;
  10370. renderRoutingFilters();
  10371. }
  10372. // -------------------------------------------------------------
  10373. // TAB 1: RULES (/routing filter rule)
  10374. // -------------------------------------------------------------
  10375. function renderRoutingFilterRules() {
  10376. const tbody = document.getElementById('routing-filter-rules-tbody');
  10377. if (!tbody) return;
  10378. const empty = document.getElementById('rf-rules-empty');
  10379. const statusCount = document.getElementById('rf-status-count');
  10380. let list = (state.routingFilters || []).slice();
  10381. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10382. list = list.filter(r => r.chain === state.filterChainSelected);
  10383. }
  10384. const q = state.rfSearchQuery;
  10385. if (q) {
  10386. list = list.filter(r =>
  10387. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10388. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10389. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10390. (r.comment && r.comment.toLowerCase().includes(q))
  10391. );
  10392. }
  10393. if (!state.rfSort?.['rules']) {
  10394. list.sort((a, b) => {
  10395. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10396. return (a.rule_order || 0) - (b.rule_order || 0);
  10397. });
  10398. }
  10399. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10400. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10401. }
  10402. if (list.length === 0) {
  10403. tbody.innerHTML = '';
  10404. if (empty) empty.classList.remove('hidden');
  10405. return;
  10406. }
  10407. if (empty) empty.classList.add('hidden');
  10408. tbody.innerHTML = list.map(r => {
  10409. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10410. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10411. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10412. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10413. let ruleDisplay = '';
  10414. if (r.rule && r.rule.trim() !== '') {
  10415. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10416. } else {
  10417. let conds = [];
  10418. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10419. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10420. let act = r.action || 'accept';
  10421. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10422. }
  10423. return `
  10424. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10425. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10426. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10427. <td class="py-2 px-3">
  10428. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10429. </td>
  10430. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10431. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10432. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10433. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  10434. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  10435. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10436. ${r.disabled ? 'Enable' : 'Disable'}
  10437. </button>
  10438. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10439. Edit
  10440. </button>
  10441. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10442. ✕
  10443. </button>
  10444. </td>
  10445. </tr>
  10446. `;
  10447. }).join('');
  10448. }
  10449. // -------------------------------------------------------------
  10450. // TAB 2: SELECT RULES (/routing filter select-rule)
  10451. // -------------------------------------------------------------
  10452. function renderRoutingFilterSelectRules() {
  10453. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10454. if (!tbody) return;
  10455. const empty = document.getElementById('rf-select-rules-empty');
  10456. const statusCount = document.getElementById('rf-status-count');
  10457. let list = (state.routingSelectRules || []).slice();
  10458. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10459. list = list.filter(r => r.chain === state.filterChainSelected);
  10460. }
  10461. const q = state.rfSearchQuery;
  10462. if (q) {
  10463. list = list.filter(r =>
  10464. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10465. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10466. (r.comment && r.comment.toLowerCase().includes(q))
  10467. );
  10468. }
  10469. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10470. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10471. }
  10472. if (list.length === 0) {
  10473. tbody.innerHTML = '';
  10474. if (empty) empty.classList.remove('hidden');
  10475. return;
  10476. }
  10477. if (empty) empty.classList.add('hidden');
  10478. tbody.innerHTML = list.map(r => {
  10479. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10480. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10481. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10482. return `
  10483. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10484. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10485. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10486. <td class="py-2 px-3">
  10487. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10488. </td>
  10489. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10490. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10491. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10492. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10493. ${r.disabled ? 'Enable' : 'Disable'}
  10494. </button>
  10495. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10496. Edit
  10497. </button>
  10498. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10499. ✕
  10500. </button>
  10501. </td>
  10502. </tr>
  10503. `;
  10504. }).join('');
  10505. }
  10506. // -------------------------------------------------------------
  10507. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10508. // -------------------------------------------------------------
  10509. function renderRoutingFilterCommunityLists() {
  10510. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10511. if (!tbody) return;
  10512. const empty = document.getElementById('rf-comm-lists-empty');
  10513. const statusCount = document.getElementById('rf-status-count');
  10514. let list = (state.routingCommunityLists || []).slice();
  10515. const q = state.rfSearchQuery;
  10516. if (q) {
  10517. list = list.filter(cl =>
  10518. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10519. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10520. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10521. );
  10522. }
  10523. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10524. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10525. }
  10526. if (list.length === 0) {
  10527. tbody.innerHTML = '';
  10528. if (empty) empty.classList.remove('hidden');
  10529. return;
  10530. }
  10531. if (empty) empty.classList.add('hidden');
  10532. tbody.innerHTML = list.map(cl => {
  10533. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10534. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10535. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10536. const commBadges = (cl.communities || []).map(c =>
  10537. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  10538. ).join(' ');
  10539. return `
  10540. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10541. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10542. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10543. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10544. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10545. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10546. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10547. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10548. ${cl.disabled ? 'Enable' : 'Disable'}
  10549. </button>
  10550. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10551. Edit
  10552. </button>
  10553. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10554. ✕
  10555. </button>
  10556. </td>
  10557. </tr>
  10558. `;
  10559. }).join('');
  10560. }
  10561. // -------------------------------------------------------------
  10562. // TAB 4: AS LISTS (/routing filter num-list)
  10563. // -------------------------------------------------------------
  10564. function renderRoutingFilterASLists() {
  10565. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10566. if (!tbody) return;
  10567. const empty = document.getElementById('rf-as-lists-empty');
  10568. const statusCount = document.getElementById('rf-status-count');
  10569. let list = (state.routingASLists || []).slice();
  10570. const q = state.rfSearchQuery;
  10571. if (q) {
  10572. list = list.filter(al =>
  10573. (al.name && al.name.toLowerCase().includes(q)) ||
  10574. (al.range && al.range.toLowerCase().includes(q)) ||
  10575. (al.comment && al.comment.toLowerCase().includes(q))
  10576. );
  10577. }
  10578. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10579. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10580. }
  10581. if (list.length === 0) {
  10582. tbody.innerHTML = '';
  10583. if (empty) empty.classList.remove('hidden');
  10584. return;
  10585. }
  10586. if (empty) empty.classList.add('hidden');
  10587. tbody.innerHTML = list.map(al => {
  10588. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10589. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10590. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10591. return `
  10592. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10593. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10594. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10595. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10596. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10597. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10598. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10599. ${al.disabled ? 'Enable' : 'Disable'}
  10600. </button>
  10601. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10602. Edit
  10603. </button>
  10604. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10605. ✕
  10606. </button>
  10607. </td>
  10608. </tr>
  10609. `;
  10610. }).join('');
  10611. }
  10612. // -------------------------------------------------------------
  10613. // SNIPPETS & WIZARD HELPERS
  10614. // -------------------------------------------------------------
  10615. function insertRuleSnippet(type) {
  10616. const textarea = document.getElementById('modal-rf-rule');
  10617. if (!textarea) return;
  10618. let snippet = '';
  10619. switch (type) {
  10620. case 'accept-default':
  10621. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10622. break;
  10623. case 'drop-rfc1918':
  10624. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10625. break;
  10626. case 'len-24':
  10627. snippet = 'if (dst-len > 24) { reject; }';
  10628. break;
  10629. case 'local-pref-150':
  10630. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10631. break;
  10632. case 'as-prepend-2':
  10633. snippet = 'set bgp-path-prepend 2; accept;';
  10634. break;
  10635. case 'set-comm':
  10636. snippet = 'set bgp-communities.add 65000:100; accept;';
  10637. break;
  10638. case 'match-comm':
  10639. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10640. break;
  10641. case 'reject-all':
  10642. snippet = 'reject;';
  10643. break;
  10644. }
  10645. if (!snippet) return;
  10646. if (!textarea.value.trim()) {
  10647. textarea.value = snippet;
  10648. } else {
  10649. textarea.value = textarea.value.trim() + '\n' + snippet;
  10650. }
  10651. }
  10652. function generateScriptFromWizard() {
  10653. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10654. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10655. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10656. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10657. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10658. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10659. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10660. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10661. const conds = [];
  10662. if (pfx) {
  10663. if (pfxLen) {
  10664. if (pfxLen.includes('-')) {
  10665. const parts = pfxLen.split('-');
  10666. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10667. } else {
  10668. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10669. }
  10670. } else {
  10671. conds.push(`dst in ${pfx}`);
  10672. }
  10673. }
  10674. if (proto && proto !== 'any') {
  10675. conds.push(`protocol ${proto}`);
  10676. }
  10677. if (asp) {
  10678. conds.push(`bgp-as-path "${asp}"`);
  10679. }
  10680. if (comm) {
  10681. conds.push(`bgp-communities includes ${comm}`);
  10682. }
  10683. const actions = [];
  10684. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10685. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10686. actions.push(`${act};`);
  10687. let code = '';
  10688. if (conds.length > 0) {
  10689. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10690. } else {
  10691. code = actions.join(' ');
  10692. }
  10693. const textarea = document.getElementById('modal-rf-rule');
  10694. if (textarea) textarea.value = code;
  10695. }
  10696. // -------------------------------------------------------------
  10697. // MODAL CRUD: RULES (/routing filter rule)
  10698. // -------------------------------------------------------------
  10699. function openAddRoutingFilterModal(defaultChain = '') {
  10700. const form = document.getElementById('routing-filter-form');
  10701. if (form) form.reset();
  10702. const idEl = document.getElementById('modal-rf-id');
  10703. if (idEl) idEl.value = '';
  10704. const titleEl = document.getElementById('modal-rf-title');
  10705. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10706. const chainEl = document.getElementById('modal-rf-chain');
  10707. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10708. const orderEl = document.getElementById('modal-rf-order');
  10709. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10710. const ruleEl = document.getElementById('modal-rf-rule');
  10711. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10712. const disEl = document.getElementById('modal-rf-disabled');
  10713. if (disEl) disEl.checked = false;
  10714. const modal = document.getElementById('modal-routing-filter');
  10715. if (modal) modal.classList.remove('hidden');
  10716. }
  10717. function openEditRoutingFilterModal(id) {
  10718. const r = (state.routingFilters || []).find(item => item.id === id);
  10719. if (!r) return;
  10720. const idEl = document.getElementById('modal-rf-id');
  10721. if (idEl) idEl.value = r.id;
  10722. const titleEl = document.getElementById('modal-rf-title');
  10723. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10724. const chainEl = document.getElementById('modal-rf-chain');
  10725. if (chainEl) chainEl.value = r.chain || '';
  10726. const orderEl = document.getElementById('modal-rf-order');
  10727. if (orderEl) orderEl.value = r.rule_order || 10;
  10728. const ruleEl = document.getElementById('modal-rf-rule');
  10729. if (ruleEl) {
  10730. if (r.rule) {
  10731. ruleEl.value = r.rule;
  10732. } else {
  10733. let conds = [];
  10734. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10735. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10736. let act = r.action || 'accept';
  10737. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10738. }
  10739. }
  10740. const comEl = document.getElementById('modal-rf-comment');
  10741. if (comEl) comEl.value = r.comment || '';
  10742. const disEl = document.getElementById('modal-rf-disabled');
  10743. if (disEl) disEl.checked = !!r.disabled;
  10744. const modal = document.getElementById('modal-routing-filter');
  10745. if (modal) modal.classList.remove('hidden');
  10746. }
  10747. function closeRoutingFilterModal() {
  10748. const modal = document.getElementById('modal-routing-filter');
  10749. if (modal) modal.classList.add('hidden');
  10750. }
  10751. async function submitRoutingFilter(e) {
  10752. if (e) e.preventDefault();
  10753. const payload = {
  10754. id: document.getElementById('modal-rf-id').value,
  10755. chain: document.getElementById('modal-rf-chain').value.trim(),
  10756. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10757. rule: document.getElementById('modal-rf-rule').value.trim(),
  10758. comment: document.getElementById('modal-rf-comment').value.trim(),
  10759. disabled: document.getElementById('modal-rf-disabled').checked
  10760. };
  10761. try {
  10762. const res = await fetch(`${API_BASE}/routing/filters`, {
  10763. method: 'POST',
  10764. headers: { 'Content-Type': 'application/json' },
  10765. body: JSON.stringify(payload)
  10766. });
  10767. if (res.ok) {
  10768. closeRoutingFilterModal();
  10769. showToast('Success', 'Routing filter rule saved', 'success');
  10770. loadDynamicRouting();
  10771. } else {
  10772. const err = await res.json();
  10773. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10774. }
  10775. } catch (err) {
  10776. showToast('Error', err.message, 'error');
  10777. }
  10778. }
  10779. async function applyRoutingFilterForm() {
  10780. const payload = {
  10781. id: document.getElementById('modal-rf-id').value,
  10782. chain: document.getElementById('modal-rf-chain').value.trim(),
  10783. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10784. rule: document.getElementById('modal-rf-rule').value.trim(),
  10785. comment: document.getElementById('modal-rf-comment').value.trim(),
  10786. disabled: document.getElementById('modal-rf-disabled').checked
  10787. };
  10788. try {
  10789. const res = await fetch(`${API_BASE}/routing/filters`, {
  10790. method: 'POST',
  10791. headers: { 'Content-Type': 'application/json' },
  10792. body: JSON.stringify(payload)
  10793. });
  10794. if (res.ok) {
  10795. const data = await res.json();
  10796. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10797. showToast('Applied', 'Routing filter configuration applied', 'success');
  10798. loadDynamicRouting();
  10799. } else {
  10800. const err = await res.json();
  10801. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10802. }
  10803. } catch (err) {
  10804. showToast('Error', err.message, 'error');
  10805. }
  10806. }
  10807. async function moveRoutingFilterOrder(id, delta) {
  10808. const list = state.routingFilters || [];
  10809. const idx = list.findIndex(r => r.id === id);
  10810. if (idx < 0) return;
  10811. const targetIdx = idx + delta;
  10812. if (targetIdx < 0 || targetIdx >= list.length) return;
  10813. const currentOrder = list[idx].rule_order || 10;
  10814. const targetOrder = list[targetIdx].rule_order || 20;
  10815. list[idx].rule_order = targetOrder;
  10816. list[targetIdx].rule_order = currentOrder;
  10817. try {
  10818. await fetch(`${API_BASE}/routing/filters`, {
  10819. method: 'POST',
  10820. headers: { 'Content-Type': 'application/json' },
  10821. body: JSON.stringify(list[idx])
  10822. });
  10823. await fetch(`${API_BASE}/routing/filters`, {
  10824. method: 'POST',
  10825. headers: { 'Content-Type': 'application/json' },
  10826. body: JSON.stringify(list[targetIdx])
  10827. });
  10828. loadDynamicRouting();
  10829. } catch (e) {
  10830. console.error('Reorder error:', e);
  10831. }
  10832. }
  10833. async function deleteRoutingFilter(id) {
  10834. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10835. try {
  10836. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10837. if (res.ok) {
  10838. showToast('Deleted', 'Routing filter rule removed', 'info');
  10839. loadDynamicRouting();
  10840. } else {
  10841. const err = await res.json();
  10842. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10843. }
  10844. } catch (err) {
  10845. showToast('Error', err.message, 'error');
  10846. }
  10847. }
  10848. async function toggleRoutingFilterState(id, disabled) {
  10849. try {
  10850. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10851. method: 'POST',
  10852. headers: { 'Content-Type': 'application/json' },
  10853. body: JSON.stringify({ disabled })
  10854. });
  10855. if (res.ok) {
  10856. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10857. loadDynamicRouting();
  10858. } else {
  10859. const err = await res.json();
  10860. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10861. }
  10862. } catch (err) {
  10863. showToast('Error', err.message, 'error');
  10864. }
  10865. }
  10866. // -------------------------------------------------------------
  10867. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10868. // -------------------------------------------------------------
  10869. function openAddSelectRuleModal() {
  10870. document.getElementById('modal-rf-sr-id').value = '';
  10871. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10872. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10873. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10874. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10875. document.getElementById('modal-rf-sr-comment').value = '';
  10876. document.getElementById('modal-rf-sr-disabled').checked = false;
  10877. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10878. }
  10879. function openEditSelectRuleModal(id) {
  10880. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10881. if (!r) return;
  10882. document.getElementById('modal-rf-sr-id').value = r.id;
  10883. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10884. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10885. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10886. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10887. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10888. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10889. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10890. }
  10891. function closeSelectRuleModal() {
  10892. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10893. }
  10894. async function submitSelectRule(e) {
  10895. e.preventDefault();
  10896. const payload = {
  10897. id: document.getElementById('modal-rf-sr-id').value,
  10898. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10899. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10900. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10901. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10902. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10903. };
  10904. try {
  10905. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10906. method: 'POST',
  10907. headers: { 'Content-Type': 'application/json' },
  10908. body: JSON.stringify(payload)
  10909. });
  10910. if (res.ok) {
  10911. closeSelectRuleModal();
  10912. showToast('Success', 'Select rule saved', 'success');
  10913. loadDynamicRouting();
  10914. } else {
  10915. const err = await res.json();
  10916. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10917. }
  10918. } catch (err) {
  10919. showToast('Error', err.message, 'error');
  10920. }
  10921. }
  10922. async function deleteSelectRule(id) {
  10923. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10924. try {
  10925. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10926. if (res.ok) {
  10927. showToast('Deleted', 'Select rule removed', 'info');
  10928. loadDynamicRouting();
  10929. } else {
  10930. const err = await res.json();
  10931. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10932. }
  10933. } catch (err) {
  10934. showToast('Error', err.message, 'error');
  10935. }
  10936. }
  10937. async function toggleSelectRuleState(id, disabled) {
  10938. try {
  10939. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10940. method: 'POST',
  10941. headers: { 'Content-Type': 'application/json' },
  10942. body: JSON.stringify({ disabled })
  10943. });
  10944. if (res.ok) {
  10945. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10946. loadDynamicRouting();
  10947. } else {
  10948. const err = await res.json();
  10949. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10950. }
  10951. } catch (err) {
  10952. showToast('Error', err.message, 'error');
  10953. }
  10954. }
  10955. // -------------------------------------------------------------
  10956. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10957. // -------------------------------------------------------------
  10958. function openAddCommunityListModal() {
  10959. document.getElementById('modal-rf-cl-id').value = '';
  10960. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10961. document.getElementById('modal-rf-cl-name').value = '';
  10962. document.getElementById('modal-rf-cl-communities').value = '';
  10963. document.getElementById('modal-rf-cl-regexp').value = '';
  10964. document.getElementById('modal-rf-cl-comment').value = '';
  10965. document.getElementById('modal-rf-cl-disabled').checked = false;
  10966. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10967. }
  10968. function openEditCommunityListModal(id) {
  10969. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10970. if (!cl) return;
  10971. document.getElementById('modal-rf-cl-id').value = cl.id;
  10972. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10973. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10974. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10975. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10976. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10977. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10978. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10979. }
  10980. function closeCommunityListModal() {
  10981. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10982. }
  10983. async function submitCommunityList(e) {
  10984. e.preventDefault();
  10985. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10986. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10987. const payload = {
  10988. id: document.getElementById('modal-rf-cl-id').value,
  10989. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10990. communities: comms,
  10991. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10992. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10993. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10994. };
  10995. try {
  10996. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10997. method: 'POST',
  10998. headers: { 'Content-Type': 'application/json' },
  10999. body: JSON.stringify(payload)
  11000. });
  11001. if (res.ok) {
  11002. closeCommunityListModal();
  11003. showToast('Success', 'Community list saved', 'success');
  11004. loadDynamicRouting();
  11005. } else {
  11006. const err = await res.json();
  11007. showToast('Error', err.error || 'Failed to save community list', 'error');
  11008. }
  11009. } catch (err) {
  11010. showToast('Error', err.message, 'error');
  11011. }
  11012. }
  11013. async function deleteCommunityList(id) {
  11014. if (!confirm('Are you sure you want to delete this community list?')) return;
  11015. try {
  11016. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11017. if (res.ok) {
  11018. showToast('Deleted', 'Community list removed', 'info');
  11019. loadDynamicRouting();
  11020. } else {
  11021. const err = await res.json();
  11022. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11023. }
  11024. } catch (err) {
  11025. showToast('Error', err.message, 'error');
  11026. }
  11027. }
  11028. async function toggleCommunityListState(id, disabled) {
  11029. try {
  11030. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11031. method: 'POST',
  11032. headers: { 'Content-Type': 'application/json' },
  11033. body: JSON.stringify({ disabled })
  11034. });
  11035. if (res.ok) {
  11036. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11037. loadDynamicRouting();
  11038. } else {
  11039. const err = await res.json();
  11040. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11041. }
  11042. } catch (err) {
  11043. showToast('Error', err.message, 'error');
  11044. }
  11045. }
  11046. // -------------------------------------------------------------
  11047. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11048. // -------------------------------------------------------------
  11049. function openAddASListModal() {
  11050. document.getElementById('modal-rf-al-id').value = '';
  11051. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11052. document.getElementById('modal-rf-al-name').value = '';
  11053. document.getElementById('modal-rf-al-range').value = '';
  11054. document.getElementById('modal-rf-al-comment').value = '';
  11055. document.getElementById('modal-rf-al-disabled').checked = false;
  11056. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11057. }
  11058. function openEditASListModal(id) {
  11059. const al = (state.routingASLists || []).find(item => item.id === id);
  11060. if (!al) return;
  11061. document.getElementById('modal-rf-al-id').value = al.id;
  11062. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11063. document.getElementById('modal-rf-al-name').value = al.name || '';
  11064. document.getElementById('modal-rf-al-range').value = al.range || '';
  11065. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11066. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11067. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11068. }
  11069. function closeASListModal() {
  11070. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11071. }
  11072. async function submitASList(e) {
  11073. e.preventDefault();
  11074. const payload = {
  11075. id: document.getElementById('modal-rf-al-id').value,
  11076. name: document.getElementById('modal-rf-al-name').value.trim(),
  11077. range: document.getElementById('modal-rf-al-range').value.trim(),
  11078. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11079. disabled: document.getElementById('modal-rf-al-disabled').checked
  11080. };
  11081. try {
  11082. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11083. method: 'POST',
  11084. headers: { 'Content-Type': 'application/json' },
  11085. body: JSON.stringify(payload)
  11086. });
  11087. if (res.ok) {
  11088. closeASListModal();
  11089. showToast('Success', 'AS number list saved', 'success');
  11090. loadDynamicRouting();
  11091. } else {
  11092. const err = await res.json();
  11093. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11094. }
  11095. } catch (err) {
  11096. showToast('Error', err.message, 'error');
  11097. }
  11098. }
  11099. async function deleteASList(id) {
  11100. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11101. try {
  11102. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11103. if (res.ok) {
  11104. showToast('Deleted', 'AS list removed', 'info');
  11105. loadDynamicRouting();
  11106. } else {
  11107. const err = await res.json();
  11108. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11109. }
  11110. } catch (err) {
  11111. showToast('Error', err.message, 'error');
  11112. }
  11113. }
  11114. async function toggleASListState(id, disabled) {
  11115. try {
  11116. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11117. method: 'POST',
  11118. headers: { 'Content-Type': 'application/json' },
  11119. body: JSON.stringify({ disabled })
  11120. });
  11121. if (res.ok) {
  11122. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11123. loadDynamicRouting();
  11124. } else {
  11125. const err = await res.json();
  11126. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11127. }
  11128. } catch (err) {
  11129. showToast('Error', err.message, 'error');
  11130. }
  11131. }
  11132. // ==========================================
  11133. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11134. // ==========================================
  11135. function loadToolsView() {
  11136. populateToolsInterfaces();
  11137. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11138. }
  11139. function populateToolsInterfaces() {
  11140. const pingSel = document.getElementById('tools-ping-iface');
  11141. const traceSel = document.getElementById('tools-tr-iface');
  11142. let opts = '<option value="">Auto (Default Route)</option>';
  11143. if (Array.isArray(state.interfaces)) {
  11144. state.interfaces.forEach(iface => {
  11145. if (iface.name) {
  11146. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11147. }
  11148. });
  11149. }
  11150. if (pingSel) {
  11151. const cur = pingSel.value;
  11152. pingSel.innerHTML = opts;
  11153. if (cur) pingSel.value = cur;
  11154. }
  11155. if (traceSel) {
  11156. const cur = traceSel.value;
  11157. traceSel.innerHTML = opts;
  11158. if (cur) traceSel.value = cur;
  11159. }
  11160. }
  11161. function switchToolsSubTab(subTab) {
  11162. state.activeToolsSubTab = subTab;
  11163. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11164. tabs.forEach(t => {
  11165. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11166. const view = document.getElementById(`tools-view-${t}`);
  11167. if (btn) {
  11168. if (t === subTab) {
  11169. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  11170. } else {
  11171. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  11172. }
  11173. }
  11174. if (view) {
  11175. if (t === subTab) {
  11176. view.classList.remove('hidden');
  11177. } else {
  11178. view.classList.add('hidden');
  11179. }
  11180. }
  11181. });
  11182. }
  11183. function setPortPreset(port) {
  11184. const input = document.getElementById('tools-port-num');
  11185. if (input) input.value = port;
  11186. }
  11187. let pingAbortController = null;
  11188. let tracerouteAbortController = null;
  11189. function clearPingTable() {
  11190. const tbody = document.getElementById('tools-ping-tbody');
  11191. if (tbody) tbody.innerHTML = '';
  11192. const rawEl = document.getElementById('tools-ping-raw');
  11193. if (rawEl) rawEl.innerText = '';
  11194. const sentEl = document.getElementById('tools-ping-stat-sent');
  11195. if (sentEl) sentEl.innerText = '0';
  11196. const recvEl = document.getElementById('tools-ping-stat-recv');
  11197. if (recvEl) recvEl.innerText = '0';
  11198. const lossEl = document.getElementById('tools-ping-stat-loss');
  11199. if (lossEl) lossEl.innerText = '0%';
  11200. const avgEl = document.getElementById('tools-ping-stat-avg');
  11201. if (avgEl) avgEl.innerText = '0 ms';
  11202. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11203. if (minMaxEl) minMaxEl.innerText = '-';
  11204. const badge = document.getElementById('tools-ping-status-badge');
  11205. if (badge) {
  11206. badge.className = '';
  11207. badge.innerText = '';
  11208. }
  11209. }
  11210. function clearTracerouteTable() {
  11211. const tbody = document.getElementById('tools-tr-tbody');
  11212. if (tbody) tbody.innerHTML = '';
  11213. const rawEl = document.getElementById('tools-tr-raw');
  11214. if (rawEl) rawEl.innerText = '';
  11215. const statHops = document.getElementById('tools-tr-hops-count');
  11216. if (statHops) statHops.innerText = '0 Hops';
  11217. }
  11218. function resetPingButton() {
  11219. const btn = document.getElementById('tools-ping-btn');
  11220. const btnText = document.getElementById('tools-ping-btn-text');
  11221. const spinner = document.getElementById('tools-ping-spinner');
  11222. if (btn) {
  11223. btn.disabled = false;
  11224. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11225. }
  11226. if (btnText) btnText.innerText = 'Start Ping';
  11227. if (spinner) spinner.classList.add('hidden');
  11228. }
  11229. function setPingRunningButton() {
  11230. const btn = document.getElementById('tools-ping-btn');
  11231. const btnText = document.getElementById('tools-ping-btn-text');
  11232. const spinner = document.getElementById('tools-ping-spinner');
  11233. if (btn) {
  11234. btn.disabled = false;
  11235. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11236. }
  11237. if (btnText) btnText.innerText = 'Stop Ping';
  11238. if (spinner) spinner.classList.remove('hidden');
  11239. }
  11240. function resetTracerouteButton() {
  11241. const btn = document.getElementById('tools-tr-btn');
  11242. const btnText = document.getElementById('tools-tr-btn-text');
  11243. const spinner = document.getElementById('tools-tr-spinner');
  11244. if (btn) {
  11245. btn.disabled = false;
  11246. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11247. }
  11248. if (btnText) btnText.innerText = 'Start Traceroute';
  11249. if (spinner) spinner.classList.add('hidden');
  11250. }
  11251. function setTracerouteRunningButton() {
  11252. const btn = document.getElementById('tools-tr-btn');
  11253. const btnText = document.getElementById('tools-tr-btn-text');
  11254. const spinner = document.getElementById('tools-tr-spinner');
  11255. if (btn) {
  11256. btn.disabled = false;
  11257. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11258. }
  11259. if (btnText) btnText.innerText = 'Stop Traceroute';
  11260. if (spinner) spinner.classList.remove('hidden');
  11261. }
  11262. async function executePing(e) {
  11263. if (e) e.preventDefault();
  11264. // If already running, clicking the button stops the stream!
  11265. if (pingAbortController) {
  11266. pingAbortController.abort();
  11267. pingAbortController = null;
  11268. resetPingButton();
  11269. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11270. return;
  11271. }
  11272. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11273. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11274. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11275. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11276. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11277. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11278. if (!target) {
  11279. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11280. return;
  11281. }
  11282. clearPingTable();
  11283. const resCard = document.getElementById('tools-ping-results');
  11284. if (resCard) resCard.classList.remove('hidden');
  11285. pingAbortController = new AbortController();
  11286. setPingRunningButton();
  11287. try {
  11288. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11289. method: 'POST',
  11290. headers: { 'Content-Type': 'application/json' },
  11291. body: JSON.stringify({
  11292. target,
  11293. count,
  11294. size,
  11295. timeout,
  11296. interface: iface,
  11297. dont_frag: dontFrag
  11298. }),
  11299. signal: pingAbortController.signal
  11300. });
  11301. if (!res.ok) {
  11302. const errText = await res.text();
  11303. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11304. resetPingButton();
  11305. pingAbortController = null;
  11306. return;
  11307. }
  11308. const reader = res.body.getReader();
  11309. const decoder = new TextDecoder('utf-8');
  11310. let buffer = '';
  11311. while (true) {
  11312. const { done, value } = await reader.read();
  11313. if (done) break;
  11314. buffer += decoder.decode(value, { stream: true });
  11315. const blocks = buffer.split('\n\n');
  11316. buffer = blocks.pop() || '';
  11317. for (const block of blocks) {
  11318. const trimmed = block.trim();
  11319. if (!trimmed) continue;
  11320. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11321. try {
  11322. const evt = JSON.parse(line);
  11323. handleLivePingEvent(evt);
  11324. } catch (parseErr) {
  11325. console.warn('Ping SSE parse error:', parseErr, line);
  11326. }
  11327. }
  11328. }
  11329. } catch (err) {
  11330. if (err.name === 'AbortError') {
  11331. // User aborted normally
  11332. } else {
  11333. showToast('Ping Error', err.message, 'error');
  11334. }
  11335. } finally {
  11336. pingAbortController = null;
  11337. resetPingButton();
  11338. }
  11339. }
  11340. function handleLivePingEvent(evt) {
  11341. const sentEl = document.getElementById('tools-ping-stat-sent');
  11342. const recvEl = document.getElementById('tools-ping-stat-recv');
  11343. const lossEl = document.getElementById('tools-ping-stat-loss');
  11344. const avgEl = document.getElementById('tools-ping-stat-avg');
  11345. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11346. const badge = document.getElementById('tools-ping-status-badge');
  11347. const tbody = document.getElementById('tools-ping-tbody');
  11348. const rawEl = document.getElementById('tools-ping-raw');
  11349. if (evt.raw && rawEl) {
  11350. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11351. rawEl.scrollTop = rawEl.scrollHeight;
  11352. }
  11353. if (evt.type === 'reply') {
  11354. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11355. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11356. if (lossEl && evt.packet_loss_pct !== undefined) {
  11357. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11358. lossEl.className = evt.packet_loss_pct === 0
  11359. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11360. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  11361. }
  11362. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11363. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11364. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11365. }
  11366. if (badge) {
  11367. if (evt.packet_loss_pct === 0) {
  11368. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  11369. badge.innerText = '100% OK';
  11370. } else {
  11371. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  11372. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11373. }
  11374. }
  11375. if (tbody) {
  11376. const tr = document.createElement('tr');
  11377. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11378. tr.innerHTML = `
  11379. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11380. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11381. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11382. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11383. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11384. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  11385. `;
  11386. tbody.appendChild(tr);
  11387. }
  11388. } else if (evt.type === 'timeout') {
  11389. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11390. if (lossEl && evt.packet_loss_pct !== undefined) {
  11391. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11392. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  11393. }
  11394. if (badge) {
  11395. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11396. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11397. }
  11398. if (tbody) {
  11399. const tr = document.createElement('tr');
  11400. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11401. tr.innerHTML = `
  11402. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11403. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11404. <td class="py-2 px-3 text-slate-600">--</td>
  11405. <td class="py-2 px-3 text-slate-600">--</td>
  11406. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11407. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  11408. `;
  11409. tbody.appendChild(tr);
  11410. }
  11411. } else if (evt.type === 'unreach') {
  11412. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11413. if (lossEl && evt.packet_loss_pct !== undefined) {
  11414. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11415. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11416. }
  11417. if (badge) {
  11418. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11419. badge.innerText = 'UNREACHABLE';
  11420. }
  11421. if (tbody) {
  11422. const tr = document.createElement('tr');
  11423. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11424. tr.innerHTML = `
  11425. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11426. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11427. <td class="py-2 px-3 text-slate-600">--</td>
  11428. <td class="py-2 px-3 text-slate-600">--</td>
  11429. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11430. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  11431. `;
  11432. tbody.appendChild(tr);
  11433. }
  11434. } else if (evt.type === 'stats') {
  11435. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11436. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11437. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11438. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11439. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11440. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11441. }
  11442. } else if (evt.type === 'done') {
  11443. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  11444. }
  11445. }
  11446. async function executeTraceroute(e) {
  11447. if (e) e.preventDefault();
  11448. if (tracerouteAbortController) {
  11449. tracerouteAbortController.abort();
  11450. tracerouteAbortController = null;
  11451. resetTracerouteButton();
  11452. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11453. return;
  11454. }
  11455. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11456. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11457. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11458. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11459. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11460. if (!target) {
  11461. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11462. return;
  11463. }
  11464. clearTracerouteTable();
  11465. const resCard = document.getElementById('tools-tr-results');
  11466. if (resCard) resCard.classList.remove('hidden');
  11467. tracerouteAbortController = new AbortController();
  11468. setTracerouteRunningButton();
  11469. try {
  11470. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11471. method: 'POST',
  11472. headers: { 'Content-Type': 'application/json' },
  11473. body: JSON.stringify({
  11474. target,
  11475. max_hops: maxHops,
  11476. protocol,
  11477. interface: iface,
  11478. resolve
  11479. }),
  11480. signal: tracerouteAbortController.signal
  11481. });
  11482. if (!res.ok) {
  11483. const errText = await res.text();
  11484. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11485. resetTracerouteButton();
  11486. tracerouteAbortController = null;
  11487. return;
  11488. }
  11489. const reader = res.body.getReader();
  11490. const decoder = new TextDecoder('utf-8');
  11491. let buffer = '';
  11492. while (true) {
  11493. const { done, value } = await reader.read();
  11494. if (done) break;
  11495. buffer += decoder.decode(value, { stream: true });
  11496. const blocks = buffer.split('\n\n');
  11497. buffer = blocks.pop() || '';
  11498. for (const block of blocks) {
  11499. const trimmed = block.trim();
  11500. if (!trimmed) continue;
  11501. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11502. try {
  11503. const evt = JSON.parse(line);
  11504. handleLiveTracerouteEvent(evt);
  11505. } catch (parseErr) {
  11506. console.warn('Traceroute SSE parse error:', parseErr, line);
  11507. }
  11508. }
  11509. }
  11510. } catch (err) {
  11511. if (err.name === 'AbortError') {
  11512. // User aborted normally
  11513. } else {
  11514. showToast('Traceroute Error', err.message, 'error');
  11515. }
  11516. } finally {
  11517. tracerouteAbortController = null;
  11518. resetTracerouteButton();
  11519. }
  11520. }
  11521. function handleLiveTracerouteEvent(evt) {
  11522. const statHops = document.getElementById('tools-tr-hops-count');
  11523. const tbody = document.getElementById('tools-tr-tbody');
  11524. const rawEl = document.getElementById('tools-tr-raw');
  11525. if (evt.raw && rawEl) {
  11526. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11527. rawEl.scrollTop = rawEl.scrollHeight;
  11528. }
  11529. if (evt.hops_count !== undefined && statHops) {
  11530. statHops.innerText = `${evt.hops_count} Hops`;
  11531. }
  11532. if (evt.type === 'hop' && evt.hop && tbody) {
  11533. const h = evt.hop;
  11534. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11535. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11536. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11537. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11538. const tr = document.createElement('tr');
  11539. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11540. tr.innerHTML = `
  11541. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11542. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11543. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11544. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11545. <td class="py-2.5 px-3 text-right">
  11546. ${isTimeout
  11547. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11548. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  11549. </td>
  11550. `;
  11551. tbody.appendChild(tr);
  11552. } else if (evt.type === 'done') {
  11553. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11554. }
  11555. }
  11556. async function executeMTR(e) {
  11557. if (e) e.preventDefault();
  11558. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11559. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11560. if (!target) {
  11561. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11562. return;
  11563. }
  11564. const btn = document.getElementById('tools-mtr-btn');
  11565. const spinner = document.getElementById('tools-mtr-spinner');
  11566. if (btn) btn.disabled = true;
  11567. if (spinner) spinner.classList.remove('hidden');
  11568. try {
  11569. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11570. method: 'POST',
  11571. headers: { 'Content-Type': 'application/json' },
  11572. body: JSON.stringify({ target, count: cycles })
  11573. });
  11574. const data = await res.json();
  11575. if (!res.ok) {
  11576. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11577. return;
  11578. }
  11579. const resCard = document.getElementById('tools-mtr-results');
  11580. if (resCard) resCard.classList.remove('hidden');
  11581. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11582. const statHops = document.getElementById('tools-mtr-hops-count');
  11583. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11584. const tbody = document.getElementById('tools-mtr-tbody');
  11585. if (tbody) {
  11586. if (hopsCount > 0) {
  11587. tbody.innerHTML = data.hops.map(h => {
  11588. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  11589. return `
  11590. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11591. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11592. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11593. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11594. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11595. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11596. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11597. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11598. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11599. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11600. </tr>
  11601. `;
  11602. }).join('');
  11603. } else {
  11604. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11605. }
  11606. }
  11607. const rawEl = document.getElementById('tools-mtr-raw');
  11608. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11609. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11610. } catch (err) {
  11611. showToast('MTR Error', err.message, 'error');
  11612. } finally {
  11613. if (btn) btn.disabled = false;
  11614. if (spinner) spinner.classList.add('hidden');
  11615. }
  11616. }
  11617. async function executeDNS(e) {
  11618. if (e) e.preventDefault();
  11619. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11620. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11621. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11622. if (!domain) {
  11623. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11624. return;
  11625. }
  11626. const btn = document.getElementById('tools-dns-btn');
  11627. const spinner = document.getElementById('tools-dns-spinner');
  11628. if (btn) btn.disabled = true;
  11629. if (spinner) spinner.classList.remove('hidden');
  11630. try {
  11631. const res = await fetch(`${API_BASE}/tools/dns`, {
  11632. method: 'POST',
  11633. headers: { 'Content-Type': 'application/json' },
  11634. body: JSON.stringify({ domain, type, server })
  11635. });
  11636. const data = await res.json();
  11637. if (!res.ok) {
  11638. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11639. return;
  11640. }
  11641. const resCard = document.getElementById('tools-dns-results');
  11642. if (resCard) resCard.classList.remove('hidden');
  11643. const metaEl = document.getElementById('tools-dns-meta');
  11644. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11645. const tbody = document.getElementById('tools-dns-tbody');
  11646. if (tbody) {
  11647. if (Array.isArray(data.records) && data.records.length > 0) {
  11648. tbody.innerHTML = data.records.map(r => `
  11649. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11650. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11651. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11652. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11653. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  11654. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11655. </tr>
  11656. `).join('');
  11657. } else {
  11658. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  11659. }
  11660. }
  11661. const rawEl = document.getElementById('tools-dns-raw');
  11662. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11663. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11664. } catch (err) {
  11665. showToast('DNS Error', err.message, 'error');
  11666. } finally {
  11667. if (btn) btn.disabled = false;
  11668. if (spinner) spinner.classList.add('hidden');
  11669. }
  11670. }
  11671. async function executePortProbe(e) {
  11672. if (e) e.preventDefault();
  11673. const target = document.getElementById('tools-port-target')?.value?.trim();
  11674. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11675. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11676. if (!target || !port) {
  11677. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11678. return;
  11679. }
  11680. const btn = document.getElementById('tools-port-btn');
  11681. const spinner = document.getElementById('tools-port-spinner');
  11682. if (btn) btn.disabled = true;
  11683. if (spinner) spinner.classList.remove('hidden');
  11684. try {
  11685. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11686. method: 'POST',
  11687. headers: { 'Content-Type': 'application/json' },
  11688. body: JSON.stringify({ target, port, timeout })
  11689. });
  11690. const data = await res.json();
  11691. if (!res.ok) {
  11692. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11693. return;
  11694. }
  11695. const resCard = document.getElementById('tools-port-results');
  11696. if (resCard) resCard.classList.remove('hidden');
  11697. const banner = document.getElementById('tools-port-banner');
  11698. const icon = document.getElementById('tools-port-icon');
  11699. const title = document.getElementById('tools-port-title');
  11700. const sub = document.getElementById('tools-port-sub');
  11701. const latency = document.getElementById('tools-port-latency');
  11702. if (data.open) {
  11703. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11704. if (icon) {
  11705. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  11706. icon.innerText = '✓';
  11707. }
  11708. if (title) {
  11709. title.className = 'text-sm font-bold text-emerald-300';
  11710. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11711. }
  11712. if (sub) {
  11713. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11714. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11715. }
  11716. if (latency) {
  11717. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11718. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11719. }
  11720. } else {
  11721. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11722. if (icon) {
  11723. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  11724. icon.innerText = '✕';
  11725. }
  11726. if (title) {
  11727. title.className = 'text-sm font-bold text-rose-300';
  11728. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11729. }
  11730. if (sub) {
  11731. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11732. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11733. }
  11734. if (latency) {
  11735. latency.className = 'text-base font-bold font-mono text-slate-500';
  11736. latency.innerText = '--';
  11737. }
  11738. }
  11739. const rawEl = document.getElementById('tools-port-raw');
  11740. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  11741. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11742. } catch (err) {
  11743. showToast('Probe Error', err.message, 'error');
  11744. } finally {
  11745. if (btn) btn.disabled = false;
  11746. if (spinner) spinner.classList.add('hidden');
  11747. }
  11748. }
  11749. // ==========================================
  11750. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11751. // ==========================================
  11752. async function loadDHCPClients(showToastMsg = false) {
  11753. try {
  11754. const [clientsRes, sumRes] = await Promise.all([
  11755. fetch(`${API_BASE}/dhcp/clients`),
  11756. fetch(`${API_BASE}/dhcp/clients/summary`)
  11757. ]);
  11758. if (clientsRes.ok) {
  11759. state.dhcpClients = await clientsRes.json();
  11760. }
  11761. if (sumRes.ok) {
  11762. state.dhcpSummary = await sumRes.json();
  11763. }
  11764. renderDHCPClients();
  11765. updateDHCPSummaryCards();
  11766. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11767. if (bDhcp && state.dhcpSummary) {
  11768. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11769. }
  11770. if (showToastMsg) {
  11771. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11772. }
  11773. } catch (err) {
  11774. console.error('Failed to load DHCP clients:', err);
  11775. if (showToastMsg) {
  11776. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11777. }
  11778. }
  11779. }
  11780. function updateDHCPSummaryCards() {
  11781. const sum = state.dhcpSummary || {
  11782. total_clients: (state.dhcpClients || []).length,
  11783. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11784. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11785. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11786. };
  11787. const totalEl = document.getElementById('dhcp-stat-total');
  11788. const boundEl = document.getElementById('dhcp-stat-bound');
  11789. const searchEl = document.getElementById('dhcp-stat-searching');
  11790. const disEl = document.getElementById('dhcp-stat-disabled');
  11791. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11792. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11793. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11794. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11795. }
  11796. function renderDHCPClients() {
  11797. const tbody = document.getElementById('dhcp-clients-tbody');
  11798. const emptyState = document.getElementById('dhcp-clients-empty');
  11799. if (!tbody) return;
  11800. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11801. if (clients.length === 0) {
  11802. tbody.innerHTML = '';
  11803. if (emptyState) emptyState.classList.remove('hidden');
  11804. return;
  11805. }
  11806. if (emptyState) emptyState.classList.add('hidden');
  11807. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11808. if (tbody.dataset.sig === sig) return;
  11809. tbody.dataset.sig = sig;
  11810. tbody.innerHTML = clients.map(c => {
  11811. let statusBadge = '';
  11812. if (!c.enabled) {
  11813. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  11814. } else if (c.status === 'bound') {
  11815. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  11816. } else if (c.status === 'searching') {
  11817. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  11818. } else if (c.status === 'stopped') {
  11819. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  11820. } else {
  11821. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  11822. }
  11823. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  11824. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11825. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11826. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  11827. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11828. // Option flags
  11829. const flags = [];
  11830. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  11831. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  11832. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  11833. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  11834. return `
  11835. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11836. <td class="py-3 px-4">
  11837. <div class="flex items-center gap-2">
  11838. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11839. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11840. </div>
  11841. </td>
  11842. <td class="py-3 px-4">${statusBadge}</td>
  11843. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11844. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11845. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11846. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11847. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11848. <td class="py-3 px-4">
  11849. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11850. </td>
  11851. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11852. ${c.enabled ? `
  11853. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  11854. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  11855. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  11856. ` : `
  11857. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  11858. `}
  11859. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  11860. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  11861. </td>
  11862. </tr>
  11863. `;
  11864. }).join('');
  11865. }
  11866. function openDHCPClientModal(clientId = null) {
  11867. const modal = document.getElementById('modal-dhcp-client');
  11868. if (!modal) return;
  11869. const title = document.getElementById('modal-dhcp-title');
  11870. const idInput = document.getElementById('modal-dhcp-id');
  11871. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11872. const distInput = document.getElementById('modal-dhcp-distance');
  11873. const commentInput = document.getElementById('modal-dhcp-comment');
  11874. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11875. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11876. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11877. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11878. // Populate interfaces
  11879. if (ifaceSelect) {
  11880. let opts = '<option value="">Select interface...</option>';
  11881. const allIfaces = state.interfaces || [];
  11882. const allVlans = state.vlans || [];
  11883. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11884. // Group 1: Physical & Bridge Interfaces
  11885. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11886. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11887. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11888. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11889. });
  11890. opts += '</optgroup>';
  11891. // Group 2: VLAN Interfaces
  11892. if (allVlans.length > 0) {
  11893. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11894. allVlans.forEach(v => {
  11895. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11896. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11897. });
  11898. opts += '</optgroup>';
  11899. }
  11900. ifaceSelect.innerHTML = opts;
  11901. }
  11902. if (clientId) {
  11903. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11904. if (client) {
  11905. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11906. if (idInput) idInput.value = client.id;
  11907. if (ifaceSelect) {
  11908. ifaceSelect.value = client.interface;
  11909. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11910. }
  11911. if (distInput) distInput.value = client.default_route_distance || 1;
  11912. if (commentInput) commentInput.value = client.comment || '';
  11913. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11914. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11915. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11916. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11917. }
  11918. } else {
  11919. if (title) title.innerText = 'Add DHCP Client';
  11920. if (idInput) idInput.value = '';
  11921. if (ifaceSelect) {
  11922. ifaceSelect.value = '';
  11923. ifaceSelect.disabled = false;
  11924. }
  11925. if (distInput) distInput.value = 1;
  11926. if (commentInput) commentInput.value = '';
  11927. if (defRouteCheck) defRouteCheck.checked = true;
  11928. if (peerDnsCheck) peerDnsCheck.checked = true;
  11929. if (peerNtpCheck) peerNtpCheck.checked = true;
  11930. if (enabledCheck) enabledCheck.checked = true;
  11931. }
  11932. modal.classList.remove('hidden');
  11933. }
  11934. function openDHCPClientModalForIface(ifaceName) {
  11935. openDHCPClientModal();
  11936. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11937. if (ifaceSelect && ifaceName) {
  11938. ifaceSelect.value = ifaceName;
  11939. }
  11940. }
  11941. function closeDHCPClientModal() {
  11942. const modal = document.getElementById('modal-dhcp-client');
  11943. if (modal) modal.classList.add('hidden');
  11944. }
  11945. async function submitSaveDHCPClient(e) {
  11946. if (e) e.preventDefault();
  11947. const id = document.getElementById('modal-dhcp-id')?.value;
  11948. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11949. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11950. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11951. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11952. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11953. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11954. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11955. if (!id && !iface) {
  11956. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11957. return;
  11958. }
  11959. try {
  11960. let res;
  11961. if (id) {
  11962. // PUT update
  11963. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11964. method: 'PUT',
  11965. headers: { 'Content-Type': 'application/json' },
  11966. body: JSON.stringify({
  11967. enabled,
  11968. add_default_route: defRoute,
  11969. default_route_distance: distance,
  11970. use_peer_dns: peerDns,
  11971. use_peer_ntp: peerNtp,
  11972. comment
  11973. })
  11974. });
  11975. } else {
  11976. // POST create
  11977. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11978. method: 'POST',
  11979. headers: { 'Content-Type': 'application/json' },
  11980. body: JSON.stringify({
  11981. interface: iface,
  11982. enabled,
  11983. add_default_route: defRoute,
  11984. default_route_distance: distance,
  11985. use_peer_dns: peerDns,
  11986. use_peer_ntp: peerNtp,
  11987. comment
  11988. })
  11989. });
  11990. }
  11991. const data = await res.json();
  11992. if (!res.ok) {
  11993. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11994. return;
  11995. }
  11996. closeDHCPClientModal();
  11997. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11998. await loadDHCPClients();
  11999. fetchData(); // refresh interfaces list with new lease/status
  12000. } catch (err) {
  12001. showToast('Error', err.message, 'error');
  12002. }
  12003. }
  12004. async function toggleDHCPClientState(id, enabled) {
  12005. try {
  12006. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12007. method: 'POST',
  12008. headers: { 'Content-Type': 'application/json' },
  12009. body: JSON.stringify({ enabled })
  12010. });
  12011. const data = await res.json();
  12012. if (!res.ok) {
  12013. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12014. return;
  12015. }
  12016. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12017. await loadDHCPClients();
  12018. fetchData();
  12019. } catch (err) {
  12020. showToast('Error', err.message, 'error');
  12021. }
  12022. }
  12023. async function renewDHCPClient(id) {
  12024. try {
  12025. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12026. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12027. method: 'POST'
  12028. });
  12029. const data = await res.json();
  12030. if (!res.ok) {
  12031. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12032. return;
  12033. }
  12034. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12035. setTimeout(() => {
  12036. loadDHCPClients();
  12037. fetchData();
  12038. }, 1500);
  12039. } catch (err) {
  12040. showToast('Error', err.message, 'error');
  12041. }
  12042. }
  12043. async function releaseDHCPClient(id) {
  12044. try {
  12045. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12046. method: 'POST'
  12047. });
  12048. const data = await res.json();
  12049. if (!res.ok) {
  12050. showToast('Error', data.error || 'Failed to release lease', 'error');
  12051. return;
  12052. }
  12053. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12054. await loadDHCPClients();
  12055. fetchData();
  12056. } catch (err) {
  12057. showToast('Error', err.message, 'error');
  12058. }
  12059. }
  12060. async function deleteDHCPClient(id, ifaceName) {
  12061. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12062. return;
  12063. }
  12064. try {
  12065. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12066. method: 'DELETE'
  12067. });
  12068. const data = await res.json();
  12069. if (!res.ok) {
  12070. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12071. return;
  12072. }
  12073. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12074. await loadDHCPClients();
  12075. fetchData();
  12076. } catch (err) {
  12077. showToast('Error', err.message, 'error');
  12078. }
  12079. }
  12080. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12081. async function loadDHCPServer(populate = true) {
  12082. try {
  12083. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12084. fetch(`${API_BASE}/dhcp-server/summary`),
  12085. fetch(`${API_BASE}/dhcp-server/servers`),
  12086. fetch(`${API_BASE}/dhcp-server/networks`),
  12087. fetch(`${API_BASE}/dhcp-server/leases`),
  12088. fetch(`${API_BASE}/dhcp-server/options`)
  12089. ]);
  12090. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12091. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12092. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12093. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12094. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12095. const sum = state.dhcpServerSummary || {};
  12096. const srvs = state.dhcpServers || [];
  12097. const nets = state.dhcpNetworks || [];
  12098. const leases = state.dhcpLeases || [];
  12099. const opts = state.dhcpOptions || [];
  12100. // KPI Cards
  12101. const statActive = document.getElementById('dhcp-server-stat-active');
  12102. if (statActive) {
  12103. const activeCount = srvs.filter(s => s.running).length;
  12104. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12105. }
  12106. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12107. if (statLeases) {
  12108. statLeases.innerText = leases.length;
  12109. }
  12110. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12111. if (statLeasesSub) {
  12112. const dyn = leases.filter(l => l.dynamic).length;
  12113. const st = leases.filter(l => !l.dynamic).length;
  12114. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12115. }
  12116. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12117. if (statNetworks) {
  12118. statNetworks.innerText = nets.length;
  12119. }
  12120. // Subtab Badges
  12121. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12122. if (bSrv) bSrv.innerText = srvs.length;
  12123. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12124. if (bNet) bNet.innerText = nets.length;
  12125. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12126. if (bLease) bLease.innerText = leases.length;
  12127. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12128. if (bOpt) bOpt.innerText = opts.length;
  12129. // Sidebar Badge
  12130. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12131. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12132. renderCurrentDHCPServerTab();
  12133. } catch (err) {
  12134. console.error('Failed to load DHCP Server:', err);
  12135. }
  12136. }
  12137. function switchDHCPServerTab(tab) {
  12138. state.dhcpServerTab = tab;
  12139. const tabs = ['servers', 'networks', 'leases', 'options'];
  12140. tabs.forEach(t => {
  12141. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12142. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12143. if (panel) {
  12144. if (t === tab) panel.classList.remove('hidden');
  12145. else panel.classList.add('hidden');
  12146. }
  12147. if (btn) {
  12148. if (t === tab) {
  12149. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  12150. } else {
  12151. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  12152. }
  12153. }
  12154. });
  12155. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12156. if (addBtn) {
  12157. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12158. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12159. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12160. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12161. }
  12162. renderCurrentDHCPServerTab();
  12163. }
  12164. function handleDHCPServerPrimaryAdd() {
  12165. const tab = state.dhcpServerTab || 'servers';
  12166. if (tab === 'servers') openAddDHCPServerModal();
  12167. else if (tab === 'networks') openAddDHCPNetworkModal();
  12168. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12169. else if (tab === 'options') openAddDHCPOptionModal();
  12170. }
  12171. function renderCurrentDHCPServerTab() {
  12172. const tab = state.dhcpServerTab || 'servers';
  12173. if (tab === 'servers') renderDHCPServers();
  12174. else if (tab === 'networks') renderDHCPNetworks();
  12175. else if (tab === 'leases') renderDHCPLeases();
  12176. else if (tab === 'options') renderDHCPOptions();
  12177. }
  12178. function renderDHCPServers() {
  12179. const tbody = document.getElementById('dhcp-server-tbody');
  12180. const empty = document.getElementById('dhcp-server-empty');
  12181. if (!tbody) return;
  12182. const servers = state.dhcpServers || [];
  12183. if (servers.length === 0) {
  12184. tbody.innerHTML = '';
  12185. empty?.classList.remove('hidden');
  12186. return;
  12187. }
  12188. empty?.classList.add('hidden');
  12189. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12190. if (tbody.dataset.sig === sig) return;
  12191. tbody.dataset.sig = sig;
  12192. tbody.innerHTML = '';
  12193. servers.forEach(s => {
  12194. const tr = document.createElement('tr');
  12195. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12196. tr.innerHTML = `
  12197. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12198. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12199. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12200. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  12201. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12202. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12203. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12204. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  12205. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12206. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12207. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  12208. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12209. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12210. </td>
  12211. `;
  12212. tbody.appendChild(tr);
  12213. });
  12214. }
  12215. function renderDHCPNetworks() {
  12216. const tbody = document.getElementById('dhcp-networks-tbody');
  12217. const empty = document.getElementById('dhcp-networks-empty');
  12218. if (!tbody) return;
  12219. tbody.innerHTML = '';
  12220. const networks = state.dhcpNetworks || [];
  12221. if (networks.length === 0) {
  12222. empty?.classList.remove('hidden');
  12223. return;
  12224. }
  12225. empty?.classList.add('hidden');
  12226. networks.forEach(n => {
  12227. const tr = document.createElement('tr');
  12228. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12229. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12230. const optionsChips = (n.dhcp_options || []).map(optId => {
  12231. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12232. if (!opt) return '';
  12233. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  12234. }).filter(Boolean).join('');
  12235. tr.innerHTML = `
  12236. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12237. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12238. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12239. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12240. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12241. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12242. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12243. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12244. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12245. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12246. </td>
  12247. `;
  12248. tbody.appendChild(tr);
  12249. });
  12250. }
  12251. function renderDHCPLeases() {
  12252. const tbody = document.getElementById('dhcp-leases-tbody');
  12253. const empty = document.getElementById('dhcp-leases-empty');
  12254. if (!tbody) return;
  12255. tbody.innerHTML = '';
  12256. const leases = state.dhcpLeases || [];
  12257. if (leases.length === 0) {
  12258. empty?.classList.remove('hidden');
  12259. return;
  12260. }
  12261. empty?.classList.add('hidden');
  12262. leases.forEach(l => {
  12263. const tr = document.createElement('tr');
  12264. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12265. 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>';
  12266. const statusBadge = l.status === 'bound'
  12267. ? '<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>'
  12268. : l.status === 'static'
  12269. ? '<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>'
  12270. : '<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>';
  12271. const makeStaticBtn = l.dynamic
  12272. ? `<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>`
  12273. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12274. tr.innerHTML = `
  12275. <td class="py-2.5 px-3 text-center">${flag}</td>
  12276. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12277. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12278. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12279. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12280. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12281. <td class="py-2.5 px-3">${statusBadge}</td>
  12282. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12283. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12284. ${makeStaticBtn}
  12285. </td>
  12286. `;
  12287. tbody.appendChild(tr);
  12288. });
  12289. }
  12290. function renderDHCPOptions() {
  12291. const tbody = document.getElementById('dhcp-options-tbody');
  12292. const empty = document.getElementById('dhcp-options-empty');
  12293. if (!tbody) return;
  12294. tbody.innerHTML = '';
  12295. const options = state.dhcpOptions || [];
  12296. if (options.length === 0) {
  12297. empty?.classList.remove('hidden');
  12298. return;
  12299. }
  12300. empty?.classList.add('hidden');
  12301. options.forEach(o => {
  12302. const tr = document.createElement('tr');
  12303. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12304. tr.innerHTML = `
  12305. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12306. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12307. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12308. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12309. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12310. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12311. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12312. </td>
  12313. `;
  12314. tbody.appendChild(tr);
  12315. });
  12316. }
  12317. // ==================== MODALS & ACTIONS: SERVER ====================
  12318. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12319. const sel = document.getElementById(elemId);
  12320. if (!sel) return;
  12321. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12322. const networks = state.dhcpNetworks || [];
  12323. networks.forEach(n => {
  12324. const opt = document.createElement('option');
  12325. opt.value = n.address;
  12326. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12327. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12328. opt.selected = true;
  12329. }
  12330. sel.appendChild(opt);
  12331. });
  12332. }
  12333. function onDHCPServerNetworkChange() {
  12334. const netSel = document.getElementById('dhcp-server-modal-network');
  12335. if (!netSel) return;
  12336. const netVal = netSel.value;
  12337. if (!netVal) return;
  12338. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12339. if (!poolInput) return;
  12340. // Auto-calculate suggested address pool based on subnet CIDR
  12341. const parts = netVal.split('/');
  12342. const ip = parts[0];
  12343. const cidr = parseInt(parts[1] || '24', 10);
  12344. if (cidr === 24) {
  12345. const octets = ip.split('.');
  12346. if (octets.length === 4) {
  12347. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12348. poolInput.value = `${base}.10-${base}.254`;
  12349. }
  12350. }
  12351. }
  12352. function openAddDHCPServerModal() {
  12353. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12354. document.getElementById('dhcp-server-modal-id').value = '';
  12355. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12356. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12357. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12358. document.getElementById('dhcp-server-modal-comment').value = '';
  12359. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12360. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12361. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12362. const networks = state.dhcpNetworks || [];
  12363. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12364. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12365. if (defaultNet) {
  12366. onDHCPServerNetworkChange();
  12367. }
  12368. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12369. }
  12370. function openEditDHCPServerModal(id) {
  12371. const s = (state.dhcpServers || []).find(item => item.id === id);
  12372. if (!s) return;
  12373. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12374. document.getElementById('dhcp-server-modal-id').value = s.id;
  12375. document.getElementById('dhcp-server-modal-name').value = s.name;
  12376. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12377. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12378. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12379. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12380. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12381. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12382. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12383. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12384. }
  12385. function closeDHCPServerModal() {
  12386. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12387. }
  12388. async function submitSaveDHCPServer(e) {
  12389. e.preventDefault();
  12390. const id = document.getElementById('dhcp-server-modal-id').value;
  12391. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12392. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12393. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12394. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12395. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12396. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12397. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12398. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12399. try {
  12400. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12401. method: 'POST',
  12402. headers: { 'Content-Type': 'application/json' },
  12403. body: JSON.stringify({
  12404. id,
  12405. name,
  12406. interface: iface,
  12407. network,
  12408. address_pool: pool,
  12409. lease_time: leaseTime,
  12410. authoritative,
  12411. disabled,
  12412. comment
  12413. })
  12414. });
  12415. if (res.ok) {
  12416. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12417. closeDHCPServerModal();
  12418. loadDHCPServer(false);
  12419. fetchData(false);
  12420. } else {
  12421. const err = await res.text();
  12422. showToast('Error', err, 'error');
  12423. }
  12424. } catch (err) {
  12425. showToast('Error', err.message, 'error');
  12426. }
  12427. }
  12428. async function toggleDHCPServerState(id, disabled) {
  12429. try {
  12430. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12431. method: 'POST',
  12432. headers: { 'Content-Type': 'application/json' },
  12433. body: JSON.stringify({ disabled })
  12434. });
  12435. if (res.ok) {
  12436. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12437. loadDHCPServer(false);
  12438. fetchData(false);
  12439. }
  12440. } catch (err) {
  12441. showToast('Error', err.message, 'error');
  12442. }
  12443. }
  12444. async function deleteDHCPServer(id, name) {
  12445. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12446. try {
  12447. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12448. if (res.ok) {
  12449. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12450. loadDHCPServer(false);
  12451. fetchData(false);
  12452. }
  12453. } catch (err) {
  12454. showToast('Error', err.message, 'error');
  12455. }
  12456. }
  12457. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12458. function openAddDHCPNetworkModal() {
  12459. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12460. document.getElementById('dhcp-network-modal-id').value = '';
  12461. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12462. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12463. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12464. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12465. document.getElementById('dhcp-network-modal-netmask').value = '';
  12466. document.getElementById('dhcp-network-modal-comment').value = '';
  12467. renderDHCPNetworkOptionsCheckboxes([]);
  12468. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12469. }
  12470. function openEditDHCPNetworkModal(id) {
  12471. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12472. if (!n) return;
  12473. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12474. document.getElementById('dhcp-network-modal-id').value = n.id;
  12475. document.getElementById('dhcp-network-modal-address').value = n.address;
  12476. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12477. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12478. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12479. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12480. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12481. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12482. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12483. }
  12484. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12485. const container = document.getElementById('dhcp-network-modal-options-list');
  12486. if (!container) return;
  12487. container.innerHTML = '';
  12488. const opts = state.dhcpOptions || [];
  12489. if (opts.length === 0) {
  12490. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12491. return;
  12492. }
  12493. opts.forEach(o => {
  12494. const isChecked = selectedIds.includes(o.id);
  12495. const label = document.createElement('label');
  12496. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12497. label.innerHTML = `
  12498. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12499. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12500. `;
  12501. container.appendChild(label);
  12502. });
  12503. }
  12504. function closeDHCPNetworkModal() {
  12505. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12506. }
  12507. async function submitSaveDHCPNetwork(e) {
  12508. e.preventDefault();
  12509. const id = document.getElementById('dhcp-network-modal-id').value;
  12510. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12511. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12512. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12513. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12514. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12515. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12516. const selectedOpts = [];
  12517. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12518. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12519. try {
  12520. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12521. method: 'POST',
  12522. headers: { 'Content-Type': 'application/json' },
  12523. body: JSON.stringify({
  12524. id,
  12525. address,
  12526. gateway,
  12527. netmask,
  12528. dns_servers: dnsServers,
  12529. domain,
  12530. dhcp_options: selectedOpts,
  12531. comment
  12532. })
  12533. });
  12534. if (res.ok) {
  12535. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12536. closeDHCPNetworkModal();
  12537. loadDHCPServer(false);
  12538. fetchData(false);
  12539. } else {
  12540. const err = await res.text();
  12541. showToast('Error', err, 'error');
  12542. }
  12543. } catch (err) {
  12544. showToast('Error', err.message, 'error');
  12545. }
  12546. }
  12547. async function deleteDHCPNetwork(id, addr) {
  12548. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12549. try {
  12550. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12551. if (res.ok) {
  12552. showToast('Deleted', `Network ${addr} removed`, 'success');
  12553. loadDHCPServer(false);
  12554. fetchData(false);
  12555. }
  12556. } catch (err) {
  12557. showToast('Error', err.message, 'error');
  12558. }
  12559. }
  12560. // ==================== MODALS & ACTIONS: LEASES ====================
  12561. function openAddDHCPStaticLeaseModal() {
  12562. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12563. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12564. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12565. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12566. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12567. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12568. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12569. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12570. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12571. }
  12572. function closeDHCPStaticLeaseModal() {
  12573. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12574. }
  12575. async function submitSaveDHCPStaticLease(e) {
  12576. e.preventDefault();
  12577. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12578. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12579. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12580. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12581. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12582. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12583. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12584. try {
  12585. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12586. method: 'POST',
  12587. headers: { 'Content-Type': 'application/json' },
  12588. body: JSON.stringify({
  12589. id,
  12590. mac_address: mac,
  12591. address: ip,
  12592. hostname,
  12593. server,
  12594. comment,
  12595. disabled
  12596. })
  12597. });
  12598. if (res.ok) {
  12599. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12600. closeDHCPStaticLeaseModal();
  12601. loadDHCPServer(false);
  12602. fetchData(false);
  12603. } else {
  12604. const err = await res.text();
  12605. showToast('Error', err, 'error');
  12606. }
  12607. } catch (err) {
  12608. showToast('Error', err.message, 'error');
  12609. }
  12610. }
  12611. async function deleteDHCPStaticLease(id) {
  12612. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12613. try {
  12614. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12615. if (res.ok) {
  12616. showToast('Deleted', 'Static lease removed', 'success');
  12617. loadDHCPServer(false);
  12618. fetchData(false);
  12619. }
  12620. } catch (err) {
  12621. showToast('Error', err.message, 'error');
  12622. }
  12623. }
  12624. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12625. try {
  12626. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12627. method: 'POST',
  12628. headers: { 'Content-Type': 'application/json' },
  12629. body: JSON.stringify({
  12630. mac_address: mac,
  12631. address: ip,
  12632. hostname,
  12633. comment: comment || 'Converted to static'
  12634. })
  12635. });
  12636. if (res.ok) {
  12637. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12638. loadDHCPServer(false);
  12639. fetchData(false);
  12640. } else {
  12641. const err = await res.text();
  12642. showToast('Error', err, 'error');
  12643. }
  12644. } catch (err) {
  12645. showToast('Error', err.message, 'error');
  12646. }
  12647. }
  12648. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12649. function openAddDHCPOptionModal() {
  12650. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12651. document.getElementById('dhcp-option-modal-id').value = '';
  12652. document.getElementById('dhcp-option-modal-name').value = '';
  12653. document.getElementById('dhcp-option-modal-code').value = '';
  12654. document.getElementById('dhcp-option-modal-value').value = '';
  12655. document.getElementById('dhcp-option-modal-comment').value = '';
  12656. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12657. }
  12658. function openEditDHCPOptionModal(id) {
  12659. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12660. if (!o) return;
  12661. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12662. document.getElementById('dhcp-option-modal-id').value = o.id;
  12663. document.getElementById('dhcp-option-modal-name').value = o.name;
  12664. document.getElementById('dhcp-option-modal-code').value = o.code;
  12665. document.getElementById('dhcp-option-modal-value').value = o.value;
  12666. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12667. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12668. }
  12669. function closeDHCPOptionModal() {
  12670. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12671. }
  12672. async function submitSaveDHCPOption(e) {
  12673. e.preventDefault();
  12674. const id = document.getElementById('dhcp-option-modal-id').value;
  12675. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12676. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12677. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12678. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12679. try {
  12680. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12681. method: 'POST',
  12682. headers: { 'Content-Type': 'application/json' },
  12683. body: JSON.stringify({ id, name, code, value, comment })
  12684. });
  12685. if (res.ok) {
  12686. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12687. closeDHCPOptionModal();
  12688. loadDHCPServer(false);
  12689. fetchData(false);
  12690. } else {
  12691. const err = await res.text();
  12692. showToast('Error', err, 'error');
  12693. }
  12694. } catch (err) {
  12695. showToast('Error', err.message, 'error');
  12696. }
  12697. }
  12698. async function deleteDHCPOption(id, name) {
  12699. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12700. try {
  12701. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12702. if (res.ok) {
  12703. showToast('Deleted', `Option ${name} removed`, 'success');
  12704. loadDHCPServer(false);
  12705. fetchData(false);
  12706. }
  12707. } catch (err) {
  12708. showToast('Error', err.message, 'error');
  12709. }
  12710. }
  12711. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12712. function openDHCPServerSetupModal() {
  12713. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12714. onDHCPWizardIfaceChange();
  12715. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12716. }
  12717. function closeDHCPServerSetupModal() {
  12718. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12719. }
  12720. function onDHCPWizardIfaceChange() {
  12721. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12722. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12723. let ip = '192.168.88.1';
  12724. let prefix = '24';
  12725. if (iface && iface.ip_address) {
  12726. const parts = iface.ip_address.split('/');
  12727. ip = parts[0];
  12728. if (parts.length > 1) prefix = parts[1];
  12729. }
  12730. // Calculate subnet base (e.g. 192.168.88.0/24)
  12731. const ipParts = ip.split('.');
  12732. if (ipParts.length === 4) {
  12733. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12734. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12735. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12736. document.getElementById('dhcp-wizard-gateway').value = ip;
  12737. document.getElementById('dhcp-wizard-pool').value = pool;
  12738. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12739. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12740. }
  12741. }
  12742. async function submitDHCPServerSetupWizard(e) {
  12743. e.preventDefault();
  12744. const iface = document.getElementById('dhcp-wizard-iface').value;
  12745. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12746. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12747. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12748. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12749. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12750. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12751. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12752. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12753. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12754. try {
  12755. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12756. method: 'POST',
  12757. headers: { 'Content-Type': 'application/json' },
  12758. body: JSON.stringify({
  12759. interface: iface,
  12760. address_space: space,
  12761. gateway: gw,
  12762. address_pool: pool,
  12763. dns_servers: dnsServers,
  12764. lease_time: leaseTime,
  12765. ntp_servers: ntpServers,
  12766. next_server: tftp
  12767. })
  12768. });
  12769. if (res.ok) {
  12770. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12771. closeDHCPServerSetupModal();
  12772. loadDHCPServer(false);
  12773. fetchData(false);
  12774. } else {
  12775. const err = await res.text();
  12776. showToast('Error', err, 'error');
  12777. }
  12778. } catch (err) {
  12779. showToast('Error', err.message, 'error');
  12780. }
  12781. }
  12782. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12783. const sel = document.getElementById(elemId);
  12784. if (!sel) return;
  12785. sel.innerHTML = '<option value="">Select interface...</option>';
  12786. const ifaces = state.interfaces || [];
  12787. ifaces.forEach(i => {
  12788. if (i.name === 'lo') return;
  12789. const opt = document.createElement('option');
  12790. opt.value = i.name;
  12791. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12792. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12793. if (i.name === selectedVal) opt.selected = true;
  12794. sel.appendChild(opt);
  12795. });
  12796. }
  12797. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12798. function initTableSorting() {
  12799. document.querySelectorAll('table').forEach(setupSortableTable);
  12800. }
  12801. function setupSortableTable(table) {
  12802. const thead = table.querySelector('thead');
  12803. const tbody = table.querySelector('tbody');
  12804. if (!thead || !tbody) return;
  12805. const headerRows = thead.querySelectorAll('tr');
  12806. if (headerRows.length === 0) return;
  12807. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12808. ths.forEach((th, colIdx) => {
  12809. if (th._sortBound) return;
  12810. th._sortBound = true;
  12811. const rawText = th.innerText.trim().toLowerCase();
  12812. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12813. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12814. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12815. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12816. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12817. return;
  12818. }
  12819. th.classList.add('table-sortable', 'group');
  12820. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12821. let icon = th.querySelector('.table-sort-icon');
  12822. if (!icon) {
  12823. icon = document.createElement('span');
  12824. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12825. icon.innerHTML = '⇅';
  12826. th.appendChild(icon);
  12827. }
  12828. th.addEventListener('click', (e) => {
  12829. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12830. handleHeaderClick(table, th, colIdx);
  12831. });
  12832. });
  12833. if (!tbody._sortObserved) {
  12834. tbody._sortObserved = true;
  12835. let sortDebounceTimer = null;
  12836. const observer = new MutationObserver((mutations) => {
  12837. if (tbody._isSorting) return;
  12838. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12839. if (!hasChildChanges) return;
  12840. clearTimeout(sortDebounceTimer);
  12841. sortDebounceTimer = setTimeout(() => {
  12842. if (tbody._isSorting) return;
  12843. if (table._activeSort && table._activeSort.dir !== 'none') {
  12844. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12845. } else {
  12846. tagOriginalRowOrder(tbody);
  12847. }
  12848. }, 50);
  12849. });
  12850. tbody._sortObserver = observer;
  12851. observer.observe(tbody, { childList: true });
  12852. }
  12853. tagOriginalRowOrder(tbody);
  12854. }
  12855. function tagOriginalRowOrder(tbody) {
  12856. let idx = 0;
  12857. Array.from(tbody.children).forEach(tr => {
  12858. if (!tr.querySelector('td[colspan]')) {
  12859. if (!tr.hasAttribute('data-orig-idx')) {
  12860. tr.setAttribute('data-orig-idx', idx++);
  12861. }
  12862. }
  12863. });
  12864. }
  12865. function handleHeaderClick(table, th, colIdx) {
  12866. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12867. let newDir = 'asc';
  12868. if (currentSort.colIdx === colIdx) {
  12869. if (currentSort.dir === 'asc') newDir = 'desc';
  12870. else if (currentSort.dir === 'desc') newDir = 'none';
  12871. else newDir = 'asc';
  12872. } else {
  12873. newDir = 'asc';
  12874. }
  12875. table._activeSort = { colIdx, dir: newDir };
  12876. updateHeaderIcons(table, colIdx, newDir);
  12877. applyTableSort(table, colIdx, newDir, true);
  12878. }
  12879. function updateHeaderIcons(table, activeColIdx, dir) {
  12880. const thead = table.querySelector('thead');
  12881. if (!thead) return;
  12882. const ths = thead.querySelectorAll('th');
  12883. ths.forEach((th, idx) => {
  12884. const icon = th.querySelector('.table-sort-icon');
  12885. if (!icon) return;
  12886. if (idx === activeColIdx && dir !== 'none') {
  12887. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12888. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12889. th.classList.add('table-sorted-active');
  12890. } else {
  12891. icon.innerHTML = '⇅';
  12892. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12893. th.classList.remove('table-sorted-active');
  12894. }
  12895. });
  12896. }
  12897. function applyTableSort(table, colIdx, dir, userInitiated) {
  12898. const tbody = table.querySelector('tbody');
  12899. if (!tbody || tbody.children.length <= 1) return;
  12900. tbody._isSorting = true;
  12901. tagOriginalRowOrder(tbody);
  12902. // Group parent rows and any attached drawer/sub-rows
  12903. const groups = [];
  12904. let currentGroup = null;
  12905. Array.from(tbody.children).forEach(tr => {
  12906. if (tr.querySelector('td[colspan]')) {
  12907. if (currentGroup) {
  12908. currentGroup.subRows.push(tr);
  12909. } else {
  12910. groups.push({ mainRow: tr, subRows: [] });
  12911. }
  12912. } else {
  12913. currentGroup = { mainRow: tr, subRows: [] };
  12914. groups.push(currentGroup);
  12915. }
  12916. });
  12917. if (dir === 'none') {
  12918. groups.sort((a, b) => {
  12919. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12920. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12921. return idxA - idxB;
  12922. });
  12923. } else {
  12924. groups.sort((a, b) => {
  12925. const cellA = a.mainRow.children[colIdx];
  12926. const cellB = b.mainRow.children[colIdx];
  12927. const res = compareTableCells(cellA, cellB);
  12928. return dir === 'asc' ? res : -res;
  12929. });
  12930. }
  12931. // Check if rows are already in correct order to avoid modifying DOM
  12932. let alreadyOrdered = true;
  12933. let childIdx = 0;
  12934. for (const g of groups) {
  12935. if (tbody.children[childIdx] !== g.mainRow) {
  12936. alreadyOrdered = false;
  12937. break;
  12938. }
  12939. childIdx++;
  12940. for (const sub of g.subRows) {
  12941. if (tbody.children[childIdx] !== sub) {
  12942. alreadyOrdered = false;
  12943. break;
  12944. }
  12945. childIdx++;
  12946. }
  12947. }
  12948. if (alreadyOrdered) {
  12949. tbody._isSorting = false;
  12950. return;
  12951. }
  12952. // Disconnect observer while re-ordering to prevent recursion and thrashing
  12953. if (tbody._sortObserver) {
  12954. tbody._sortObserver.disconnect();
  12955. }
  12956. // Re-append rows in sorted order
  12957. groups.forEach(g => {
  12958. tbody.appendChild(g.mainRow);
  12959. g.subRows.forEach(sub => tbody.appendChild(sub));
  12960. });
  12961. // Drain any queued mutations and re-connect observer
  12962. if (tbody._sortObserver) {
  12963. tbody._sortObserver.takeRecords();
  12964. tbody._sortObserver.observe(tbody, { childList: true });
  12965. }
  12966. tbody._isSorting = false;
  12967. }
  12968. function getCellRawText(cell) {
  12969. if (!cell) return '';
  12970. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12971. const input = cell.querySelector('input, select');
  12972. if (input) {
  12973. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12974. return input.value;
  12975. }
  12976. return cell.innerText.trim();
  12977. }
  12978. function parseTrafficToNumber(str) {
  12979. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12980. if (!m) return null;
  12981. const num = parseFloat(m[1].replace(/,/g, ''));
  12982. if (isNaN(num)) return null;
  12983. const unit = m[2].toUpperCase();
  12984. let mult = 1;
  12985. if (unit.startsWith('K')) mult = 1024;
  12986. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12987. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12988. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12989. return num * mult;
  12990. }
  12991. function parseIpToNumber(str) {
  12992. const clean = str.replace(/^[!~]/, '').trim();
  12993. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12994. if (!m) return null;
  12995. const o1 = parseInt(m[1], 10);
  12996. const o2 = parseInt(m[2], 10);
  12997. const o3 = parseInt(m[3], 10);
  12998. const o4 = parseInt(m[4], 10);
  12999. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13000. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13001. }
  13002. function parseCompoundPackets(str) {
  13003. const m = str.match(/^([\d,]+)p/);
  13004. if (!m) return null;
  13005. return parseInt(m[1].replace(/,/g, ''), 10);
  13006. }
  13007. function compareTableCells(cellA, cellB) {
  13008. const a = getCellRawText(cellA);
  13009. const b = getCellRawText(cellB);
  13010. if (a === '' && b !== '') return 1;
  13011. if (b === '' && a !== '') return -1;
  13012. if (a === b) return 0;
  13013. // 1. IP Addresses / CIDR
  13014. const ipA = parseIpToNumber(a);
  13015. const ipB = parseIpToNumber(b);
  13016. if (ipA !== null && ipB !== null) return ipA - ipB;
  13017. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13018. const pktA = parseCompoundPackets(a);
  13019. const pktB = parseCompoundPackets(b);
  13020. if (pktA !== null && pktB !== null) return pktA - pktB;
  13021. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13022. const trafA = parseTrafficToNumber(a);
  13023. const trafB = parseTrafficToNumber(b);
  13024. if (trafA !== null && trafB !== null) return trafA - trafB;
  13025. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13026. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13027. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13028. const numA = Number(cleanNumA);
  13029. const numB = Number(cleanNumB);
  13030. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13031. return numA - numB;
  13032. }
  13033. // 5. Natural case-insensitive string compare
  13034. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13035. }
  13036. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13037. async function loadVRRP(showToastNotification = false) {
  13038. try {
  13039. const [instRes, sumRes] = await Promise.all([
  13040. fetch(`${API_BASE}/vrrp/instances`),
  13041. fetch(`${API_BASE}/vrrp/summary`)
  13042. ]);
  13043. if (instRes.ok) {
  13044. state.vrrpInstances = await instRes.json();
  13045. renderVRRP();
  13046. }
  13047. if (sumRes.ok) {
  13048. state.vrrpSummary = await sumRes.json();
  13049. renderVRRPSummary();
  13050. }
  13051. if (showToastNotification) {
  13052. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13053. }
  13054. } catch (err) {
  13055. console.error('Failed to load VRRP:', err);
  13056. }
  13057. }
  13058. function renderVRRPSummary() {
  13059. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13060. const elTotal = document.getElementById('vrrp-stat-total');
  13061. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13062. const elMaster = document.getElementById('vrrp-stat-master');
  13063. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13064. const elBackup = document.getElementById('vrrp-stat-backup');
  13065. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13066. const bCount = document.getElementById('badge-vrrp-count');
  13067. if (bCount) bCount.innerText = s.total_instances || 0;
  13068. const dot = document.getElementById('badge-vrrp-dot');
  13069. if (dot) {
  13070. if (s.master_instances > 0) {
  13071. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13072. } else if (s.backup_instances > 0) {
  13073. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13074. } else {
  13075. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13076. }
  13077. }
  13078. }
  13079. function renderVRRP() {
  13080. const tbody = document.getElementById('vrrp-table-tbody');
  13081. const empty = document.getElementById('vrrp-table-empty');
  13082. if (!tbody) return;
  13083. tbody.innerHTML = '';
  13084. const instances = state.vrrpInstances || [];
  13085. if (instances.length === 0) {
  13086. empty?.classList.remove('hidden');
  13087. return;
  13088. }
  13089. empty?.classList.add('hidden');
  13090. instances.forEach(inst => {
  13091. const tr = document.createElement('tr');
  13092. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13093. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13094. 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>`;
  13095. if (inst.disabled) {
  13096. 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>`;
  13097. } else if (inst.state === 'MASTER') {
  13098. 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>`;
  13099. } else if (inst.state === 'BACKUP') {
  13100. 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>`;
  13101. } else if (inst.state === 'FAULT') {
  13102. 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>`;
  13103. }
  13104. // Render State Badge
  13105. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13106. if (!inst.disabled) {
  13107. if (inst.state === 'MASTER') {
  13108. 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>`;
  13109. } else if (inst.state === 'BACKUP') {
  13110. 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>`;
  13111. } else if (inst.state === 'FAULT') {
  13112. 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>`;
  13113. }
  13114. }
  13115. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13116. tr.innerHTML = `
  13117. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13118. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13119. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13120. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13121. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13122. <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>
  13123. <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>
  13124. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13125. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13126. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13127. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13128. <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>
  13129. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13130. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13131. </td>
  13132. `;
  13133. tbody.appendChild(tr);
  13134. });
  13135. }
  13136. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13137. const sel = document.getElementById(elemId);
  13138. if (!sel) return;
  13139. sel.innerHTML = '<option value="">Select interface...</option>';
  13140. const ifaces = state.interfaces || [];
  13141. ifaces.forEach(i => {
  13142. const opt = document.createElement('option');
  13143. opt.value = i.name;
  13144. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13145. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13146. sel.appendChild(opt);
  13147. });
  13148. }
  13149. function openAddVRRPModal() {
  13150. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13151. document.getElementById('modal-vrrp-id').value = '';
  13152. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13153. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13154. document.getElementById('modal-vrrp-priority').value = 100;
  13155. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13156. document.getElementById('modal-vrrp-version').value = '3';
  13157. document.getElementById('modal-vrrp-interval').value = 1;
  13158. document.getElementById('modal-vrrp-authtype').value = 'none';
  13159. document.getElementById('modal-vrrp-authpass').value = '';
  13160. document.getElementById('modal-vrrp-comment').value = '';
  13161. document.getElementById('modal-vrrp-preempt').checked = true;
  13162. document.getElementById('modal-vrrp-disabled').checked = false;
  13163. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13164. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13165. }
  13166. function openEditVRRPModal(id) {
  13167. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13168. if (!inst) return;
  13169. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13170. document.getElementById('modal-vrrp-id').value = inst.id;
  13171. document.getElementById('modal-vrrp-name').value = inst.name;
  13172. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13173. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13174. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13175. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13176. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13177. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13178. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13179. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13180. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13181. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13182. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13183. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13184. }
  13185. function closeVRRPModal() {
  13186. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13187. }
  13188. async function submitSaveVRRP(e) {
  13189. e.preventDefault();
  13190. const id = document.getElementById('modal-vrrp-id').value;
  13191. const name = document.getElementById('modal-vrrp-name').value.trim();
  13192. const iface = document.getElementById('modal-vrrp-iface').value;
  13193. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13194. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13195. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13196. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13197. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13198. const authType = document.getElementById('modal-vrrp-authtype').value;
  13199. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13200. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13201. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13202. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13203. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13204. try {
  13205. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13206. method: 'POST',
  13207. headers: { 'Content-Type': 'application/json' },
  13208. body: JSON.stringify({
  13209. id,
  13210. name,
  13211. interface: iface,
  13212. vrid,
  13213. priority,
  13214. virtual_ips: vips,
  13215. version,
  13216. interval,
  13217. auth_type: authType,
  13218. auth_password: authPass,
  13219. comment,
  13220. preempt,
  13221. disabled
  13222. })
  13223. });
  13224. if (res.ok) {
  13225. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13226. closeVRRPModal();
  13227. loadVRRP(false);
  13228. fetchData(false);
  13229. } else {
  13230. const err = await res.text();
  13231. showToast('Error', err, 'error');
  13232. }
  13233. } catch (err) {
  13234. showToast('Error', err.message, 'error');
  13235. }
  13236. }
  13237. async function deleteVRRP(id, name) {
  13238. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13239. try {
  13240. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13241. if (res.ok) {
  13242. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13243. loadVRRP(false);
  13244. fetchData(false);
  13245. } else {
  13246. const err = await res.text();
  13247. showToast('Error', err, 'error');
  13248. }
  13249. } catch (err) {
  13250. showToast('Error', err.message, 'error');
  13251. }
  13252. }
  13253. async function toggleVRRPState(id, disabled) {
  13254. try {
  13255. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13256. method: 'POST',
  13257. headers: { 'Content-Type': 'application/json' },
  13258. body: JSON.stringify({ disabled })
  13259. });
  13260. if (res.ok) {
  13261. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13262. loadVRRP(false);
  13263. fetchData(false);
  13264. } else {
  13265. const err = await res.text();
  13266. showToast('Error', err, 'error');
  13267. }
  13268. } catch (err) {
  13269. showToast('Error', err.message, 'error');
  13270. }
  13271. }
  13272. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13273. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13274. let docSortDebounce = null;
  13275. const docTableObserver = new MutationObserver((mutations) => {
  13276. let needsInit = false;
  13277. for (const m of mutations) {
  13278. for (const node of m.addedNodes) {
  13279. if (node.nodeType === 1) {
  13280. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13281. needsInit = true;
  13282. break;
  13283. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13284. needsInit = true;
  13285. break;
  13286. }
  13287. }
  13288. }
  13289. if (needsInit) break;
  13290. }
  13291. if (needsInit) {
  13292. clearTimeout(docSortDebounce);
  13293. docSortDebounce = setTimeout(initTableSorting, 100);
  13294. }
  13295. });
  13296. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13297. }
  13298. // =========================================================================
  13299. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13300. // =========================================================================
  13301. const bwtestState = {
  13302. running: false,
  13303. pollTimer: null,
  13304. eventSource: null,
  13305. chartPoints: [],
  13306. maxChartPoints: 60,
  13307. serverConfig: null,
  13308. peakTx: 0,
  13309. peakRx: 0,
  13310. targetDuration: 10,
  13311. lastSampleIndex: 0
  13312. };
  13313. async function loadBwTestView() {
  13314. fetchBwTestServerStatus();
  13315. loadBwTestHistory();
  13316. resizeBwTestCanvas();
  13317. checkActiveBwTest();
  13318. }
  13319. async function fetchBwTestServerStatus() {
  13320. try {
  13321. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13322. if (!res.ok) return;
  13323. const s = await res.json();
  13324. bwtestState.serverConfig = s;
  13325. // Update indicator and badges
  13326. const indicator = document.getElementById('bwtest-server-indicator');
  13327. const badge = document.getElementById('bwtest-server-badge');
  13328. const sideBadge = document.getElementById('badge-bwtest-server');
  13329. if (s.enabled && s.running) {
  13330. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13331. if (badge) {
  13332. badge.innerText = `Port ${s.port} (Active)`;
  13333. badge.className = 'text-emerald-400 font-bold';
  13334. }
  13335. if (sideBadge) {
  13336. sideBadge.innerText = s.port;
  13337. 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';
  13338. }
  13339. } else {
  13340. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13341. if (badge) {
  13342. badge.innerText = `Disabled`;
  13343. badge.className = 'text-slate-500 font-bold';
  13344. }
  13345. if (sideBadge) {
  13346. sideBadge.innerText = 'Off';
  13347. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13348. }
  13349. }
  13350. // Modal fields
  13351. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13352. if (toggle) toggle.checked = !!s.enabled;
  13353. const portInp = document.getElementById('bwtest-server-port-input');
  13354. if (portInp) portInp.value = s.port || 2000;
  13355. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13356. if (actSess) actSess.innerText = s.active_sessions || 0;
  13357. const totServ = document.getElementById('bwtest-modal-total-served');
  13358. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13359. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13360. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13361. } catch (err) {
  13362. console.error('Failed to fetch BwTest server status:', err);
  13363. }
  13364. }
  13365. function openBwTestServerModal() {
  13366. fetchBwTestServerStatus();
  13367. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13368. }
  13369. function closeBwTestServerModal() {
  13370. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13371. }
  13372. async function submitBwTestServerSettings(e) {
  13373. e.preventDefault();
  13374. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13375. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13376. try {
  13377. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13378. method: 'POST',
  13379. headers: { 'Content-Type': 'application/json' },
  13380. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13381. });
  13382. if (!res.ok) {
  13383. const err = await res.json();
  13384. throw new Error(err.error || 'Failed to update server configuration');
  13385. }
  13386. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13387. closeBwTestServerModal();
  13388. fetchBwTestServerStatus();
  13389. } catch (err) {
  13390. showToast('Server Configuration Error', err.message, 'error');
  13391. }
  13392. }
  13393. function setBwTestTarget(target) {
  13394. const inp = document.getElementById('bwtest-input-target');
  13395. if (inp) inp.value = target;
  13396. }
  13397. function setBwTestProtocol(proto) {
  13398. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13399. if (hiddenInp) hiddenInp.value = proto;
  13400. const btnUdp = document.getElementById('bwtest-proto-udp');
  13401. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13402. const badge = document.getElementById('bwtest-proto-badge');
  13403. const pktField = document.getElementById('bwtest-field-pktsize');
  13404. 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';
  13405. 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';
  13406. 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';
  13407. if (proto === 'udp') {
  13408. if (btnUdp) {
  13409. btnUdp.className = activeUdpCls;
  13410. const dot = btnUdp.querySelector('span');
  13411. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13412. }
  13413. if (btnTcp) {
  13414. btnTcp.className = inactiveCls;
  13415. const dot = btnTcp.querySelector('span');
  13416. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13417. }
  13418. if (badge) {
  13419. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13420. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13421. }
  13422. if (pktField) pktField.classList.remove('opacity-40');
  13423. } else {
  13424. if (btnUdp) {
  13425. btnUdp.className = inactiveCls;
  13426. const dot = btnUdp.querySelector('span');
  13427. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13428. }
  13429. if (btnTcp) {
  13430. btnTcp.className = activeTcpCls;
  13431. const dot = btnTcp.querySelector('span');
  13432. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13433. }
  13434. if (badge) {
  13435. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13436. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13437. }
  13438. if (pktField) pktField.classList.add('opacity-40');
  13439. }
  13440. }
  13441. function setBwTestDirection(dir) {
  13442. const hiddenInp = document.getElementById('bwtest-input-direction');
  13443. if (hiddenInp) hiddenInp.value = dir;
  13444. const btnBoth = document.getElementById('bwtest-dir-both');
  13445. const btnTx = document.getElementById('bwtest-dir-tx');
  13446. const btnRx = document.getElementById('bwtest-dir-rx');
  13447. 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';
  13448. 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';
  13449. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13450. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13451. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13452. }
  13453. function setBwTestLimit(bps) {
  13454. const sel = document.getElementById('bwtest-input-limit');
  13455. if (sel) sel.value = String(bps);
  13456. }
  13457. async function checkActiveBwTest() {
  13458. try {
  13459. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13460. if (!res.ok) return;
  13461. const st = await res.json();
  13462. if (st.running) {
  13463. setBwTestRunningUI(true);
  13464. if (st.current_sample) handleBwTestSample(st.current_sample);
  13465. startBwTestTelemetry();
  13466. }
  13467. } catch (err) {
  13468. console.error('Failed to check active BwTest:', err);
  13469. }
  13470. }
  13471. async function startBwTest(e) {
  13472. if (e && e.preventDefault) e.preventDefault();
  13473. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13474. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13475. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13476. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13477. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13478. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13479. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13480. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13481. bwtestState.targetDuration = duration;
  13482. bwtestState.chartPoints = [];
  13483. bwtestState.peakTx = 0;
  13484. bwtestState.peakRx = 0;
  13485. bwtestState.lastSampleIndex = 0;
  13486. // Clear UI elements
  13487. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13488. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13489. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13490. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13491. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13492. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13493. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13494. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13495. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13496. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13497. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13498. const tbody = document.getElementById('bwtest-samples-tbody');
  13499. if (tbody) tbody.innerHTML = '';
  13500. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13501. setBwTestRunningUI(true);
  13502. try {
  13503. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13504. method: 'POST',
  13505. headers: { 'Content-Type': 'application/json' },
  13506. body: JSON.stringify({
  13507. target,
  13508. port,
  13509. direction,
  13510. protocol,
  13511. bandwidth_limit,
  13512. packet_size,
  13513. streams,
  13514. duration
  13515. })
  13516. });
  13517. if (!res.ok) {
  13518. const err = await res.json();
  13519. throw new Error(err.error || 'Failed to start bandwidth test');
  13520. }
  13521. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13522. startBwTestTelemetry();
  13523. } catch (err) {
  13524. setBwTestRunningUI(false);
  13525. showToast('Start Failed', err.message, 'error');
  13526. }
  13527. }
  13528. function setBwTestRunningUI(running) {
  13529. bwtestState.running = running;
  13530. const startBtn = document.getElementById('bwtest-btn-start');
  13531. const stopBtn = document.getElementById('bwtest-btn-stop');
  13532. const badge = document.getElementById('bwtest-run-status-badge');
  13533. const ph = document.getElementById('bwtest-chart-placeholder');
  13534. if (running) {
  13535. if (startBtn) {
  13536. startBtn.disabled = true;
  13537. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13538. }
  13539. if (stopBtn) {
  13540. stopBtn.disabled = false;
  13541. stopBtn.classList.remove('opacity-40');
  13542. }
  13543. if (badge) {
  13544. badge.innerText = 'TESTING...';
  13545. 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';
  13546. }
  13547. if (ph) ph.style.display = 'none';
  13548. } else {
  13549. if (startBtn) {
  13550. startBtn.disabled = false;
  13551. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13552. }
  13553. if (stopBtn) {
  13554. stopBtn.disabled = true;
  13555. stopBtn.classList.add('opacity-40');
  13556. }
  13557. if (badge) {
  13558. badge.innerText = 'IDLE';
  13559. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13560. }
  13561. }
  13562. }
  13563. async function stopBwTest() {
  13564. try {
  13565. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13566. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13567. } catch (err) {
  13568. console.error('Failed to stop test:', err);
  13569. }
  13570. }
  13571. function startBwTestTelemetry() {
  13572. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13573. bwtestState.pollTimer = setInterval(async () => {
  13574. try {
  13575. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13576. if (!res.ok) return;
  13577. const st = await res.json();
  13578. if (st.recent_samples && st.recent_samples.length > 0) {
  13579. // Process new samples
  13580. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13581. newSamples.forEach(s => handleBwTestSample(s));
  13582. bwtestState.lastSampleIndex = st.recent_samples.length;
  13583. }
  13584. if (!st.running) {
  13585. clearInterval(bwtestState.pollTimer);
  13586. bwtestState.pollTimer = null;
  13587. setBwTestRunningUI(false);
  13588. handleBwTestFinish(st.summary, st.error);
  13589. }
  13590. } catch (err) {
  13591. console.error('BwTest polling error:', err);
  13592. }
  13593. }, 400);
  13594. }
  13595. function handleBwTestSample(s) {
  13596. if (!s) return;
  13597. const txMbps = s.tx_mbps || 0;
  13598. const rxMbps = s.rx_mbps || 0;
  13599. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13600. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13601. // KPI updates
  13602. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13603. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13604. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13605. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13606. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13607. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13608. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13609. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13610. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13611. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13612. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13613. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13614. const elLoss = document.getElementById('bwtest-stat-loss');
  13615. if (elLoss) {
  13616. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13617. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13618. }
  13619. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13620. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13621. const elJitter = document.getElementById('bwtest-stat-jitter');
  13622. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13623. const elTime = document.getElementById('bwtest-stat-time');
  13624. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13625. const elData = document.getElementById('bwtest-stat-data');
  13626. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13627. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13628. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13629. // Append point to chart buffer
  13630. bwtestState.chartPoints.push({
  13631. elapsed: s.elapsed_sec || 0,
  13632. tx: txMbps,
  13633. rx: rxMbps
  13634. });
  13635. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13636. bwtestState.chartPoints.shift();
  13637. }
  13638. drawBwTestChart();
  13639. // Add row to breakdown table
  13640. const tbody = document.getElementById('bwtest-samples-tbody');
  13641. if (tbody) {
  13642. const tr = document.createElement('tr');
  13643. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13644. tr.innerHTML = `
  13645. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13646. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13647. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13648. <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>
  13649. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13650. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13651. `;
  13652. tbody.insertBefore(tr, tbody.firstChild);
  13653. const countEl = document.getElementById('bwtest-sample-count');
  13654. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13655. }
  13656. }
  13657. function handleBwTestFinish(summary, error) {
  13658. const badge = document.getElementById('bwtest-run-status-badge');
  13659. if (error) {
  13660. showToast('Benchmark Error', error, 'error');
  13661. if (badge) {
  13662. badge.innerText = 'ERROR';
  13663. 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';
  13664. }
  13665. } else if (summary) {
  13666. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13667. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13668. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13669. if (badge) {
  13670. badge.innerText = 'COMPLETED';
  13671. 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';
  13672. }
  13673. }
  13674. loadBwTestHistory();
  13675. fetchBwTestServerStatus();
  13676. }
  13677. function resizeBwTestCanvas() {
  13678. const canvas = document.getElementById('bwtest-chart');
  13679. if (!canvas || !canvas.parentElement) return;
  13680. const rect = canvas.parentElement.getBoundingClientRect();
  13681. const dpr = window.devicePixelRatio || 1;
  13682. canvas.width = rect.width * dpr;
  13683. canvas.height = rect.height * dpr;
  13684. const ctx = canvas.getContext('2d');
  13685. ctx.scale(dpr, dpr);
  13686. drawBwTestChart();
  13687. }
  13688. window.addEventListener('resize', () => {
  13689. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13690. });
  13691. function drawBwTestChart() {
  13692. const canvas = document.getElementById('bwtest-chart');
  13693. if (!canvas) return;
  13694. const ctx = canvas.getContext('2d');
  13695. const dpr = window.devicePixelRatio || 1;
  13696. const width = canvas.width / dpr;
  13697. const height = canvas.height / dpr;
  13698. ctx.clearRect(0, 0, width, height);
  13699. const points = bwtestState.chartPoints;
  13700. if (!points || points.length === 0) return;
  13701. // Determine scale ceiling
  13702. let maxRate = 10;
  13703. for (const p of points) {
  13704. if (p.tx > maxRate) maxRate = p.tx;
  13705. if (p.rx > maxRate) maxRate = p.rx;
  13706. }
  13707. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13708. const paddingLeft = 55;
  13709. const paddingBottom = 24;
  13710. const paddingTop = 12;
  13711. const paddingRight = 16;
  13712. const chartW = width - paddingLeft - paddingRight;
  13713. const chartH = height - paddingTop - paddingBottom;
  13714. // Grid Lines and Y-Axis labels
  13715. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13716. ctx.lineWidth = 1;
  13717. ctx.fillStyle = '#94a3b8';
  13718. ctx.font = '10px monospace';
  13719. ctx.textAlign = 'right';
  13720. const gridSteps = 4;
  13721. for (let i = 0; i <= gridSteps; i++) {
  13722. const val = (maxRate / gridSteps) * i;
  13723. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13724. ctx.beginPath();
  13725. ctx.moveTo(paddingLeft, y);
  13726. ctx.lineTo(width - paddingRight, y);
  13727. ctx.stroke();
  13728. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13729. }
  13730. // Draw TX Line (Cyan #22d3ee)
  13731. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13732. // Draw RX Line (Purple #a855f7)
  13733. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13734. }
  13735. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13736. if (points.length < 2) return;
  13737. const stepX = w / Math.max(points.length - 1, 1);
  13738. // Gradient area fill
  13739. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13740. grad.addColorStop(0, fillColor);
  13741. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13742. ctx.beginPath();
  13743. points.forEach((p, idx) => {
  13744. const x = left + idx * stepX;
  13745. const val = valFn(p);
  13746. const y = top + h - (val / maxVal) * h;
  13747. if (idx === 0) {
  13748. ctx.moveTo(x, y);
  13749. } else {
  13750. ctx.lineTo(x, y);
  13751. }
  13752. });
  13753. // Complete path for fill
  13754. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13755. ctx.lineTo(left, top + h);
  13756. ctx.closePath();
  13757. ctx.fillStyle = grad;
  13758. ctx.fill();
  13759. // Draw line stroke
  13760. ctx.beginPath();
  13761. ctx.lineWidth = 2.5;
  13762. ctx.strokeStyle = strokeColor;
  13763. points.forEach((p, idx) => {
  13764. const x = left + idx * stepX;
  13765. const val = valFn(p);
  13766. const y = top + h - (val / maxVal) * h;
  13767. if (idx === 0) {
  13768. ctx.moveTo(x, y);
  13769. } else {
  13770. ctx.lineTo(x, y);
  13771. }
  13772. });
  13773. ctx.stroke();
  13774. // Draw end point halo
  13775. const lastP = points[points.length - 1];
  13776. const lastX = left + (points.length - 1) * stepX;
  13777. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13778. ctx.fillStyle = strokeColor;
  13779. ctx.beginPath();
  13780. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13781. ctx.fill();
  13782. }
  13783. async function loadBwTestHistory() {
  13784. try {
  13785. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13786. if (!res.ok) return;
  13787. const list = await res.json();
  13788. renderBwTestHistory(Array.isArray(list) ? list : []);
  13789. } catch (err) {
  13790. console.error('Failed to load BwTest history:', err);
  13791. }
  13792. }
  13793. function renderBwTestHistory(list) {
  13794. const tbody = document.getElementById('bwtest-history-tbody');
  13795. if (!tbody) return;
  13796. if (list.length === 0) {
  13797. 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>`;
  13798. return;
  13799. }
  13800. tbody.innerHTML = '';
  13801. list.forEach(item => {
  13802. const s = item.summary || {};
  13803. const tr = document.createElement('tr');
  13804. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13805. const dirBadge = item.direction === 'both'
  13806. ? `<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>`
  13807. : item.direction === 'tx'
  13808. ? `<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>`
  13809. : `<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>`;
  13810. const protoBadge = item.protocol === 'tcp'
  13811. ? `<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>`
  13812. : `<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>`;
  13813. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13814. tr.innerHTML = `
  13815. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13816. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13817. <td class="py-2.5 px-4">${protoBadge}</td>
  13818. <td class="py-2.5 px-4">${dirBadge}</td>
  13819. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13820. <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>
  13821. <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>
  13822. <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>
  13823. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13824. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13825. `;
  13826. tbody.appendChild(tr);
  13827. });
  13828. }
  13829. // ======================== SETTINGS & ROUTER DNS ========================
  13830. state.settingsSubTab = 'dns';
  13831. state.dnsSettings = null;
  13832. state.dnsStaticRecords = [];
  13833. state.dnsStatus = null;
  13834. function switchSettingsSubTab(sub) {
  13835. state.settingsSubTab = sub;
  13836. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13837. const btnSys = document.getElementById('btn-settings-subtab-system');
  13838. const tabDns = document.getElementById('settings-subtab-dns');
  13839. const tabSys = document.getElementById('settings-subtab-system');
  13840. if (sub === 'dns') {
  13841. if (btnDns) {
  13842. 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';
  13843. }
  13844. if (btnSys) {
  13845. 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';
  13846. }
  13847. tabDns?.classList.remove('hidden');
  13848. tabSys?.classList.add('hidden');
  13849. loadDNSSettings();
  13850. } else {
  13851. if (btnSys) {
  13852. 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';
  13853. }
  13854. if (btnDns) {
  13855. 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';
  13856. }
  13857. tabSys?.classList.remove('hidden');
  13858. tabDns?.classList.add('hidden');
  13859. loadSystemSettings();
  13860. }
  13861. }
  13862. async function loadSettingsData(showLoading = false) {
  13863. if (state.settingsSubTab === 'system') {
  13864. await loadSystemSettings();
  13865. } else {
  13866. await loadDNSSettings();
  13867. }
  13868. }
  13869. async function loadDNSSettings() {
  13870. try {
  13871. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13872. fetch(`${API_BASE}/dns/settings`),
  13873. fetch(`${API_BASE}/dns/static`),
  13874. fetch(`${API_BASE}/dns/status`)
  13875. ]);
  13876. if (settingsRes.ok) {
  13877. state.dnsSettings = await settingsRes.json();
  13878. populateDNSSettingsForm(state.dnsSettings);
  13879. }
  13880. if (staticRes.ok) {
  13881. state.dnsStaticRecords = await staticRes.json();
  13882. renderStaticDNSList();
  13883. }
  13884. if (statusRes.ok) {
  13885. state.dnsStatus = await statusRes.json();
  13886. updateDNSStatusView(state.dnsStatus);
  13887. }
  13888. } catch (err) {
  13889. console.error('Failed to load DNS settings:', err);
  13890. }
  13891. }
  13892. function populateDNSSettingsForm(s) {
  13893. if (!s) return;
  13894. const dnsForm = document.getElementById('form-dns-settings');
  13895. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13896. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13897. if (dynamicEl) {
  13898. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13899. 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(' ');
  13900. } else {
  13901. dynamicEl.innerText = 'None';
  13902. }
  13903. }
  13904. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13905. if (isEditing) return;
  13906. const serversInput = document.getElementById('dns-servers-input');
  13907. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13908. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13909. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13910. const domainInput = document.getElementById('dns-domain-input');
  13911. if (domainInput) domainInput.value = s.domain || '';
  13912. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13913. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13914. }
  13915. function updateDNSStatusView(st) {
  13916. if (!st) return;
  13917. const preview = document.getElementById('dns-resolv-preview');
  13918. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13919. const pillText = document.getElementById('dns-live-status-text');
  13920. const pill = document.getElementById('dns-live-status-pill');
  13921. if (pill && pillText) {
  13922. if (st.service_running) {
  13923. 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';
  13924. pillText.innerText = 'DNS Service Active';
  13925. } else {
  13926. 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';
  13927. pillText.innerText = 'DNS Service Inactive';
  13928. }
  13929. }
  13930. }
  13931. function appendDNSPreset(preset) {
  13932. const input = document.getElementById('dns-servers-input');
  13933. if (!input) return;
  13934. const dnsForm = document.getElementById('form-dns-settings');
  13935. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13936. const current = input.value.trim();
  13937. if (!current) {
  13938. input.value = preset;
  13939. } else {
  13940. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13941. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13942. toAdd.forEach(ip => {
  13943. if (!existing.includes(ip)) existing.push(ip);
  13944. });
  13945. input.value = existing.join(', ');
  13946. }
  13947. }
  13948. async function saveDNSSettings(e) {
  13949. e.preventDefault();
  13950. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13951. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13952. if (servers.length === 0) {
  13953. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13954. return;
  13955. }
  13956. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13957. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13958. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13959. try {
  13960. const res = await fetch(`${API_BASE}/dns/settings`, {
  13961. method: 'POST',
  13962. headers: { 'Content-Type': 'application/json' },
  13963. body: JSON.stringify({
  13964. servers: servers,
  13965. cache_size: cacheSize,
  13966. domain: domain,
  13967. allow_remote_requests: allowRemote
  13968. })
  13969. });
  13970. const data = await res.json();
  13971. if (res.ok) {
  13972. const dnsForm = document.getElementById('form-dns-settings');
  13973. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13974. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13975. loadDNSSettings();
  13976. } else {
  13977. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13978. }
  13979. } catch (err) {
  13980. showToast('Error', err.message, 'error');
  13981. }
  13982. }
  13983. async function flushDNSCache() {
  13984. try {
  13985. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13986. if (res.ok) {
  13987. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13988. loadDNSSettings();
  13989. } else {
  13990. const err = await res.json();
  13991. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13992. }
  13993. } catch (err) {
  13994. showToast('Error', err.message, 'error');
  13995. }
  13996. }
  13997. function renderStaticDNSList() {
  13998. const tbody = document.getElementById('dns-static-tbody');
  13999. const empty = document.getElementById('dns-static-empty');
  14000. const badge = document.getElementById('dns-static-count-badge');
  14001. if (!tbody) return;
  14002. tbody.innerHTML = '';
  14003. const records = state.dnsStaticRecords || [];
  14004. if (badge) badge.innerText = `${records.length} Records`;
  14005. if (records.length === 0) {
  14006. empty?.classList.remove('hidden');
  14007. return;
  14008. }
  14009. empty?.classList.add('hidden');
  14010. records.forEach(rec => {
  14011. const tr = document.createElement('tr');
  14012. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14013. tr.innerHTML = `
  14014. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14015. <td class="py-2.5 px-4">
  14016. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14017. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14018. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14019. }">
  14020. ${rec.type || 'A'}
  14021. </span>
  14022. </td>
  14023. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14024. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14025. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14026. <td class="py-2.5 px-4">
  14027. <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'}">
  14028. ${rec.disabled ? 'Disabled' : 'Active'}
  14029. </span>
  14030. </td>
  14031. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14032. <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>
  14033. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14034. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14035. </td>
  14036. `;
  14037. tbody.appendChild(tr);
  14038. });
  14039. }
  14040. function openStaticDNSModal(id = null) {
  14041. const modal = document.getElementById('modal-static-dns');
  14042. const title = document.getElementById('modal-static-dns-title');
  14043. const form = document.getElementById('form-static-dns');
  14044. if (!modal || !form) return;
  14045. form.reset();
  14046. document.getElementById('modal-static-dns-id').value = '';
  14047. if (id) {
  14048. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14049. if (rec) {
  14050. if (title) title.innerText = 'Edit Static DNS Record';
  14051. document.getElementById('modal-static-dns-id').value = rec.id;
  14052. document.getElementById('modal-static-dns-name').value = rec.name;
  14053. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14054. document.getElementById('modal-static-dns-addr').value = rec.address;
  14055. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14056. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14057. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14058. }
  14059. } else {
  14060. if (title) title.innerText = 'Add Static DNS Record';
  14061. }
  14062. modal.classList.remove('hidden');
  14063. }
  14064. function closeStaticDNSModal() {
  14065. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14066. }
  14067. async function submitSaveStaticDNS(e) {
  14068. e.preventDefault();
  14069. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14070. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14071. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14072. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14073. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14074. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14075. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14076. if (!name || !address) {
  14077. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14078. return;
  14079. }
  14080. try {
  14081. const res = await fetch(`${API_BASE}/dns/static`, {
  14082. method: 'POST',
  14083. headers: { 'Content-Type': 'application/json' },
  14084. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14085. });
  14086. const data = await res.json();
  14087. if (res.ok) {
  14088. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14089. closeStaticDNSModal();
  14090. loadDNSSettings();
  14091. } else {
  14092. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14093. }
  14094. } catch (err) {
  14095. showToast('Error', err.message, 'error');
  14096. }
  14097. }
  14098. async function deleteStaticDNS(id) {
  14099. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14100. try {
  14101. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14102. if (res.ok) {
  14103. showToast('Deleted', 'Static DNS record deleted', 'success');
  14104. loadDNSSettings();
  14105. }
  14106. } catch (err) {
  14107. showToast('Error', err.message, 'error');
  14108. }
  14109. }
  14110. async function toggleStaticDNS(id, disabled) {
  14111. try {
  14112. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14113. method: 'POST',
  14114. headers: { 'Content-Type': 'application/json' },
  14115. body: JSON.stringify({ disabled })
  14116. });
  14117. if (res.ok) {
  14118. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14119. loadDNSSettings();
  14120. }
  14121. } catch (err) {
  14122. showToast('Error', err.message, 'error');
  14123. }
  14124. }
  14125. async function loadSystemSettings() {
  14126. try {
  14127. const sysForm = document.getElementById('form-system-settings');
  14128. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14129. const res = await fetch(`${API_BASE}/system/settings`);
  14130. if (res.ok) {
  14131. const data = await res.json();
  14132. if (!isEditing) {
  14133. const hostInput = document.getElementById('system-hostname-input');
  14134. if (hostInput) hostInput.value = data.hostname || '';
  14135. const tzInput = document.getElementById('system-timezone-input');
  14136. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14137. }
  14138. }
  14139. } catch (err) {
  14140. console.error('Failed to load system settings:', err);
  14141. }
  14142. }
  14143. async function saveSystemSettings(e) {
  14144. e.preventDefault();
  14145. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14146. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14147. try {
  14148. const res = await fetch(`${API_BASE}/system/settings`, {
  14149. method: 'POST',
  14150. headers: { 'Content-Type': 'application/json' },
  14151. body: JSON.stringify({ hostname, timezone })
  14152. });
  14153. const data = await res.json();
  14154. if (res.ok) {
  14155. const sysForm = document.getElementById('form-system-settings');
  14156. if (sysForm) sysForm.dataset.dirty = 'false';
  14157. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14158. const sideH = document.getElementById('side-hostname');
  14159. if (sideH) sideH.innerText = data.hostname;
  14160. } else {
  14161. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14162. }
  14163. } catch (err) {
  14164. showToast('Error', err.message, 'error');
  14165. }
  14166. }