app.js 425 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163
  1. // Proxmox RouterOS 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. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. 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';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. 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';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (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')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <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>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <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>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <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">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <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">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <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>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <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>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. 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');
  648. 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>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. 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'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. 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>`;
  675. }
  676. 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>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. 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">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. 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">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <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">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. 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">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <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>
  716. <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">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. 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';
  755. 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>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. 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'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. 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>`;
  781. }
  782. 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>`;
  783. })()}
  784. <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>
  785. <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>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <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">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. 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'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <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>
  855. <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>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. 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>`;
  884. }
  885. if (disabled) {
  886. 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>`;
  887. }
  888. 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>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPPoE Multi-Instance ========================
  898. async function loadPPPoE(populateInputs = true) {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  901. const list = await res.json();
  902. state.pppoeList = Array.isArray(list) ? list : [];
  903. const badge = document.getElementById('pppoe-count-badge');
  904. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  905. const tbody = document.getElementById('pppoe-table-body');
  906. const empty = document.getElementById('pppoe-empty');
  907. if (!tbody) return;
  908. tbody.innerHTML = '';
  909. if (state.pppoeList.length === 0) {
  910. if (empty) empty.classList.remove('hidden');
  911. } else {
  912. if (empty) empty.classList.add('hidden');
  913. state.pppoeList.forEach(inst => {
  914. const tr = document.createElement('tr');
  915. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  916. tr.innerHTML = `
  917. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  918. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  919. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  920. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  921. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  922. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  923. <td class="py-2.5 px-3 text-center">
  924. <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'}">
  925. ${inst.default_route ? 'Yes' : 'No'}
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  929. ${inst.running ? `
  930. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  931. ` : `
  932. <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>
  933. `}
  934. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  935. ${inst.disabled ? 'Enable' : 'Disable'}
  936. </button>
  937. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  938. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  939. </td>
  940. `;
  941. tbody.appendChild(tr);
  942. });
  943. }
  944. } catch (err) {
  945. console.error('Failed to load PPPoE:', err);
  946. }
  947. }
  948. function openAddPPPoEModal() {
  949. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  950. document.getElementById('pppoe-modal-edit-orig').value = '';
  951. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  952. document.getElementById('pppoe-modal-name').readOnly = false;
  953. document.getElementById('pppoe-modal-user').value = '';
  954. document.getElementById('pppoe-modal-pass').value = '';
  955. document.getElementById('pppoe-modal-service').value = '';
  956. document.getElementById('pppoe-modal-mtu').value = '1492';
  957. document.getElementById('pppoe-modal-defroute').checked = true;
  958. document.getElementById('pppoe-modal-reconnect').checked = true;
  959. document.getElementById('pppoe-modal-disabled').checked = false;
  960. // Populate interfaces
  961. const sel = document.getElementById('pppoe-modal-iface');
  962. sel.innerHTML = '';
  963. (state.interfaces || []).forEach(i => {
  964. if (i.name === 'lo') return;
  965. const opt = document.createElement('option');
  966. opt.value = i.name;
  967. opt.innerText = `${i.name} (${i.role || i.type})`;
  968. sel.appendChild(opt);
  969. });
  970. document.getElementById('pppoe-modal').classList.remove('hidden');
  971. }
  972. function openEditPPPoEModal(name) {
  973. const inst = (state.pppoeList || []).find(i => i.name === name);
  974. if (!inst) return;
  975. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  976. document.getElementById('pppoe-modal-edit-orig').value = name;
  977. document.getElementById('pppoe-modal-name').value = inst.name;
  978. document.getElementById('pppoe-modal-name').readOnly = true;
  979. document.getElementById('pppoe-modal-user').value = inst.username || '';
  980. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  981. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  982. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  983. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  984. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  985. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  986. const sel = document.getElementById('pppoe-modal-iface');
  987. sel.innerHTML = '';
  988. (state.interfaces || []).forEach(i => {
  989. if (i.name === 'lo') return;
  990. const opt = document.createElement('option');
  991. opt.value = i.name;
  992. opt.innerText = `${i.name} (${i.role || i.type})`;
  993. if (i.name === inst.interface) opt.selected = true;
  994. sel.appendChild(opt);
  995. });
  996. document.getElementById('pppoe-modal').classList.remove('hidden');
  997. }
  998. function closePPPoEModal() {
  999. document.getElementById('pppoe-modal').classList.add('hidden');
  1000. }
  1001. async function submitSavePPPoE(e) {
  1002. e.preventDefault();
  1003. const name = document.getElementById('pppoe-modal-name').value.trim();
  1004. const iface = document.getElementById('pppoe-modal-iface').value;
  1005. const user = document.getElementById('pppoe-modal-user').value.trim();
  1006. const pass = document.getElementById('pppoe-modal-pass').value;
  1007. const service = document.getElementById('pppoe-modal-service').value.trim();
  1008. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1009. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1010. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1011. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1012. try {
  1013. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({
  1017. name,
  1018. interface: iface,
  1019. username: user,
  1020. password: pass,
  1021. service_name: service,
  1022. mtu,
  1023. default_route: defRoute,
  1024. auto_reconnect: reconnect,
  1025. disabled
  1026. })
  1027. });
  1028. if (res.ok) {
  1029. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1030. closePPPoEModal();
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. } else {
  1034. const err = await res.json();
  1035. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. async function connectPPPoEInstance(name) {
  1042. try {
  1043. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1044. if (res.ok) {
  1045. showToast('Connecting', `Dialing ${name}...`, 'info');
  1046. setTimeout(() => loadPPPoE(false), 2000);
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', err.message, 'error');
  1050. }
  1051. }
  1052. async function disconnectPPPoEInstance(name) {
  1053. try {
  1054. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1055. if (res.ok) {
  1056. showToast('Disconnected', `${name} session terminated`, 'info');
  1057. setTimeout(() => loadPPPoE(false), 1000);
  1058. }
  1059. } catch (err) {
  1060. showToast('Error', err.message, 'error');
  1061. }
  1062. }
  1063. async function togglePPPoEState(name, enable) {
  1064. try {
  1065. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1066. method: 'POST',
  1067. headers: { 'Content-Type': 'application/json' },
  1068. body: JSON.stringify({ enabled: enable })
  1069. });
  1070. if (res.ok) {
  1071. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1072. loadPPPoE(false);
  1073. }
  1074. } catch (err) {
  1075. showToast('Error', err.message, 'error');
  1076. }
  1077. }
  1078. async function deletePPPoEInstance(name) {
  1079. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1080. try {
  1081. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1082. if (res.ok) {
  1083. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1084. loadPPPoE(false);
  1085. fetchData(false);
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1092. state.wgSubTab = 'ifaces';
  1093. function switchWGSubTab(tab) {
  1094. state.wgSubTab = tab;
  1095. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1096. const peersPanel = document.getElementById('wg-subtab-peers');
  1097. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1098. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1099. if (tab === 'ifaces') {
  1100. ifacesPanel?.classList.remove('hidden');
  1101. peersPanel?.classList.add('hidden');
  1102. 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';
  1103. 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';
  1104. } else {
  1105. ifacesPanel?.classList.add('hidden');
  1106. peersPanel?.classList.remove('hidden');
  1107. 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';
  1108. 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';
  1109. renderWGPeers();
  1110. }
  1111. }
  1112. async function loadWireGuard(populateInputs = true) {
  1113. try {
  1114. const [ifacesRes, peersRes] = await Promise.all([
  1115. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1116. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1117. ]);
  1118. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1119. const peers = peersRes.ok ? await peersRes.json() : [];
  1120. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1121. state.wgPeers = Array.isArray(peers) ? peers : [];
  1122. // Badges
  1123. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1124. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1125. const peersCountBadge = document.getElementById('wg-peers-count');
  1126. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1127. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1128. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1129. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1130. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1131. // Render Interfaces
  1132. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1133. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1134. if (ifacesTbody) {
  1135. ifacesTbody.innerHTML = '';
  1136. if (state.wgInterfaces.length === 0) {
  1137. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1138. } else {
  1139. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1140. state.wgInterfaces.forEach(iface => {
  1141. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1142. const tr = document.createElement('tr');
  1143. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1144. tr.innerHTML = `
  1145. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1146. <td class="py-2.5 px-3">
  1147. <div class="flex items-center gap-1.5">
  1148. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1149. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1150. </div>
  1151. </td>
  1152. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1153. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1154. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1155. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1156. ${(iface.public_key || '').substring(0, 10)}... 📋
  1157. </span>
  1158. </td>
  1159. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1160. <td class="py-2.5 px-3 text-center">
  1161. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1162. </td>
  1163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1164. ${iface.running ? `
  1165. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1166. ` : `
  1167. <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>
  1168. `}
  1169. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1170. ${iface.disabled ? 'Enable' : 'Disable'}
  1171. </button>
  1172. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1173. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1174. </td>
  1175. `;
  1176. ifacesTbody.appendChild(tr);
  1177. });
  1178. }
  1179. }
  1180. // Populate filter dropdown in peers tab
  1181. const filterSel = document.getElementById('wg-peers-filter-iface');
  1182. if (filterSel) {
  1183. const currentVal = filterSel.value;
  1184. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1185. state.wgInterfaces.forEach(i => {
  1186. const opt = document.createElement('option');
  1187. opt.value = i.name;
  1188. opt.innerText = i.name;
  1189. if (i.name === currentVal) opt.selected = true;
  1190. filterSel.appendChild(opt);
  1191. });
  1192. }
  1193. renderWGPeers();
  1194. } catch (err) {
  1195. console.error('Failed to load WireGuard:', err);
  1196. }
  1197. }
  1198. function renderWGPeers() {
  1199. const filterSel = document.getElementById('wg-peers-filter-iface');
  1200. const selectedIface = filterSel ? filterSel.value : '';
  1201. const tbody = document.getElementById('wg-peers-table-body');
  1202. const empty = document.getElementById('wg-peers-empty');
  1203. if (!tbody) return;
  1204. tbody.innerHTML = '';
  1205. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1206. if (filtered.length === 0) {
  1207. if (empty) empty.classList.remove('hidden');
  1208. } else {
  1209. if (empty) empty.classList.add('hidden');
  1210. filtered.forEach(p => {
  1211. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1212. const tr = document.createElement('tr');
  1213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1214. tr.innerHTML = `
  1215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1216. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1217. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1218. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1219. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1220. ${(p.public_key || '').substring(0, 10)}... 📋
  1221. </span>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1224. <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '--'}</td>
  1225. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1226. <td class="py-2.5 px-3 font-mono text-[11px]">
  1227. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1228. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1231. <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">
  1232. ${p.disabled ? 'Enable' : 'Disable'}
  1233. </button>
  1234. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1235. <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>
  1236. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. }
  1243. function openAddWGInterfaceModal() {
  1244. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1245. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1246. const nameEl = document.getElementById('wg-iface-modal-name');
  1247. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1248. nameEl.readOnly = false;
  1249. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1250. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1251. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1252. document.getElementById('wg-iface-modal-comment').value = '';
  1253. document.getElementById('wg-iface-modal-pubkey').value = '';
  1254. document.getElementById('wg-iface-modal-privkey').value = '';
  1255. document.getElementById('wg-iface-modal-disabled').checked = false;
  1256. generateWGInterfaceKeys();
  1257. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1258. }
  1259. function openEditWGInterfaceModal(name) {
  1260. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1261. if (!iface) return;
  1262. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1263. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1264. const nameEl = document.getElementById('wg-iface-modal-name');
  1265. nameEl.value = iface.name;
  1266. nameEl.readOnly = false; // ALLOW RENAMING
  1267. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1268. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1269. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1270. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1271. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1272. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1273. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1274. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddWGInterfaceModal() {
  1277. document.getElementById('wg-iface-modal').classList.add('hidden');
  1278. }
  1279. async function generateWGInterfaceKeys() {
  1280. try {
  1281. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1282. const keys = await res.json();
  1283. if (res.ok) {
  1284. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1285. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1286. }
  1287. } catch (err) {
  1288. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1289. }
  1290. }
  1291. async function onWGInterfacePrivKeyInput() {
  1292. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1293. if (!privKey) return;
  1294. try {
  1295. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1296. method: 'POST',
  1297. headers: { 'Content-Type': 'application/json' },
  1298. body: JSON.stringify({ private_key: privKey })
  1299. });
  1300. if (res.ok) {
  1301. const data = await res.json();
  1302. if (data.public_key) {
  1303. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1304. }
  1305. }
  1306. } catch (err) {
  1307. // Ignore while typing
  1308. }
  1309. }
  1310. function toggleWGPrivKeyVisibility() {
  1311. const el = document.getElementById('wg-iface-modal-privkey');
  1312. const btn = document.getElementById('btn-toggle-wg-privkey');
  1313. if (el.type === 'password') {
  1314. el.type = 'text';
  1315. btn.innerText = '🙈 Hide';
  1316. } else {
  1317. el.type = 'password';
  1318. btn.innerText = '👁️ Show';
  1319. }
  1320. }
  1321. function copyWGInterfacePubKey() {
  1322. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1323. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1324. }
  1325. async function submitSaveWGInterface(e) {
  1326. e.preventDefault();
  1327. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1328. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1329. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1330. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1331. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1332. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1333. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1334. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1335. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1336. try {
  1337. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1338. method: 'POST',
  1339. headers: { 'Content-Type': 'application/json' },
  1340. body: JSON.stringify({
  1341. orig_name: origName,
  1342. name,
  1343. listen_port: port,
  1344. address: addr,
  1345. mtu,
  1346. comment,
  1347. public_key: pub,
  1348. private_key: priv,
  1349. disabled
  1350. })
  1351. });
  1352. const data = await res.json();
  1353. if (res.ok) {
  1354. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1355. closeAddWGInterfaceModal();
  1356. loadWireGuard(false);
  1357. fetchData(false);
  1358. } else {
  1359. showToast('Error', data.error || 'Failed to save interface', 'error');
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. async function startWGInterface(name) {
  1366. try {
  1367. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1368. if (res.ok) {
  1369. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1370. loadWireGuard(false);
  1371. fetchData(false);
  1372. }
  1373. } catch (err) {
  1374. showToast('Error', err.message, 'error');
  1375. }
  1376. }
  1377. async function stopWGInterface(name) {
  1378. try {
  1379. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1380. if (res.ok) {
  1381. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1382. loadWireGuard(false);
  1383. fetchData(false);
  1384. }
  1385. } catch (err) {
  1386. showToast('Error', err.message, 'error');
  1387. }
  1388. }
  1389. async function toggleWGInterfaceState(name, enable) {
  1390. try {
  1391. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1392. method: 'POST',
  1393. headers: { 'Content-Type': 'application/json' },
  1394. body: JSON.stringify({ enabled: enable })
  1395. });
  1396. if (res.ok) {
  1397. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1398. loadWireGuard(false);
  1399. fetchData(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function deleteWGInterface(name) {
  1406. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1409. if (res.ok) {
  1410. showToast('Deleted', `Interface ${name} removed`, 'success');
  1411. loadWireGuard(false);
  1412. fetchData(false);
  1413. }
  1414. } catch (err) {
  1415. showToast('Error', err.message, 'error');
  1416. }
  1417. }
  1418. function populateWGPeerIfaceSelect(selectedIface = '') {
  1419. const sel = document.getElementById('wg-peer-modal-iface');
  1420. if (!sel) return;
  1421. sel.innerHTML = '';
  1422. (state.wgInterfaces || []).forEach(i => {
  1423. const opt = document.createElement('option');
  1424. opt.value = i.name;
  1425. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1426. if (i.name === selectedIface) opt.selected = true;
  1427. sel.appendChild(opt);
  1428. });
  1429. }
  1430. function openAddWGPeerModal() {
  1431. if ((state.wgInterfaces || []).length === 0) {
  1432. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1433. openAddWGInterfaceModal();
  1434. return;
  1435. }
  1436. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1437. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1438. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1439. populateWGPeerIfaceSelect();
  1440. document.getElementById('wg-peer-modal-name').value = '';
  1441. document.getElementById('wg-peer-modal-pubkey').value = '';
  1442. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1443. document.getElementById('wg-peer-modal-endpoint').value = '';
  1444. document.getElementById('wg-peer-modal-port').value = '';
  1445. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1446. document.getElementById('wg-peer-modal-preshared').value = '';
  1447. document.getElementById('wg-peer-modal-disabled').checked = false;
  1448. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1449. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1450. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1451. }
  1452. function openEditWGPeerModal(ifaceName, pubKey) {
  1453. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1454. if (!peer) {
  1455. showToast('Not Found', 'Peer not found', 'warning');
  1456. return;
  1457. }
  1458. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1459. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1460. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1461. populateWGPeerIfaceSelect(peer.interface);
  1462. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1463. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1464. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1465. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1466. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1467. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1468. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1469. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1470. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1471. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1472. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1473. }
  1474. function closeAddWGPeerModal() {
  1475. document.getElementById('wg-peer-modal').classList.add('hidden');
  1476. }
  1477. async function generatePeerKeypairHelper() {
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1480. const keys = await res.json();
  1481. if (res.ok) {
  1482. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1483. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1484. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1485. checkWGPeerKeyValidity();
  1486. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1487. }
  1488. } catch (err) {
  1489. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1490. }
  1491. }
  1492. function copyGeneratedPeerPrivKey() {
  1493. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1494. if (priv) copyToClipboard(priv, 'Client Private Key');
  1495. }
  1496. async function generatePeerPSK() {
  1497. try {
  1498. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1499. const keys = await res.json();
  1500. if (res.ok && keys.private_key) {
  1501. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1502. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1503. }
  1504. } catch (err) {
  1505. showToast('Error', err.message, 'error');
  1506. }
  1507. }
  1508. function checkWGPeerKeyValidity() {
  1509. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1510. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1511. const warningEl = document.getElementById('wg-peer-key-warning');
  1512. if (!warningEl) return;
  1513. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1514. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1515. warningEl.classList.remove('hidden');
  1516. } else {
  1517. warningEl.classList.add('hidden');
  1518. }
  1519. }
  1520. async function submitSaveWGPeer(e) {
  1521. e.preventDefault();
  1522. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1523. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1524. const iface = document.getElementById('wg-peer-modal-iface').value;
  1525. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1526. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1527. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1528. .split(',')
  1529. .map(s => s.trim())
  1530. .filter(s => s.length > 0);
  1531. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1532. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1533. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1534. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1535. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1536. // Validation
  1537. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1538. if (targetIface && targetIface.public_key === pub) {
  1539. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1540. return;
  1541. }
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({
  1547. orig_interface: origIface,
  1548. orig_public_key: origPubKey,
  1549. interface: iface,
  1550. name,
  1551. public_key: pub,
  1552. allowed_ips: allowed,
  1553. endpoint_address: epHost,
  1554. endpoint_port: epPort,
  1555. persistent_keepalive: keepalive,
  1556. preshared_key: psk,
  1557. disabled
  1558. })
  1559. });
  1560. const data = await res.json();
  1561. if (res.ok) {
  1562. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1563. closeAddWGPeerModal();
  1564. loadWireGuard(false);
  1565. } else {
  1566. showToast('Error', data.error || 'Failed to save peer', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. async function toggleWGPeerState(iface, pubkey, enable) {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1575. method: 'POST',
  1576. headers: { 'Content-Type': 'application/json' },
  1577. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1578. });
  1579. const data = await res.json();
  1580. if (res.ok) {
  1581. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1582. loadWireGuard(false);
  1583. } else {
  1584. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. async function deleteWGPeer(iface, pubkey) {
  1591. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1597. });
  1598. const data = await res.json();
  1599. if (res.ok) {
  1600. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1601. loadWireGuard(false);
  1602. } else {
  1603. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. // ======================== IPSec Multi-Tunnel ========================
  1610. async function loadIPSec(populateInputs = true) {
  1611. try {
  1612. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1613. const list = await res.json();
  1614. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1615. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1616. const badge = document.getElementById('ipsec-sas-badge');
  1617. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1618. const tbody = document.getElementById('ipsec-table-body');
  1619. const empty = document.getElementById('ipsec-empty');
  1620. if (!tbody) return;
  1621. tbody.innerHTML = '';
  1622. if (state.ipsecTunnels.length === 0) {
  1623. if (empty) empty.classList.remove('hidden');
  1624. } else {
  1625. if (empty) empty.classList.add('hidden');
  1626. state.ipsecTunnels.forEach(c => {
  1627. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1628. const tr = document.createElement('tr');
  1629. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1630. tr.innerHTML = `
  1631. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1632. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1633. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1635. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1636. <td class="py-2.5 px-4 font-sans">
  1637. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1638. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1639. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1640. </td>
  1641. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1642. ${isEstablished ? `
  1643. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1644. ` : `
  1645. <button onclick="startIPSecTunnel('${c.name}')" class="text-xs bg-amber-600/30 hover:bg-amber-600/50 text-amber-300 px-2 py-0.5 rounded border border-amber-500/30">Initiate</button>
  1646. `}
  1647. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1648. ${c.disabled ? 'Enable' : 'Disable'}
  1649. </button>
  1650. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1651. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1652. </td>
  1653. `;
  1654. tbody.appendChild(tr);
  1655. });
  1656. }
  1657. } catch (err) {
  1658. console.error('Failed to load IPSec:', err);
  1659. }
  1660. }
  1661. function openAddIPSecModal() {
  1662. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1663. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1664. document.getElementById('ipsec-modal-name').readOnly = false;
  1665. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1666. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1667. document.getElementById('ipsec-modal-remotegw').value = '';
  1668. document.getElementById('ipsec-modal-psk').value = '';
  1669. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1670. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1671. document.getElementById('ipsec-modal-autostart').checked = true;
  1672. document.getElementById('ipsec-modal-disabled').checked = false;
  1673. document.getElementById('ipsec-modal').classList.remove('hidden');
  1674. }
  1675. function openEditIPSecModal(name) {
  1676. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1677. if (!conn) return;
  1678. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1679. document.getElementById('ipsec-modal-name').value = conn.name;
  1680. document.getElementById('ipsec-modal-name').readOnly = true;
  1681. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1682. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1683. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1684. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1685. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1686. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1687. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1688. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1689. document.getElementById('ipsec-modal').classList.remove('hidden');
  1690. }
  1691. function closeAddIPSecModal() {
  1692. document.getElementById('ipsec-modal').classList.add('hidden');
  1693. }
  1694. async function submitSaveIPSec(e) {
  1695. e.preventDefault();
  1696. const name = document.getElementById('ipsec-modal-name').value.trim();
  1697. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1698. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1699. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1700. const psk = document.getElementById('ipsec-modal-psk').value;
  1701. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1702. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1703. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1704. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1705. try {
  1706. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1707. method: 'POST',
  1708. headers: { 'Content-Type': 'application/json' },
  1709. body: JSON.stringify({
  1710. name,
  1711. local_addrs: '%any',
  1712. remote_addrs: remotegw,
  1713. local_subnet: localts,
  1714. remote_subnet: remotets,
  1715. preshared_key: psk,
  1716. ike_proposals: ike,
  1717. esp_proposals: esp,
  1718. auto_start: autostart,
  1719. disabled
  1720. })
  1721. });
  1722. if (res.ok) {
  1723. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1724. closeAddIPSecModal();
  1725. loadIPSec(false);
  1726. fetchData(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. async function startIPSecTunnel(name) {
  1733. try {
  1734. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1735. if (res.ok) {
  1736. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1737. setTimeout(() => loadIPSec(false), 2000);
  1738. }
  1739. } catch (err) {
  1740. showToast('Error', err.message, 'error');
  1741. }
  1742. }
  1743. async function stopIPSecTunnel(name) {
  1744. try {
  1745. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1746. if (res.ok) {
  1747. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1748. loadIPSec(false);
  1749. }
  1750. } catch (err) {
  1751. showToast('Error', err.message, 'error');
  1752. }
  1753. }
  1754. async function toggleIPSecState(name, enable) {
  1755. try {
  1756. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1757. method: 'POST',
  1758. headers: { 'Content-Type': 'application/json' },
  1759. body: JSON.stringify({ enabled: enable })
  1760. });
  1761. if (res.ok) {
  1762. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1763. loadIPSec(false);
  1764. }
  1765. } catch (err) {
  1766. showToast('Error', err.message, 'error');
  1767. }
  1768. }
  1769. async function deleteIPSecConn(name) {
  1770. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1771. try {
  1772. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1773. if (res.ok) {
  1774. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1775. loadIPSec(false);
  1776. fetchData(false);
  1777. }
  1778. } catch (err) {
  1779. showToast('Error', err.message, 'error');
  1780. }
  1781. }
  1782. // ======================== L2TP Multi-Instance ========================
  1783. async function loadL2TP(populateInputs = true) {
  1784. try {
  1785. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1786. const list = await res.json();
  1787. state.l2tpList = Array.isArray(list) ? list : [];
  1788. const badge = document.getElementById('l2tp-count-badge');
  1789. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1790. const tbody = document.getElementById('l2tp-table-body');
  1791. const empty = document.getElementById('l2tp-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. if (state.l2tpList.length === 0) {
  1795. if (empty) empty.classList.remove('hidden');
  1796. } else {
  1797. if (empty) empty.classList.add('hidden');
  1798. state.l2tpList.forEach(inst => {
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1804. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1806. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1807. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1808. <td class="py-2.5 px-3 text-center">
  1809. <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'}">
  1810. ${inst.default_route ? 'Yes' : 'No'}
  1811. </span>
  1812. </td>
  1813. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1814. ${inst.running ? `
  1815. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1816. ` : `
  1817. <button onclick="connectL2TPInstance('${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>
  1818. `}
  1819. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1820. ${inst.disabled ? 'Enable' : 'Disable'}
  1821. </button>
  1822. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1823. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. } catch (err) {
  1830. console.error('Failed to load L2TP:', err);
  1831. }
  1832. }
  1833. function openAddL2TPModal() {
  1834. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1835. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1836. document.getElementById('l2tp-modal-name').readOnly = false;
  1837. document.getElementById('l2tp-modal-server').value = '';
  1838. document.getElementById('l2tp-modal-user').value = '';
  1839. document.getElementById('l2tp-modal-pass').value = '';
  1840. document.getElementById('l2tp-modal-ipsec').value = '';
  1841. document.getElementById('l2tp-modal-defroute').checked = true;
  1842. document.getElementById('l2tp-modal-disabled').checked = false;
  1843. document.getElementById('l2tp-modal').classList.remove('hidden');
  1844. }
  1845. function openEditL2TPModal(name) {
  1846. const inst = (state.l2tpList || []).find(i => i.name === name);
  1847. if (!inst) return;
  1848. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1849. document.getElementById('l2tp-modal-name').value = inst.name;
  1850. document.getElementById('l2tp-modal-name').readOnly = true;
  1851. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1852. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1853. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1854. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1855. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1856. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1857. document.getElementById('l2tp-modal').classList.remove('hidden');
  1858. }
  1859. function closeL2TPModal() {
  1860. document.getElementById('l2tp-modal').classList.add('hidden');
  1861. }
  1862. async function submitSaveL2TP(e) {
  1863. e.preventDefault();
  1864. const name = document.getElementById('l2tp-modal-name').value.trim();
  1865. const server = document.getElementById('l2tp-modal-server').value.trim();
  1866. const user = document.getElementById('l2tp-modal-user').value.trim();
  1867. const pass = document.getElementById('l2tp-modal-pass').value;
  1868. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1869. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1870. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1871. try {
  1872. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1873. method: 'POST',
  1874. headers: { 'Content-Type': 'application/json' },
  1875. body: JSON.stringify({
  1876. name,
  1877. connect_to: server,
  1878. username: user,
  1879. password: pass,
  1880. ipsec_secret: ipsec,
  1881. default_route: defRoute,
  1882. disabled
  1883. })
  1884. });
  1885. if (res.ok) {
  1886. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1887. closeL2TPModal();
  1888. loadL2TP(false);
  1889. fetchData(false);
  1890. }
  1891. } catch (err) {
  1892. showToast('Error', err.message, 'error');
  1893. }
  1894. }
  1895. async function connectL2TPInstance(name) {
  1896. try {
  1897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1898. if (res.ok) {
  1899. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1900. setTimeout(() => loadL2TP(false), 2000);
  1901. }
  1902. } catch (err) {
  1903. showToast('Error', err.message, 'error');
  1904. }
  1905. }
  1906. async function disconnectL2TPInstance(name) {
  1907. try {
  1908. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1909. if (res.ok) {
  1910. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1911. loadL2TP(false);
  1912. }
  1913. } catch (err) {
  1914. showToast('Error', err.message, 'error');
  1915. }
  1916. }
  1917. async function toggleL2TPState(name, enable) {
  1918. try {
  1919. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ enabled: enable })
  1923. });
  1924. if (res.ok) {
  1925. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1926. loadL2TP(false);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. async function deleteL2TPInstance(name) {
  1933. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1934. try {
  1935. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1936. if (res.ok) {
  1937. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1938. loadL2TP(false);
  1939. fetchData(false);
  1940. }
  1941. } catch (err) {
  1942. showToast('Error', err.message, 'error');
  1943. }
  1944. }
  1945. // ======================== PPTP Multi-Instance ========================
  1946. async function loadPPTP(populateInputs = true) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1949. const list = await res.json();
  1950. state.pptpList = Array.isArray(list) ? list : [];
  1951. const badge = document.getElementById('pptp-count-badge');
  1952. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1953. const tbody = document.getElementById('pptp-table-body');
  1954. const empty = document.getElementById('pptp-empty');
  1955. if (!tbody) return;
  1956. tbody.innerHTML = '';
  1957. if (state.pptpList.length === 0) {
  1958. if (empty) empty.classList.remove('hidden');
  1959. } else {
  1960. if (empty) empty.classList.add('hidden');
  1961. state.pptpList.forEach(inst => {
  1962. const tr = document.createElement('tr');
  1963. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1964. tr.innerHTML = `
  1965. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1966. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1967. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1968. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1969. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1970. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1971. <td class="py-2.5 px-3 text-center">
  1972. <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'}">
  1973. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1977. ${inst.running ? `
  1978. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1979. ` : `
  1980. <button onclick="connectPPTPInstance('${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>
  1981. `}
  1982. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1983. ${inst.disabled ? 'Enable' : 'Disable'}
  1984. </button>
  1985. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1986. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1987. </td>
  1988. `;
  1989. tbody.appendChild(tr);
  1990. });
  1991. }
  1992. } catch (err) {
  1993. console.error('Failed to load PPTP:', err);
  1994. }
  1995. }
  1996. function openAddPPTPModal() {
  1997. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1998. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1999. document.getElementById('pptp-modal-name').readOnly = false;
  2000. document.getElementById('pptp-modal-server').value = '';
  2001. document.getElementById('pptp-modal-user').value = '';
  2002. document.getElementById('pptp-modal-pass').value = '';
  2003. document.getElementById('pptp-modal-mppe').checked = true;
  2004. document.getElementById('pptp-modal-defroute').checked = true;
  2005. document.getElementById('pptp-modal-disabled').checked = false;
  2006. document.getElementById('pptp-modal').classList.remove('hidden');
  2007. }
  2008. function openEditPPTPModal(name) {
  2009. const inst = (state.pptpList || []).find(i => i.name === name);
  2010. if (!inst) return;
  2011. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2012. document.getElementById('pptp-modal-name').value = inst.name;
  2013. document.getElementById('pptp-modal-name').readOnly = true;
  2014. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2015. document.getElementById('pptp-modal-user').value = inst.username || '';
  2016. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2017. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2018. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2019. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2020. document.getElementById('pptp-modal').classList.remove('hidden');
  2021. }
  2022. function closePPTPModal() {
  2023. document.getElementById('pptp-modal').classList.add('hidden');
  2024. }
  2025. async function submitSavePPTP(e) {
  2026. e.preventDefault();
  2027. const name = document.getElementById('pptp-modal-name').value.trim();
  2028. const server = document.getElementById('pptp-modal-server').value.trim();
  2029. const user = document.getElementById('pptp-modal-user').value.trim();
  2030. const pass = document.getElementById('pptp-modal-pass').value;
  2031. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2032. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2033. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2034. try {
  2035. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2036. method: 'POST',
  2037. headers: { 'Content-Type': 'application/json' },
  2038. body: JSON.stringify({
  2039. name,
  2040. connect_to: server,
  2041. username: user,
  2042. password: pass,
  2043. require_mppe: mppe,
  2044. default_route: defRoute,
  2045. auto_reconnect: true,
  2046. disabled
  2047. })
  2048. });
  2049. if (res.ok) {
  2050. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2051. closePPTPModal();
  2052. loadPPTP(false);
  2053. fetchData(false);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. async function connectPPTPInstance(name) {
  2060. try {
  2061. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2062. if (res.ok) {
  2063. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2064. setTimeout(() => loadPPTP(false), 2000);
  2065. }
  2066. } catch (err) {
  2067. showToast('Error', err.message, 'error');
  2068. }
  2069. }
  2070. async function disconnectPPTPInstance(name) {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2073. if (res.ok) {
  2074. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2075. loadPPTP(false);
  2076. }
  2077. } catch (err) {
  2078. showToast('Error', err.message, 'error');
  2079. }
  2080. }
  2081. async function togglePPTPState(name, enable) {
  2082. try {
  2083. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2084. method: 'POST',
  2085. headers: { 'Content-Type': 'application/json' },
  2086. body: JSON.stringify({ enabled: enable })
  2087. });
  2088. if (res.ok) {
  2089. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2090. loadPPTP(false);
  2091. }
  2092. } catch (err) {
  2093. showToast('Error', err.message, 'error');
  2094. }
  2095. }
  2096. async function deletePPTPInstance(name) {
  2097. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2098. try {
  2099. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2100. if (res.ok) {
  2101. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2102. loadPPTP(false);
  2103. fetchData(false);
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. // ---------------- Modal & Helper Functions ----------------
  2110. function openVlanModal(defaultParent = '') {
  2111. const select = document.getElementById('vlan-parent');
  2112. select.innerHTML = '';
  2113. const allIfaces = state.interfaces || [];
  2114. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2115. if (eligible.length === 0) {
  2116. const opt = document.createElement('option');
  2117. opt.value = '';
  2118. opt.innerText = 'No VLAN-capable interfaces available';
  2119. select.appendChild(opt);
  2120. } else {
  2121. eligible.forEach(i => {
  2122. const opt = document.createElement('option');
  2123. opt.value = i.name;
  2124. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2125. if (i.name === defaultParent) opt.selected = true;
  2126. select.appendChild(opt);
  2127. });
  2128. }
  2129. document.getElementById('vlan-id').value = '';
  2130. document.getElementById('vlan-name').value = '';
  2131. document.getElementById('vlan-ip').value = '';
  2132. document.getElementById('vlan-desc').value = '';
  2133. autoSuggestVlanName();
  2134. document.getElementById('vlan-modal').classList.remove('hidden');
  2135. }
  2136. function closeVlanModal() {
  2137. document.getElementById('vlan-modal').classList.add('hidden');
  2138. }
  2139. function autoSuggestVlanName() {
  2140. const parent = document.getElementById('vlan-parent').value;
  2141. if (!parent) return;
  2142. const id = document.getElementById('vlan-id').value;
  2143. const nameInput = document.getElementById('vlan-name');
  2144. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2145. }
  2146. function setSubnetPreset(cidr) {
  2147. const ipInput = document.getElementById('vlan-ip');
  2148. const id = document.getElementById('vlan-id').value || '10';
  2149. ipInput.value = `192.168.${id}.1${cidr}`;
  2150. }
  2151. async function submitCreateVlan(e) {
  2152. e.preventDefault();
  2153. const btn = document.getElementById('vlan-submit-btn');
  2154. btn.disabled = true;
  2155. btn.innerText = 'Creating...';
  2156. const parent = document.getElementById('vlan-parent').value;
  2157. if (!parent) {
  2158. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2159. btn.disabled = false;
  2160. btn.innerText = 'Create VLAN';
  2161. return;
  2162. }
  2163. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2164. const name = document.getElementById('vlan-name').value.trim();
  2165. const ip = document.getElementById('vlan-ip').value.trim();
  2166. const role = document.getElementById('vlan-role').value;
  2167. const desc = document.getElementById('vlan-desc').value.trim();
  2168. try {
  2169. const res = await fetch(`${API_BASE}/vlans`, {
  2170. method: 'POST',
  2171. headers: { 'Content-Type': 'application/json' },
  2172. body: JSON.stringify({
  2173. parent_name: parent,
  2174. vlan_id: id,
  2175. name: name,
  2176. ip_address: ip,
  2177. role: role,
  2178. description: desc,
  2179. mtu: 1500,
  2180. auto_up: true
  2181. })
  2182. });
  2183. const data = await res.json();
  2184. if (res.ok) {
  2185. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2186. state.expandedParents.add(parent);
  2187. closeVlanModal();
  2188. await fetchData(true);
  2189. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2190. } else {
  2191. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2192. }
  2193. } catch (err) {
  2194. showToast('Error', err.message, 'error');
  2195. } finally {
  2196. btn.disabled = false;
  2197. btn.innerText = 'Create VLAN';
  2198. }
  2199. }
  2200. async function confirmDeleteVlan(name) {
  2201. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2202. try {
  2203. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2204. if (res.ok) {
  2205. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2206. closeIfaceModal();
  2207. fetchData(true);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. function openIfaceModal(name) {
  2214. const iface = (state.interfaces || []).find(i => i.name === name);
  2215. if (!iface) return;
  2216. state.currentModalIface = iface.name;
  2217. document.getElementById('modal-iface-name').innerText = iface.name;
  2218. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2219. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2220. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2221. document.getElementById('modal-iface-desc').value = iface.description || '';
  2222. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2223. if (iface.is_vlan) {
  2224. delBtn.classList.remove('hidden');
  2225. } else {
  2226. delBtn.classList.add('hidden');
  2227. }
  2228. renderModalIPs(iface);
  2229. document.getElementById('iface-modal').classList.remove('hidden');
  2230. }
  2231. function renderModalIPs(iface) {
  2232. const container = document.getElementById('modal-ip-list');
  2233. container.innerHTML = '';
  2234. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2235. if (addrs.length === 0) {
  2236. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2237. return;
  2238. }
  2239. addrs.forEach(addr => {
  2240. const row = document.createElement('div');
  2241. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2242. row.innerHTML = `
  2243. <span class="text-white">${addr}</span>
  2244. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2245. `;
  2246. container.appendChild(row);
  2247. });
  2248. }
  2249. function closeIfaceModal() {
  2250. document.getElementById('iface-modal').classList.add('hidden');
  2251. state.currentModalIface = null;
  2252. }
  2253. async function setIfaceState(name, newState) {
  2254. await toggleInterfaceState(name, newState);
  2255. const updated = (state.interfaces || []).find(i => i.name === name);
  2256. if (updated) openIfaceModal(name);
  2257. }
  2258. async function applyMTU() {
  2259. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2260. try {
  2261. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2262. method: 'POST',
  2263. headers: { 'Content-Type': 'application/json' },
  2264. body: JSON.stringify({ mtu })
  2265. });
  2266. if (res.ok) {
  2267. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2268. fetchData(false);
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. async function addInterfaceIP() {
  2275. const ip = document.getElementById('modal-new-ip').value.trim();
  2276. if (!ip) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2279. method: 'POST',
  2280. headers: { 'Content-Type': 'application/json' },
  2281. body: JSON.stringify({ ip })
  2282. });
  2283. if (res.ok) {
  2284. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2285. document.getElementById('modal-new-ip').value = '';
  2286. await fetchData(false);
  2287. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2288. if (iface) renderModalIPs(iface);
  2289. } else {
  2290. const err = await res.json();
  2291. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2292. }
  2293. } catch (err) {
  2294. showToast('Error', err.message, 'error');
  2295. }
  2296. }
  2297. async function removeInterfaceIP(ip) {
  2298. if (!confirm(`Remove IP ${ip}?`)) return;
  2299. try {
  2300. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2301. method: 'DELETE',
  2302. headers: { 'Content-Type': 'application/json' },
  2303. body: JSON.stringify({ ip })
  2304. });
  2305. if (res.ok) {
  2306. showToast('IP Removed', `Removed ${ip}`, 'success');
  2307. await fetchData(false);
  2308. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2309. if (iface) renderModalIPs(iface);
  2310. }
  2311. } catch (err) {
  2312. showToast('Error', err.message, 'error');
  2313. }
  2314. }
  2315. async function saveInterfaceMetadata() {
  2316. const role = document.getElementById('modal-iface-role').value;
  2317. const desc = document.getElementById('modal-iface-desc').value.trim();
  2318. try {
  2319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2320. method: 'POST',
  2321. headers: { 'Content-Type': 'application/json' },
  2322. body: JSON.stringify({ role, description: desc })
  2323. });
  2324. if (res.ok) {
  2325. showToast('Saved', 'Metadata updated', 'success');
  2326. closeIfaceModal();
  2327. fetchData(false);
  2328. }
  2329. } catch (err) {
  2330. showToast('Error', err.message, 'error');
  2331. }
  2332. }
  2333. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2334. state.fwSubTab = 'filter';
  2335. state.routesSubTab = 'routes';
  2336. function renderRuleFlag(disabled, hasComment) {
  2337. let flags = '';
  2338. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2339. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2340. return flags || '<span class="text-slate-600">-</span>';
  2341. }
  2342. function renderActionBadge(action) {
  2343. const act = (action || '').toLowerCase();
  2344. let color = 'bg-slate-800 text-slate-300';
  2345. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2346. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2347. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2348. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2349. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2350. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2351. }
  2352. function switchFWSubTab(tab) {
  2353. state.fwSubTab = tab;
  2354. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2355. tabs.forEach(t => {
  2356. const panel = document.getElementById(`fw-subtab-${t}`);
  2357. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2358. if (panel) {
  2359. if (t === tab) panel.classList.remove('hidden');
  2360. else panel.classList.add('hidden');
  2361. }
  2362. if (btn) {
  2363. if (t === tab) {
  2364. 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';
  2365. } else {
  2366. 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';
  2367. }
  2368. }
  2369. });
  2370. const addBtn = document.getElementById('fw-primary-add-btn');
  2371. if (addBtn) {
  2372. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2373. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2374. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2375. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2376. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2377. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2378. }
  2379. if (tab === 'geo') loadGeoIP();
  2380. if (tab === 'connections') loadConnections();
  2381. setTimeout(initTableSorting, 50);
  2382. }
  2383. function openCurrentFWModal() {
  2384. if (state.fwSubTab === 'filter') openAddFilterModal();
  2385. else if (state.fwSubTab === 'nat') openAddNATModal();
  2386. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2387. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2388. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2389. else if (state.fwSubTab === 'connections') loadConnections();
  2390. }
  2391. async function loadFirewall(populateDropdowns = true) {
  2392. try {
  2393. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2394. fetch(`${API_BASE}/firewall/summary`),
  2395. fetch(`${API_BASE}/firewall/filter`),
  2396. fetch(`${API_BASE}/firewall/nat`),
  2397. fetch(`${API_BASE}/firewall/mangle`),
  2398. fetch(`${API_BASE}/firewall/address-lists`),
  2399. fetch(`${API_BASE}/firewall/geoip/status`),
  2400. fetch(`${API_BASE}/firewall/geoip/countries`)
  2401. ]);
  2402. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2403. if (filterRes.ok) state.filterRules = await filterRes.json();
  2404. if (natRes.ok) state.natRules = await natRes.json();
  2405. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2406. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2407. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2408. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2409. // Badges
  2410. const bFilter = document.getElementById('fw-badge-filter');
  2411. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2412. const bNat = document.getElementById('fw-badge-nat');
  2413. if (bNat) bNat.innerText = (state.natRules || []).length;
  2414. const bMangle = document.getElementById('fw-badge-mangle');
  2415. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2416. const bAddr = document.getElementById('fw-badge-addrlist');
  2417. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2418. const bGeo = document.getElementById('fw-badge-geo');
  2419. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2420. renderFilterRules();
  2421. renderNATRules();
  2422. renderMangleRules();
  2423. renderAddressLists();
  2424. renderGeoCountries();
  2425. if (state.fwSubTab === 'connections') {
  2426. loadConnections();
  2427. }
  2428. } catch (err) {
  2429. console.error('Failed to load firewall:', err);
  2430. }
  2431. }
  2432. // ----------------- Filter Rules -----------------
  2433. function renderFilterRules() {
  2434. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2435. const tbody = document.getElementById('filter-table-body');
  2436. const empty = document.getElementById('filter-empty');
  2437. if (!tbody) return;
  2438. tbody.innerHTML = '';
  2439. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2440. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2441. if (rules.length === 0) {
  2442. empty?.classList.remove('hidden');
  2443. return;
  2444. }
  2445. empty?.classList.add('hidden');
  2446. rules.forEach((r, idx) => {
  2447. const tr = document.createElement('tr');
  2448. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2449. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2450. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2451. let actionExtra = '';
  2452. if (r.action === 'reject') {
  2453. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2454. } else if (r.action === 'jump') {
  2455. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2456. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2457. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2458. } else if (r.action === 'log' && r.log_prefix) {
  2459. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2460. }
  2461. tr.innerHTML = `
  2462. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2463. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2464. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2465. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2466. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2467. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2468. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2469. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2470. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2471. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2472. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2473. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2474. </td>
  2475. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2476. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2477. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2478. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2479. <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>
  2480. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2481. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2482. </td>
  2483. `;
  2484. tbody.appendChild(tr);
  2485. });
  2486. }
  2487. function formatTarget(addr, list, geo) {
  2488. const parts = [];
  2489. if (addr) parts.push(`<span>${addr}</span>`);
  2490. if (list) {
  2491. const inv = list.startsWith('!') ? '!' : '';
  2492. const clean = list.replace(/^!/, '');
  2493. 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>`);
  2494. }
  2495. if (geo) {
  2496. const inv = geo.startsWith('!') ? '!' : '';
  2497. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2498. 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>`);
  2499. }
  2500. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2501. return parts.join(' ');
  2502. }
  2503. function populateInterfaceSelect(selectId, currentVal = '') {
  2504. const sel = document.getElementById(selectId);
  2505. if (!sel) return;
  2506. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2507. (state.interfaces || []).forEach(i => {
  2508. const opt = document.createElement('option');
  2509. opt.value = i.name;
  2510. opt.innerText = `${i.name} (${i.role || i.type})`;
  2511. if (i.name === currentVal) opt.selected = true;
  2512. sel.appendChild(opt);
  2513. });
  2514. }
  2515. function populateAddressListSelect(selectId, currentVal = '') {
  2516. const sel = document.getElementById(selectId);
  2517. if (!sel) return;
  2518. sel.innerHTML = '<option value="">(None)</option>';
  2519. const cleanVal = (currentVal || '').replace(/^!/, '');
  2520. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2521. customNames.forEach(name => {
  2522. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2523. const opt = document.createElement('option');
  2524. opt.value = name;
  2525. opt.innerText = `${name} (${count} entries)`;
  2526. if (name === cleanVal) opt.selected = true;
  2527. sel.appendChild(opt);
  2528. });
  2529. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2530. const opt = document.createElement('option');
  2531. opt.value = cleanVal;
  2532. opt.innerText = cleanVal;
  2533. opt.selected = true;
  2534. sel.appendChild(opt);
  2535. }
  2536. populateCommonAddrListDatalist();
  2537. }
  2538. function populateCommonAddrListDatalist() {
  2539. const dl = document.getElementById('fw-addrlist-datalist');
  2540. if (!dl) return;
  2541. dl.innerHTML = '';
  2542. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2543. names.forEach(name => {
  2544. const opt = document.createElement('option');
  2545. opt.value = name;
  2546. dl.appendChild(opt);
  2547. });
  2548. }
  2549. function populateGeoIPSelect(selectId, currentVal = '') {
  2550. const sel = document.getElementById(selectId);
  2551. if (!sel) return;
  2552. sel.innerHTML = '<option value="">(None)</option>';
  2553. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2554. // Presets optgroup
  2555. const grpPresets = document.createElement('optgroup');
  2556. grpPresets.label = '⚡ Regional Presets';
  2557. const presets = [
  2558. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2559. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2560. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2561. ];
  2562. presets.forEach(p => {
  2563. const opt = document.createElement('option');
  2564. opt.value = p.code;
  2565. opt.innerText = p.label;
  2566. if (p.code === cleanVal) opt.selected = true;
  2567. grpPresets.appendChild(opt);
  2568. });
  2569. sel.appendChild(grpPresets);
  2570. // All Countries optgroup
  2571. const grpCountries = document.createElement('optgroup');
  2572. grpCountries.label = '🌍 All Countries';
  2573. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2574. countries.forEach(c => {
  2575. const opt = document.createElement('option');
  2576. opt.value = c.code;
  2577. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2578. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2579. if (c.code === cleanVal) opt.selected = true;
  2580. grpCountries.appendChild(opt);
  2581. });
  2582. sel.appendChild(grpCountries);
  2583. }
  2584. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2585. function switchFwRuleTab(tab) {
  2586. state.activeFwRuleTab = tab;
  2587. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2588. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2589. btn.classList.add('text-slate-400', 'border-transparent');
  2590. });
  2591. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2592. if (activeBtn) {
  2593. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2594. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2595. }
  2596. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2597. const activePane = document.getElementById(`fw-pane-${tab}`);
  2598. if (activePane) activePane.classList.remove('hidden');
  2599. if (tab === 'statistics') {
  2600. startFwStatPolling();
  2601. } else {
  2602. stopFwStatPolling();
  2603. }
  2604. }
  2605. function toggleFwField(fieldKey, expand) {
  2606. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2607. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2608. if (!plusBtn || !fieldBox) return;
  2609. if (expand) {
  2610. plusBtn.classList.add('hidden');
  2611. fieldBox.classList.remove('hidden');
  2612. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2613. if (valInput) valInput.focus();
  2614. } else {
  2615. fieldBox.classList.add('hidden');
  2616. plusBtn.classList.remove('hidden');
  2617. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2618. if (valInput) {
  2619. if (valInput.tagName === 'SELECT') {
  2620. valInput.selectedIndex = 0;
  2621. } else {
  2622. valInput.value = '';
  2623. }
  2624. }
  2625. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2626. if (invInput) invInput.checked = false;
  2627. if (fieldKey === 'cs') {
  2628. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2629. const el = document.getElementById(id);
  2630. if (el) el.checked = false;
  2631. });
  2632. }
  2633. if (fieldKey === 'natstate') {
  2634. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2635. const el = document.getElementById(id);
  2636. if (el) el.checked = false;
  2637. });
  2638. }
  2639. if (fieldKey === 'days') {
  2640. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2641. const el = document.getElementById(`fw-day-${d}`);
  2642. if (el) el.checked = true;
  2643. });
  2644. }
  2645. }
  2646. }
  2647. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2648. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2649. toggleFwField(fieldKey, true);
  2650. let strVal = String(value);
  2651. if (hasInvert) {
  2652. const inv = strVal.startsWith('!');
  2653. if (inv) strVal = strVal.slice(1);
  2654. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2655. if (invEl) invEl.checked = inv;
  2656. }
  2657. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2658. if (valEl) valEl.value = strVal;
  2659. } else {
  2660. toggleFwField(fieldKey, false);
  2661. }
  2662. }
  2663. function getFwFieldVal(fieldKey, hasInvert = false) {
  2664. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2665. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2666. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2667. let v = valEl ? valEl.value.trim() : '';
  2668. if (!v) return '';
  2669. if (hasInvert) {
  2670. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2671. if (invEl && invEl.checked) {
  2672. v = '!' + v.replace(/^!/, '');
  2673. }
  2674. }
  2675. return v;
  2676. }
  2677. function toggleMaximizeFilterModal() {
  2678. const win = document.getElementById('filter-modal-window');
  2679. if (!win) return;
  2680. if (win.classList.contains('max-w-[720px]')) {
  2681. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2682. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2683. } else {
  2684. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2685. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2686. }
  2687. }
  2688. function openAddFilterModal() {
  2689. switchFwRuleTab('general');
  2690. const badge = document.getElementById('fw-modal-badge');
  2691. if (badge) badge.innerText = 'New...';
  2692. document.getElementById('filter-modal-id').value = '';
  2693. document.getElementById('filter-modal-enabled').checked = true;
  2694. document.getElementById('filter-modal-comment').value = '';
  2695. document.getElementById('filter-modal-chain').value = 'forward';
  2696. document.getElementById('filter-modal-action').value = 'accept';
  2697. document.getElementById('filter-modal-log').checked = false;
  2698. populateInterfaceSelect('fw-val-iniface');
  2699. populateInterfaceSelect('fw-val-outiface');
  2700. populateAddressListSelect('fw-val-srclist');
  2701. populateAddressListSelect('fw-val-dstlist');
  2702. populateGeoIPSelect('fw-val-srcgeo');
  2703. populateGeoIPSelect('fw-val-dstgeo');
  2704. const allFieldKeys = [
  2705. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2706. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2707. 'routingmark', 'conntype', 'cs', 'natstate',
  2708. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2709. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2710. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2711. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2712. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2713. ];
  2714. allFieldKeys.forEach(k => toggleFwField(k, false));
  2715. resetCurrentRuleCounters();
  2716. toggleFilterActionFields();
  2717. document.getElementById('filter-modal').classList.remove('hidden');
  2718. }
  2719. function openEditFilterModal(id) {
  2720. const r = (state.filterRules || []).find(rule => rule.id === id);
  2721. if (!r) return;
  2722. switchFwRuleTab('general');
  2723. const badge = document.getElementById('fw-modal-badge');
  2724. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2725. document.getElementById('filter-modal-id').value = r.id;
  2726. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2727. document.getElementById('filter-modal-comment').value = r.comment || '';
  2728. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2729. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2730. document.getElementById('filter-modal-log').checked = !!r.log;
  2731. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2732. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2733. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2734. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2735. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2736. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2737. setFwFieldVal('src', r.src_address, true);
  2738. setFwFieldVal('dst', r.dst_address, true);
  2739. setFwFieldVal('srclist', r.src_address_list, true);
  2740. setFwFieldVal('dstlist', r.dst_address_list, true);
  2741. setFwFieldVal('srcgeo', r.src_geoip, true);
  2742. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2743. if (r.protocol && r.protocol !== 'all') {
  2744. setFwFieldVal('proto', r.protocol, true);
  2745. } else {
  2746. toggleFwField('proto', false);
  2747. }
  2748. setFwFieldVal('sport', r.src_port, true);
  2749. setFwFieldVal('dport', r.dst_port, true);
  2750. setFwFieldVal('anyport', r.any_port, true);
  2751. setFwFieldVal('iniface', r.in_interface, true);
  2752. setFwFieldVal('outiface', r.out_interface, true);
  2753. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2754. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2755. setFwFieldVal('pktmark', r.packet_mark, true);
  2756. setFwFieldVal('connmark', r.connection_mark, true);
  2757. setFwFieldVal('routingmark', r.routing_mark, true);
  2758. setFwFieldVal('conntype', r.connection_type, false);
  2759. const states = r.connection_state || [];
  2760. if (states.length > 0) {
  2761. toggleFwField('cs', true);
  2762. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2763. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2764. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2765. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2766. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2767. } else {
  2768. toggleFwField('cs', false);
  2769. }
  2770. const natStates = r.connection_nat_state || [];
  2771. if (natStates.length > 0) {
  2772. toggleFwField('natstate', true);
  2773. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2774. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2775. } else {
  2776. toggleFwField('natstate', false);
  2777. }
  2778. // Advanced tab fields
  2779. setFwFieldVal('layer7', r.layer7_protocol, false);
  2780. setFwFieldVal('content', r.content, false);
  2781. setFwFieldVal('connbytes', r.connection_bytes, false);
  2782. setFwFieldVal('connrate', r.connection_rate, false);
  2783. setFwFieldVal('pcc', r.pcc, false);
  2784. setFwFieldVal('srcmac', r.src_mac_address, true);
  2785. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2786. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2787. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2788. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2789. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2790. setFwFieldVal('tlshost', r.tls_host, false);
  2791. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2792. setFwFieldVal('priority', r.priority, false);
  2793. setFwFieldVal('dscp', r.dscp, false);
  2794. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2795. if (r.tos) {
  2796. const tosEl = document.getElementById('fw-val-tos');
  2797. if (tosEl) tosEl.value = r.tos;
  2798. }
  2799. setFwFieldVal('pktsize', r.packet_size, false);
  2800. setFwFieldVal('random', r.random, false);
  2801. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2802. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2803. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2804. setFwFieldVal('ttl', r.ttl, false);
  2805. // Extra tab fields
  2806. setFwFieldVal('time', r.time, false);
  2807. if (r.days) {
  2808. toggleFwField('days', true);
  2809. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2810. const chk = document.getElementById(`fw-day-${d}`);
  2811. if (chk) chk.checked = r.days.includes(d);
  2812. });
  2813. } else {
  2814. toggleFwField('days', false);
  2815. }
  2816. setFwFieldVal('limit', r.limit, false);
  2817. setFwFieldVal('dstlimit', r.dst_limit, false);
  2818. setFwFieldVal('psd', r.psd, false);
  2819. // Action fields
  2820. if (r.reject_with) {
  2821. const rwEl = document.getElementById('filter-modal-rejectwith');
  2822. if (rwEl) rwEl.value = r.reject_with;
  2823. }
  2824. if (r.jump_target) {
  2825. const jtEl = document.getElementById('filter-modal-jumptarget');
  2826. if (jtEl) jtEl.value = r.jump_target;
  2827. }
  2828. if (r.address_list) {
  2829. const alEl = document.getElementById('filter-modal-action-addrlist');
  2830. if (alEl) alEl.value = r.address_list;
  2831. }
  2832. if (r.address_list_timeout) {
  2833. const toEl = document.getElementById('filter-modal-action-timeout');
  2834. if (toEl) toEl.value = r.address_list_timeout;
  2835. }
  2836. setFwFieldVal('logprefix', r.log_prefix, false);
  2837. // Statistics
  2838. const bEl = document.getElementById('fw-stat-bytes');
  2839. const pEl = document.getElementById('fw-stat-packets');
  2840. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2841. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2842. state.fwLastBytes = r.bytes || 0;
  2843. state.fwLastPackets = r.packets || 0;
  2844. state.fwLastTimestamp = Date.now();
  2845. state.fwStatRateHistory = new Array(30).fill(0);
  2846. state.fwStatPktHistory = new Array(30).fill(0);
  2847. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2848. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2849. toggleFilterActionFields();
  2850. document.getElementById('filter-modal').classList.remove('hidden');
  2851. }
  2852. function closeFilterModal() {
  2853. stopFwStatPolling();
  2854. document.getElementById('filter-modal').classList.add('hidden');
  2855. }
  2856. function toggleFilterActionFields() {
  2857. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2858. const rejectBox = document.getElementById('filter-action-reject-box');
  2859. const jumpBox = document.getElementById('filter-action-jump-box');
  2860. const addrBox = document.getElementById('filter-action-addrlist-box');
  2861. if (rejectBox) {
  2862. if (act === 'reject') rejectBox.classList.remove('hidden');
  2863. else rejectBox.classList.add('hidden');
  2864. }
  2865. if (jumpBox) {
  2866. if (act === 'jump') jumpBox.classList.remove('hidden');
  2867. else jumpBox.classList.add('hidden');
  2868. }
  2869. if (addrBox) {
  2870. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  2871. addrBox.classList.remove('hidden');
  2872. } else {
  2873. addrBox.classList.add('hidden');
  2874. }
  2875. }
  2876. if (act === 'log') {
  2877. const logEl = document.getElementById('filter-modal-log');
  2878. if (logEl) logEl.checked = true;
  2879. toggleFwField('logprefix', true);
  2880. }
  2881. }
  2882. function toggleFwLogPrefix() {
  2883. const isLog = document.getElementById('filter-modal-log')?.checked;
  2884. toggleFwField('logprefix', !!isLog);
  2885. }
  2886. function copyFilterRule() {
  2887. document.getElementById('filter-modal-id').value = '';
  2888. const badge = document.getElementById('fw-modal-badge');
  2889. if (badge) badge.innerText = 'New...';
  2890. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2891. }
  2892. function resetCurrentRuleCounters() {
  2893. state.fwStatRateHistory = new Array(30).fill(0);
  2894. state.fwStatPktHistory = new Array(30).fill(0);
  2895. state.fwLastBytes = 0;
  2896. state.fwLastPackets = 0;
  2897. state.fwLastTimestamp = Date.now();
  2898. const bEl = document.getElementById('fw-stat-bytes');
  2899. const pEl = document.getElementById('fw-stat-packets');
  2900. const rEl = document.getElementById('fw-stat-rate');
  2901. const prEl = document.getElementById('fw-stat-pktrate');
  2902. if (bEl) bEl.value = '0 B';
  2903. if (pEl) pEl.value = '0';
  2904. if (rEl) rEl.value = '0 bps';
  2905. if (prEl) prEl.value = '0 p/s';
  2906. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2907. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2908. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2909. }
  2910. async function resetAllFwCounters() {
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2913. if (res.ok) {
  2914. resetCurrentRuleCounters();
  2915. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2916. loadFirewall(false);
  2917. }
  2918. } catch (err) {
  2919. showToast('Error', err.message, 'error');
  2920. }
  2921. }
  2922. async function applyFilterRule(closeAfter = false) {
  2923. const id = document.getElementById('filter-modal-id').value;
  2924. const chain = document.getElementById('filter-modal-chain').value;
  2925. const action = document.getElementById('filter-modal-action').value;
  2926. const comment = document.getElementById('filter-modal-comment').value.trim();
  2927. const enabled = document.getElementById('filter-modal-enabled').checked;
  2928. const src = getFwFieldVal('src', true);
  2929. const dst = getFwFieldVal('dst', true);
  2930. const srclist = getFwFieldVal('srclist', true);
  2931. const dstlist = getFwFieldVal('dstlist', true);
  2932. const srcgeo = getFwFieldVal('srcgeo', true);
  2933. const dstgeo = getFwFieldVal('dstgeo', true);
  2934. const proto = getFwFieldVal('proto', true);
  2935. const sport = getFwFieldVal('sport', true);
  2936. const dport = getFwFieldVal('dport', true);
  2937. const anyport = getFwFieldVal('anyport', true);
  2938. const iniface = getFwFieldVal('iniface', true);
  2939. const outiface = getFwFieldVal('outiface', true);
  2940. const inifacelist = getFwFieldVal('inifacelist', true);
  2941. const outifacelist = getFwFieldVal('outifacelist', true);
  2942. const pktmark = getFwFieldVal('pktmark', true);
  2943. const connmark = getFwFieldVal('connmark', true);
  2944. const routingmark = getFwFieldVal('routingmark', true);
  2945. const conntype = getFwFieldVal('conntype', false);
  2946. const states = [];
  2947. const csBox = document.getElementById('fw-field-cs');
  2948. if (csBox && !csBox.classList.contains('hidden')) {
  2949. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2950. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2951. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2952. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2953. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2954. }
  2955. const natStates = [];
  2956. const natBox = document.getElementById('fw-field-natstate');
  2957. if (natBox && !natBox.classList.contains('hidden')) {
  2958. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2959. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2960. }
  2961. const payload = {
  2962. id,
  2963. chain,
  2964. action,
  2965. protocol: proto || 'all',
  2966. src_address: src,
  2967. dst_address: dst,
  2968. src_port: sport,
  2969. dst_port: dport,
  2970. any_port: anyport,
  2971. in_interface: iniface,
  2972. out_interface: outiface,
  2973. in_interface_list: inifacelist,
  2974. out_interface_list: outifacelist,
  2975. packet_mark: pktmark,
  2976. connection_mark: connmark,
  2977. routing_mark: routingmark,
  2978. connection_type: conntype,
  2979. connection_state: states,
  2980. connection_nat_state: natStates,
  2981. src_address_list: srclist,
  2982. dst_address_list: dstlist,
  2983. src_geoip: srcgeo,
  2984. dst_geoip: dstgeo,
  2985. comment,
  2986. disabled: !enabled,
  2987. // Advanced tab
  2988. layer7_protocol: getFwFieldVal('layer7', false),
  2989. content: getFwFieldVal('content', false),
  2990. connection_bytes: getFwFieldVal('connbytes', false),
  2991. connection_rate: getFwFieldVal('connrate', false),
  2992. pcc: getFwFieldVal('pcc', false),
  2993. src_mac_address: getFwFieldVal('srcmac', true),
  2994. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2995. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2996. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2997. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2998. ipsec_policy: getFwFieldVal('ipsec', false),
  2999. tls_host: getFwFieldVal('tlshost', false),
  3000. ingress_priority: getFwFieldVal('ingresspriority', false),
  3001. priority: getFwFieldVal('priority', false),
  3002. dscp: getFwFieldVal('dscp', false),
  3003. tcp_mss: getFwFieldVal('tcpmss', false),
  3004. tos: document.getElementById('fw-val-tos')?.value || '',
  3005. packet_size: getFwFieldVal('pktsize', false),
  3006. random: getFwFieldVal('random', false),
  3007. tcp_flags: getFwFieldVal('tcpflags', false),
  3008. icmp_options: getFwFieldVal('icmpoptions', false),
  3009. ipv4_options: getFwFieldVal('ipv4options', false),
  3010. ttl: getFwFieldVal('ttl', false),
  3011. // Extra tab
  3012. time: getFwFieldVal('time', false),
  3013. limit: getFwFieldVal('limit', false),
  3014. dst_limit: getFwFieldVal('dstlimit', false),
  3015. psd: getFwFieldVal('psd', false),
  3016. // Action tab
  3017. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3018. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3019. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3020. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3021. log: document.getElementById('filter-modal-log')?.checked || false,
  3022. log_prefix: getFwFieldVal('logprefix', false)
  3023. };
  3024. try {
  3025. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3026. method: 'POST',
  3027. headers: { 'Content-Type': 'application/json' },
  3028. body: JSON.stringify(payload)
  3029. });
  3030. if (res.ok) {
  3031. const data = await res.json();
  3032. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3033. loadFirewall(false);
  3034. if (closeAfter) {
  3035. closeFilterModal();
  3036. } else {
  3037. if (data.id) {
  3038. document.getElementById('filter-modal-id').value = data.id;
  3039. const badge = document.getElementById('fw-modal-badge');
  3040. if (badge) badge.innerText = `#${data.id}`;
  3041. }
  3042. }
  3043. } else {
  3044. const err = await res.json();
  3045. showToast('Error', err.message || 'Failed to save rule', 'error');
  3046. }
  3047. } catch (err) {
  3048. showToast('Error', err.message, 'error');
  3049. }
  3050. }
  3051. function submitSaveFilterRule(e) {
  3052. if (e && e.preventDefault) e.preventDefault();
  3053. return applyFilterRule(true);
  3054. }
  3055. function startFwStatPolling() {
  3056. stopFwStatPolling();
  3057. pollRuleStats();
  3058. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3059. }
  3060. function stopFwStatPolling() {
  3061. if (state.fwStatInterval) {
  3062. clearInterval(state.fwStatInterval);
  3063. state.fwStatInterval = null;
  3064. }
  3065. }
  3066. async function pollRuleStats() {
  3067. const id = document.getElementById('filter-modal-id')?.value;
  3068. if (!id) {
  3069. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3070. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3071. return;
  3072. }
  3073. try {
  3074. const res = await fetch(`${API_BASE}/firewall/filter`);
  3075. if (!res.ok) return;
  3076. const rules = await res.json();
  3077. const r = rules.find(x => x.id === id);
  3078. if (!r) return;
  3079. const now = Date.now();
  3080. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3081. state.fwLastTimestamp = now;
  3082. const curBytes = r.bytes || 0;
  3083. const curPackets = r.packets || 0;
  3084. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3085. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3086. state.fwLastBytes = curBytes;
  3087. state.fwLastPackets = curPackets;
  3088. const rateBps = Math.round((deltaBytes * 8) / dt);
  3089. const ratePkt = Math.round(deltaPkts / dt);
  3090. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3091. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3092. state.fwStatRateHistory.push(rateBps);
  3093. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3094. state.fwStatPktHistory.push(ratePkt);
  3095. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3096. const bEl = document.getElementById('fw-stat-bytes');
  3097. const pEl = document.getElementById('fw-stat-packets');
  3098. const rEl = document.getElementById('fw-stat-rate');
  3099. const prEl = document.getElementById('fw-stat-pktrate');
  3100. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3101. if (pEl) pEl.value = curPackets.toLocaleString();
  3102. if (rEl) rEl.value = formatBps(rateBps);
  3103. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3104. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3105. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3106. } catch (e) {
  3107. console.error('Error polling rule stats', e);
  3108. }
  3109. }
  3110. function formatBps(bps) {
  3111. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3112. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3113. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3114. return bps + ' bps';
  3115. }
  3116. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3117. const svg = document.getElementById(svgId);
  3118. if (!svg) return;
  3119. const w = 500;
  3120. const h = 100;
  3121. const paddingRight = 45;
  3122. const graphWidth = w - paddingRight;
  3123. const maxVal = Math.max(5, ...dataArray);
  3124. const currentVal = dataArray[dataArray.length - 1] || 0;
  3125. const leg = document.getElementById(legendId);
  3126. if (leg) {
  3127. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3128. }
  3129. let gridLines = '';
  3130. for (let i = 0; i <= 5; i++) {
  3131. const y = 8 + (i * (h - 18) / 5);
  3132. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3133. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3134. gridLines += `
  3135. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3136. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3137. `;
  3138. }
  3139. const step = graphWidth / (dataArray.length - 1);
  3140. const points = dataArray.map((val, idx) => {
  3141. const x = idx * step;
  3142. const y = (h - 10) - (val / maxVal) * (h - 20);
  3143. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3144. });
  3145. const polylineStr = points.join(' ');
  3146. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3147. svg.innerHTML = `
  3148. ${gridLines}
  3149. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3150. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3151. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3152. `;
  3153. }
  3154. async function moveFilterRule(id, dir) {
  3155. try {
  3156. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3157. method: 'POST',
  3158. headers: { 'Content-Type': 'application/json' },
  3159. body: JSON.stringify({ direction: dir })
  3160. });
  3161. if (res.ok) loadFirewall(false);
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function toggleFilterRuleState(id, disabled) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ disabled })
  3172. });
  3173. if (res.ok) loadFirewall(false);
  3174. } catch (err) {
  3175. showToast('Error', err.message, 'error');
  3176. }
  3177. }
  3178. async function deleteFilterRule(id) {
  3179. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('Deleted', 'Filter rule removed', 'success');
  3184. loadFirewall(false);
  3185. }
  3186. } catch (err) {
  3187. showToast('Error', err.message, 'error');
  3188. }
  3189. }
  3190. // ----------------- NAT Rules -----------------
  3191. function renderNATRules() {
  3192. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3193. const tbody = document.getElementById('nat-table-body');
  3194. const empty = document.getElementById('nat-empty');
  3195. if (!tbody) return;
  3196. tbody.innerHTML = '';
  3197. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3198. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3199. if (rules.length === 0) {
  3200. empty?.classList.remove('hidden');
  3201. return;
  3202. }
  3203. empty?.classList.add('hidden');
  3204. rules.forEach((r, idx) => {
  3205. const tr = document.createElement('tr');
  3206. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3207. let toTarget = '-';
  3208. if (r.action === 'jump') {
  3209. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3210. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3211. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3212. } else if (r.action === 'redirect') {
  3213. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3214. } else if (r.action === 'masquerade') {
  3215. 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>`;
  3216. } else if (r.action === 'log') {
  3217. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3218. } else {
  3219. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3220. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3221. }
  3222. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3223. tr.innerHTML = `
  3224. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3225. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3226. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3227. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3228. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3229. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3230. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3231. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3232. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3233. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3234. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3235. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3236. </td>
  3237. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3238. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3239. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3240. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3241. <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>
  3242. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3243. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3244. </td>
  3245. `;
  3246. tbody.appendChild(tr);
  3247. });
  3248. }
  3249. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3250. function switchNATRuleTab(tab) {
  3251. state.activeNATRuleTab = tab;
  3252. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3253. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3254. btn.classList.add('text-slate-400', 'border-transparent');
  3255. });
  3256. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3257. if (activeBtn) {
  3258. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3259. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3260. }
  3261. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3262. const activePane = document.getElementById(`nat-pane-${tab}`);
  3263. if (activePane) activePane.classList.remove('hidden');
  3264. if (tab === 'statistics') {
  3265. startNATStatPolling();
  3266. } else {
  3267. stopNATStatPolling();
  3268. }
  3269. }
  3270. function toggleNATField(fieldKey, expand) {
  3271. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3272. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3273. if (!plusBtn || !fieldBox) return;
  3274. if (expand) {
  3275. plusBtn.classList.add('hidden');
  3276. fieldBox.classList.remove('hidden');
  3277. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3278. if (valInput) valInput.focus();
  3279. } else {
  3280. fieldBox.classList.add('hidden');
  3281. plusBtn.classList.remove('hidden');
  3282. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3283. if (valInput) {
  3284. if (valInput.tagName === 'SELECT') {
  3285. valInput.selectedIndex = 0;
  3286. } else {
  3287. valInput.value = '';
  3288. }
  3289. }
  3290. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3291. if (invInput) invInput.checked = false;
  3292. if (fieldKey === 'days') {
  3293. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3294. const el = document.getElementById(`nat-day-${d}`);
  3295. if (el) el.checked = true;
  3296. });
  3297. }
  3298. }
  3299. }
  3300. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3301. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3302. toggleNATField(fieldKey, true);
  3303. let strVal = String(value);
  3304. if (hasInvert) {
  3305. const inv = strVal.startsWith('!');
  3306. if (inv) strVal = strVal.slice(1);
  3307. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3308. if (invEl) invEl.checked = inv;
  3309. }
  3310. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3311. if (valEl) valEl.value = strVal;
  3312. } else {
  3313. toggleNATField(fieldKey, false);
  3314. }
  3315. }
  3316. function getNATFieldVal(fieldKey, hasInvert = false) {
  3317. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3318. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3319. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3320. let v = valEl ? valEl.value.trim() : '';
  3321. if (!v) return '';
  3322. if (hasInvert) {
  3323. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3324. if (invEl && invEl.checked) {
  3325. v = '!' + v.replace(/^!/, '');
  3326. }
  3327. }
  3328. return v;
  3329. }
  3330. function toggleMaximizeNATModal() {
  3331. const win = document.getElementById('nat-modal-window');
  3332. if (!win) return;
  3333. if (win.classList.contains('max-w-[720px]')) {
  3334. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3335. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3336. } else {
  3337. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3338. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3339. }
  3340. }
  3341. function handleNATChainChange() {
  3342. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3343. const actSel = document.getElementById('nat-modal-action');
  3344. if (actSel) {
  3345. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3346. actSel.value = 'masquerade';
  3347. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3348. actSel.value = 'dst-nat';
  3349. }
  3350. }
  3351. toggleNATActionFields();
  3352. }
  3353. function toggleNATActionFields() {
  3354. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3355. const rowAddr = document.getElementById('nat-row-toaddr');
  3356. const rowPort = document.getElementById('nat-row-toport');
  3357. const jumpBox = document.getElementById('nat-action-jump-box');
  3358. const addrBox = document.getElementById('nat-action-addrlist-box');
  3359. // Hide all dynamic rows first
  3360. if (rowAddr) rowAddr.classList.add('hidden');
  3361. if (rowPort) rowPort.classList.add('hidden');
  3362. if (jumpBox) jumpBox.classList.add('hidden');
  3363. if (addrBox) addrBox.classList.add('hidden');
  3364. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3365. if (rowAddr) rowAddr.classList.remove('hidden');
  3366. if (rowPort) rowPort.classList.remove('hidden');
  3367. } else if (act === 'redirect' || act === 'masquerade') {
  3368. if (rowPort) rowPort.classList.remove('hidden');
  3369. } else if (act === 'jump') {
  3370. if (jumpBox) jumpBox.classList.remove('hidden');
  3371. } else if (act.includes('address-list') || act.includes('address list')) {
  3372. if (addrBox) addrBox.classList.remove('hidden');
  3373. }
  3374. if (act === 'log') {
  3375. const logEl = document.getElementById('nat-modal-log');
  3376. if (logEl) logEl.checked = true;
  3377. toggleNATField('logprefix', true);
  3378. }
  3379. }
  3380. function toggleNATLogPrefix() {
  3381. const isLog = document.getElementById('nat-modal-log')?.checked;
  3382. toggleNATField('logprefix', !!isLog);
  3383. }
  3384. function openAddNATModal() {
  3385. switchNATRuleTab('general');
  3386. const badge = document.getElementById('nat-modal-badge');
  3387. if (badge) badge.innerText = 'New...';
  3388. document.getElementById('nat-modal-id').value = '';
  3389. document.getElementById('nat-modal-enabled').checked = true;
  3390. document.getElementById('nat-modal-comment').value = '';
  3391. document.getElementById('nat-modal-chain').value = 'srcnat';
  3392. document.getElementById('nat-modal-action').value = 'masquerade';
  3393. document.getElementById('nat-modal-toaddr').value = '';
  3394. document.getElementById('nat-modal-toport').value = '';
  3395. document.getElementById('nat-modal-log').checked = false;
  3396. populateInterfaceSelect('nat-val-iniface');
  3397. populateInterfaceSelect('nat-val-outiface');
  3398. populateAddressListSelect('nat-val-srclist');
  3399. populateAddressListSelect('nat-val-dstlist');
  3400. populateGeoIPSelect('nat-val-srcgeo');
  3401. populateGeoIPSelect('nat-val-dstgeo');
  3402. const allFieldKeys = [
  3403. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3404. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3405. 'routingmark', 'conntype',
  3406. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3407. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3408. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3409. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3410. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3411. ];
  3412. allFieldKeys.forEach(k => toggleNATField(k, false));
  3413. resetCurrentNATRuleCounters();
  3414. toggleNATActionFields();
  3415. document.getElementById('nat-modal').classList.remove('hidden');
  3416. }
  3417. function openEditNATModal(id) {
  3418. const r = (state.natRules || []).find(rule => rule.id === id);
  3419. if (!r) return;
  3420. switchNATRuleTab('general');
  3421. const badge = document.getElementById('nat-modal-badge');
  3422. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3423. document.getElementById('nat-modal-id').value = r.id;
  3424. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3425. document.getElementById('nat-modal-comment').value = r.comment || '';
  3426. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3427. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3428. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3429. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3430. document.getElementById('nat-modal-log').checked = !!r.log;
  3431. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3432. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3433. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3434. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3435. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3436. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3437. setNATFieldVal('src', r.src_address, true);
  3438. setNATFieldVal('dst', r.dst_address, true);
  3439. setNATFieldVal('srclist', r.src_address_list, true);
  3440. setNATFieldVal('dstlist', r.dst_address_list, true);
  3441. setNATFieldVal('srcgeo', r.src_geoip, true);
  3442. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3443. if (r.protocol && r.protocol !== 'all') {
  3444. setNATFieldVal('proto', r.protocol, true);
  3445. } else {
  3446. toggleNATField('proto', false);
  3447. }
  3448. setNATFieldVal('sport', r.src_port, true);
  3449. setNATFieldVal('dport', r.dst_port, true);
  3450. setNATFieldVal('anyport', r.any_port, true);
  3451. setNATFieldVal('iniface', r.in_interface, true);
  3452. setNATFieldVal('outiface', r.out_interface, true);
  3453. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3454. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3455. setNATFieldVal('pktmark', r.packet_mark, true);
  3456. setNATFieldVal('connmark', r.connection_mark, true);
  3457. setNATFieldVal('routingmark', r.routing_mark, true);
  3458. setNATFieldVal('conntype', r.connection_type, false);
  3459. // Advanced tab fields
  3460. setNATFieldVal('layer7', r.layer7_protocol, false);
  3461. setNATFieldVal('content', r.content, false);
  3462. setNATFieldVal('connbytes', r.connection_bytes, false);
  3463. setNATFieldVal('connrate', r.connection_rate, false);
  3464. setNATFieldVal('pcc', r.pcc, false);
  3465. setNATFieldVal('srcmac', r.src_mac_address, true);
  3466. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3467. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3468. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3469. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3470. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3471. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3472. setNATFieldVal('priority', r.priority, false);
  3473. setNATFieldVal('dscp', r.dscp, false);
  3474. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3475. if (r.tos) {
  3476. const tosEl = document.getElementById('nat-val-tos');
  3477. if (tosEl) tosEl.value = r.tos;
  3478. }
  3479. setNATFieldVal('pktsize', r.packet_size, false);
  3480. setNATFieldVal('random', r.random, false);
  3481. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3482. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3483. setNATFieldVal('ttl', r.ttl, false);
  3484. // Extra tab fields
  3485. setNATFieldVal('time', r.time, false);
  3486. if (r.days) {
  3487. toggleNATField('days', true);
  3488. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3489. const chk = document.getElementById(`nat-day-${d}`);
  3490. if (chk) chk.checked = r.days.includes(d);
  3491. });
  3492. } else {
  3493. toggleNATField('days', false);
  3494. }
  3495. setNATFieldVal('limit', r.limit, false);
  3496. setNATFieldVal('dstlimit', r.dst_limit, false);
  3497. setNATFieldVal('psd', r.psd, false);
  3498. // Action fields
  3499. if (r.jump_target) {
  3500. const jtEl = document.getElementById('nat-modal-jumptarget');
  3501. if (jtEl) jtEl.value = r.jump_target;
  3502. }
  3503. if (r.address_list) {
  3504. const alEl = document.getElementById('nat-modal-action-addrlist');
  3505. if (alEl) alEl.value = r.address_list;
  3506. }
  3507. if (r.address_list_timeout) {
  3508. const toEl = document.getElementById('nat-modal-action-timeout');
  3509. if (toEl) toEl.value = r.address_list_timeout;
  3510. }
  3511. setNATFieldVal('logprefix', r.log_prefix, false);
  3512. // Statistics
  3513. const bEl = document.getElementById('nat-stat-bytes');
  3514. const pEl = document.getElementById('nat-stat-packets');
  3515. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3516. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3517. state.natLastBytes = r.bytes || 0;
  3518. state.natLastPackets = r.packets || 0;
  3519. state.natLastTimestamp = Date.now();
  3520. state.natStatRateHistory = new Array(30).fill(0);
  3521. state.natStatPktHistory = new Array(30).fill(0);
  3522. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3523. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3524. toggleNATActionFields();
  3525. document.getElementById('nat-modal').classList.remove('hidden');
  3526. }
  3527. function closeNATModal() {
  3528. stopNATStatPolling();
  3529. document.getElementById('nat-modal').classList.add('hidden');
  3530. }
  3531. function copyNATRule() {
  3532. document.getElementById('nat-modal-id').value = '';
  3533. const badge = document.getElementById('nat-modal-badge');
  3534. if (badge) badge.innerText = 'New...';
  3535. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3536. }
  3537. function resetCurrentNATRuleCounters() {
  3538. state.natStatRateHistory = new Array(30).fill(0);
  3539. state.natStatPktHistory = new Array(30).fill(0);
  3540. state.natLastBytes = 0;
  3541. state.natLastPackets = 0;
  3542. state.natLastTimestamp = Date.now();
  3543. const bEl = document.getElementById('nat-stat-bytes');
  3544. const pEl = document.getElementById('nat-stat-packets');
  3545. const rEl = document.getElementById('nat-stat-rate');
  3546. const prEl = document.getElementById('nat-stat-pktrate');
  3547. if (bEl) bEl.value = '0 B';
  3548. if (pEl) pEl.value = '0';
  3549. if (rEl) rEl.value = '0 bps';
  3550. if (prEl) prEl.value = '0 p/s';
  3551. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3552. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3553. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3554. }
  3555. async function applyNATRule(closeAfter = false) {
  3556. const id = document.getElementById('nat-modal-id').value;
  3557. const chain = document.getElementById('nat-modal-chain').value;
  3558. const action = document.getElementById('nat-modal-action').value;
  3559. const comment = document.getElementById('nat-modal-comment').value.trim();
  3560. const enabled = document.getElementById('nat-modal-enabled').checked;
  3561. const src = getNATFieldVal('src', true);
  3562. const dst = getNATFieldVal('dst', true);
  3563. const srclist = getNATFieldVal('srclist', true);
  3564. const dstlist = getNATFieldVal('dstlist', true);
  3565. const srcgeo = getNATFieldVal('srcgeo', true);
  3566. const dstgeo = getNATFieldVal('dstgeo', true);
  3567. const proto = getNATFieldVal('proto', true);
  3568. const sport = getNATFieldVal('sport', true);
  3569. const dport = getNATFieldVal('dport', true);
  3570. const anyport = getNATFieldVal('anyport', true);
  3571. const iniface = getNATFieldVal('iniface', true);
  3572. const outiface = getNATFieldVal('outiface', true);
  3573. const inifacelist = getNATFieldVal('inifacelist', true);
  3574. const outifacelist = getNATFieldVal('outifacelist', true);
  3575. const pktmark = getNATFieldVal('pktmark', true);
  3576. const connmark = getNATFieldVal('connmark', true);
  3577. const routingmark = getNATFieldVal('routingmark', true);
  3578. const conntype = getNATFieldVal('conntype', false);
  3579. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3580. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3581. const payload = {
  3582. id,
  3583. chain,
  3584. action,
  3585. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3586. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3587. protocol: proto || 'all',
  3588. src_address: src,
  3589. dst_address: dst,
  3590. src_port: sport,
  3591. dst_port: dport,
  3592. any_port: anyport,
  3593. in_interface: iniface,
  3594. out_interface: outiface,
  3595. in_interface_list: inifacelist,
  3596. out_interface_list: outifacelist,
  3597. packet_mark: pktmark,
  3598. connection_mark: connmark,
  3599. routing_mark: routingmark,
  3600. connection_type: conntype,
  3601. src_address_list: srclist,
  3602. dst_address_list: dstlist,
  3603. src_geoip: srcgeo,
  3604. dst_geoip: dstgeo,
  3605. comment,
  3606. disabled: !enabled,
  3607. // Advanced tab
  3608. layer7_protocol: getNATFieldVal('layer7', false),
  3609. content: getNATFieldVal('content', false),
  3610. connection_bytes: getNATFieldVal('connbytes', false),
  3611. connection_rate: getNATFieldVal('connrate', false),
  3612. pcc: getNATFieldVal('pcc', false),
  3613. src_mac_address: getNATFieldVal('srcmac', true),
  3614. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3615. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3616. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3617. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3618. ipsec_policy: getNATFieldVal('ipsec', false),
  3619. ingress_priority: getNATFieldVal('ingresspriority', false),
  3620. priority: getNATFieldVal('priority', false),
  3621. dscp: getNATFieldVal('dscp', false),
  3622. tcp_mss: getNATFieldVal('tcpmss', false),
  3623. tos: document.getElementById('nat-val-tos')?.value || '',
  3624. packet_size: getNATFieldVal('pktsize', false),
  3625. random: getNATFieldVal('random', false),
  3626. icmp_options: getNATFieldVal('icmpoptions', false),
  3627. ipv4_options: getNATFieldVal('ipv4options', false),
  3628. ttl: getNATFieldVal('ttl', false),
  3629. // Extra tab
  3630. time: getNATFieldVal('time', false),
  3631. limit: getNATFieldVal('limit', false),
  3632. dst_limit: getNATFieldVal('dstlimit', false),
  3633. psd: getNATFieldVal('psd', false),
  3634. // Action tab
  3635. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3636. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3637. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3638. log: document.getElementById('nat-modal-log')?.checked || false,
  3639. log_prefix: getNATFieldVal('logprefix', false)
  3640. };
  3641. try {
  3642. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3643. method: 'POST',
  3644. headers: { 'Content-Type': 'application/json' },
  3645. body: JSON.stringify(payload)
  3646. });
  3647. if (res.ok) {
  3648. const data = await res.json();
  3649. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3650. loadFirewall(false);
  3651. if (closeAfter) {
  3652. closeNATModal();
  3653. } else {
  3654. if (data.id) {
  3655. document.getElementById('nat-modal-id').value = data.id;
  3656. const badge = document.getElementById('nat-modal-badge');
  3657. if (badge) badge.innerText = `#${data.id}`;
  3658. }
  3659. }
  3660. } else {
  3661. const err = await res.json();
  3662. showToast('Error', err.message || 'Failed to save rule', 'error');
  3663. }
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. function submitSaveNATRule(e) {
  3669. if (e && e.preventDefault) e.preventDefault();
  3670. return applyNATRule(true);
  3671. }
  3672. function startNATStatPolling() {
  3673. stopNATStatPolling();
  3674. pollNATRuleStats();
  3675. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3676. }
  3677. function stopNATStatPolling() {
  3678. if (state.natStatInterval) {
  3679. clearInterval(state.natStatInterval);
  3680. state.natStatInterval = null;
  3681. }
  3682. }
  3683. async function pollNATRuleStats() {
  3684. const id = document.getElementById('nat-modal-id')?.value;
  3685. if (!id) {
  3686. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3687. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3688. return;
  3689. }
  3690. try {
  3691. const res = await fetch(`${API_BASE}/firewall/nat`);
  3692. if (!res.ok) return;
  3693. const rules = await res.json();
  3694. const r = rules.find(x => x.id === id);
  3695. if (!r) return;
  3696. const now = Date.now();
  3697. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3698. state.natLastTimestamp = now;
  3699. const curBytes = r.bytes || 0;
  3700. const curPackets = r.packets || 0;
  3701. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3702. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3703. state.natLastBytes = curBytes;
  3704. state.natLastPackets = curPackets;
  3705. const rateBps = Math.round((deltaBytes * 8) / dt);
  3706. const ratePkt = Math.round(deltaPkts / dt);
  3707. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3708. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3709. state.natStatRateHistory.push(rateBps);
  3710. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3711. state.natStatPktHistory.push(ratePkt);
  3712. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3713. const bEl = document.getElementById('nat-stat-bytes');
  3714. const pEl = document.getElementById('nat-stat-packets');
  3715. const rEl = document.getElementById('nat-stat-rate');
  3716. const prEl = document.getElementById('nat-stat-pktrate');
  3717. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3718. if (pEl) pEl.value = curPackets.toLocaleString();
  3719. if (rEl) rEl.value = formatBps(rateBps);
  3720. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3721. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3722. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3723. } catch (e) {
  3724. console.error('Error polling NAT rule stats', e);
  3725. }
  3726. }
  3727. async function moveNATRule(id, dir) {
  3728. try {
  3729. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3730. method: 'POST',
  3731. headers: { 'Content-Type': 'application/json' },
  3732. body: JSON.stringify({ direction: dir })
  3733. });
  3734. if (res.ok) loadFirewall(false);
  3735. } catch (err) {
  3736. showToast('Error', err.message, 'error');
  3737. }
  3738. }
  3739. async function toggleNATRuleState(id, disabled) {
  3740. try {
  3741. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3742. method: 'POST',
  3743. headers: { 'Content-Type': 'application/json' },
  3744. body: JSON.stringify({ disabled })
  3745. });
  3746. if (res.ok) loadFirewall(false);
  3747. } catch (err) {
  3748. showToast('Error', err.message, 'error');
  3749. }
  3750. }
  3751. async function deleteNATRule(id) {
  3752. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3753. try {
  3754. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3755. if (res.ok) {
  3756. showToast('Deleted', 'NAT rule removed', 'success');
  3757. loadFirewall(false);
  3758. }
  3759. } catch (err) {
  3760. showToast('Error', err.message, 'error');
  3761. }
  3762. }
  3763. // ----------------- Mangle Rules -----------------
  3764. function renderMangleRules() {
  3765. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3766. const tbody = document.getElementById('mangle-table-body');
  3767. const empty = document.getElementById('mangle-empty');
  3768. if (!tbody) return;
  3769. tbody.innerHTML = '';
  3770. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3771. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3772. if (rules.length === 0) {
  3773. empty?.classList.remove('hidden');
  3774. return;
  3775. }
  3776. empty?.classList.add('hidden');
  3777. rules.forEach((r, idx) => {
  3778. const tr = document.createElement('tr');
  3779. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3780. let markVal = '<span class="text-slate-500">-</span>';
  3781. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3782. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3783. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3784. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3785. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3786. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3787. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3788. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3789. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3790. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3791. 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>`;
  3792. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3793. tr.innerHTML = `
  3794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3795. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3796. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3797. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3798. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3799. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3800. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3801. <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>
  3802. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3803. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3804. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3805. </td>
  3806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3807. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3808. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3809. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3810. <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>
  3811. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3812. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3813. </td>
  3814. `;
  3815. tbody.appendChild(tr);
  3816. });
  3817. }
  3818. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3819. function switchMangleRuleTab(tab) {
  3820. state.activeMangleRuleTab = tab;
  3821. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  3822. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. btn.classList.add('text-slate-400', 'border-transparent');
  3824. });
  3825. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  3826. if (activeBtn) {
  3827. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3828. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3829. }
  3830. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  3831. const activePane = document.getElementById(`mangle-pane-${tab}`);
  3832. if (activePane) activePane.classList.remove('hidden');
  3833. if (tab === 'statistics') {
  3834. startMangleStatPolling();
  3835. } else {
  3836. stopMangleStatPolling();
  3837. }
  3838. }
  3839. function toggleMangleField(fieldKey, expand) {
  3840. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  3841. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3842. if (!plusBtn || !fieldBox) return;
  3843. if (expand) {
  3844. plusBtn.classList.add('hidden');
  3845. fieldBox.classList.remove('hidden');
  3846. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3847. if (valInput) valInput.focus();
  3848. } else {
  3849. fieldBox.classList.add('hidden');
  3850. plusBtn.classList.remove('hidden');
  3851. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3852. if (valInput) {
  3853. if (valInput.tagName === 'SELECT') {
  3854. valInput.selectedIndex = 0;
  3855. } else {
  3856. valInput.value = '';
  3857. }
  3858. }
  3859. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  3860. if (invInput) invInput.checked = false;
  3861. if (fieldKey === 'cs') {
  3862. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'natstate') {
  3868. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  3869. const el = document.getElementById(id);
  3870. if (el) el.checked = false;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3877. toggleMangleField(fieldKey, true);
  3878. let strVal = String(value);
  3879. if (hasInvert) {
  3880. const inv = strVal.startsWith('!');
  3881. if (inv) strVal = strVal.slice(1);
  3882. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3883. if (invEl) invEl.checked = inv;
  3884. }
  3885. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3886. if (valEl) valEl.value = strVal;
  3887. } else {
  3888. toggleMangleField(fieldKey, false);
  3889. }
  3890. }
  3891. function getMangleFieldVal(fieldKey, hasInvert = false) {
  3892. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3893. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3894. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3895. let v = valEl ? valEl.value.trim() : '';
  3896. if (!v) return '';
  3897. if (hasInvert) {
  3898. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3899. if (invEl && invEl.checked) {
  3900. v = '!' + v.replace(/^!/, '');
  3901. }
  3902. }
  3903. return v;
  3904. }
  3905. function toggleMaximizeMangleModal() {
  3906. const win = document.getElementById('mangle-modal-window');
  3907. if (!win) return;
  3908. if (win.classList.contains('max-w-[720px]')) {
  3909. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3910. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3911. } else {
  3912. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3913. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3914. }
  3915. }
  3916. function toggleMangleActionFields() {
  3917. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  3918. // Hide all dynamic rows first
  3919. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  3920. const el = document.getElementById(`mangle-row-${id}`);
  3921. if (el) el.classList.add('hidden');
  3922. });
  3923. const jumpBox = document.getElementById('mangle-action-jump-box');
  3924. const addrBox = document.getElementById('mangle-action-addrlist-box');
  3925. if (jumpBox) jumpBox.classList.add('hidden');
  3926. if (addrBox) addrBox.classList.add('hidden');
  3927. // Activate matching rows
  3928. if (act === 'mark-connection') {
  3929. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  3930. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3931. } else if (act === 'mark-routing') {
  3932. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  3933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3934. } else if (act === 'mark-packet') {
  3935. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  3936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3937. } else if (act === 'change-mss') {
  3938. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  3939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3940. } else if (act === 'change-dscp') {
  3941. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  3942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3943. } else if (act === 'change-ttl') {
  3944. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  3945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3946. } else if (act === 'set-priority') {
  3947. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  3948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3949. } else if (act === 'route') {
  3950. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  3951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3952. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  3953. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  3954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3955. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  3956. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3957. } else if (act === 'jump') {
  3958. if (jumpBox) jumpBox.classList.remove('hidden');
  3959. } else if (act.includes('address-list') || act.includes('address list')) {
  3960. if (addrBox) addrBox.classList.remove('hidden');
  3961. }
  3962. if (act === 'log') {
  3963. const logEl = document.getElementById('mangle-modal-log');
  3964. if (logEl) logEl.checked = true;
  3965. toggleMangleField('logprefix', true);
  3966. }
  3967. }
  3968. function toggleMangleLogPrefix() {
  3969. const isLog = document.getElementById('mangle-modal-log')?.checked;
  3970. toggleMangleField('logprefix', !!isLog);
  3971. }
  3972. const allMangleFieldKeys = [
  3973. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3974. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3975. 'routingmark', 'conntype', 'cs', 'natstate',
  3976. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3977. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3978. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3979. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3980. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  3981. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  3982. ];
  3983. function openAddMangleModal() {
  3984. switchMangleRuleTab('general');
  3985. const badge = document.getElementById('mangle-modal-badge');
  3986. if (badge) badge.innerText = 'New...';
  3987. document.getElementById('mangle-modal-id').value = '';
  3988. document.getElementById('mangle-modal-enabled').checked = true;
  3989. document.getElementById('mangle-modal-comment').value = '';
  3990. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3991. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3992. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  3993. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  3994. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  3995. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  3996. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  3997. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  3998. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  3999. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4000. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4001. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4002. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4003. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4004. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4005. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4006. populateInterfaceSelect('mangle-val-iniface');
  4007. populateInterfaceSelect('mangle-val-outiface');
  4008. populateAddressListSelect('mangle-val-srclist');
  4009. populateAddressListSelect('mangle-val-dstlist');
  4010. populateGeoIPSelect('mangle-val-srcgeo');
  4011. populateGeoIPSelect('mangle-val-dstgeo');
  4012. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4013. resetCurrentMangleRuleCounters();
  4014. toggleMangleActionFields();
  4015. document.getElementById('mangle-modal').classList.remove('hidden');
  4016. }
  4017. function openEditMangleModal(id) {
  4018. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4019. if (!r) return;
  4020. switchMangleRuleTab('general');
  4021. const badge = document.getElementById('mangle-modal-badge');
  4022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4023. document.getElementById('mangle-modal-id').value = r.id;
  4024. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4025. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4026. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4027. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4028. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4029. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4030. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4031. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4032. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4033. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4034. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4035. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4036. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4037. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4038. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4039. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4040. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4041. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4042. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4043. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4044. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4045. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4046. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4047. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4048. setMangleFieldVal('src', r.src_address, true);
  4049. setMangleFieldVal('dst', r.dst_address, true);
  4050. setMangleFieldVal('srclist', r.src_address_list, true);
  4051. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4052. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4053. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4054. if (r.protocol && r.protocol !== 'all') {
  4055. setMangleFieldVal('proto', r.protocol, true);
  4056. } else {
  4057. toggleMangleField('proto', false);
  4058. }
  4059. setMangleFieldVal('sport', r.src_port, true);
  4060. setMangleFieldVal('dport', r.dst_port, true);
  4061. setMangleFieldVal('anyport', r.any_port, true);
  4062. setMangleFieldVal('iniface', r.in_interface, true);
  4063. setMangleFieldVal('outiface', r.out_interface, true);
  4064. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4065. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4066. setMangleFieldVal('pktmark', r.packet_mark, true);
  4067. setMangleFieldVal('connmark', r.connection_mark, true);
  4068. setMangleFieldVal('routingmark', r.routing_mark, true);
  4069. setMangleFieldVal('conntype', r.connection_type, false);
  4070. // Connection State
  4071. const states = r.connection_state || [];
  4072. if (states.length > 0) {
  4073. toggleMangleField('cs', true);
  4074. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4075. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4076. if (el) el.checked = states.includes(s);
  4077. });
  4078. } else {
  4079. toggleMangleField('cs', false);
  4080. }
  4081. // Connection NAT State
  4082. const natStates = r.connection_nat_state || [];
  4083. if (natStates.length > 0) {
  4084. toggleMangleField('natstate', true);
  4085. ['srcnat', 'dstnat'].forEach(s => {
  4086. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4087. if (el) el.checked = natStates.includes(s);
  4088. });
  4089. } else {
  4090. toggleMangleField('natstate', false);
  4091. }
  4092. // Advanced tab fields
  4093. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4094. setMangleFieldVal('content', r.content, false);
  4095. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4096. setMangleFieldVal('connrate', r.connection_rate, false);
  4097. setMangleFieldVal('pcc', r.pcc, false);
  4098. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4099. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4100. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4101. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4102. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4103. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4104. setMangleFieldVal('tlshost', r.tls_host, false);
  4105. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4106. setMangleFieldVal('priority', r.priority, false);
  4107. setMangleFieldVal('dscp', r.dscp, false);
  4108. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4109. if (r.tos) {
  4110. const tosEl = document.getElementById('mangle-val-tos');
  4111. if (tosEl) tosEl.value = r.tos;
  4112. }
  4113. setMangleFieldVal('pktsize', r.packet_size, false);
  4114. setMangleFieldVal('random', r.random, false);
  4115. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4116. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4117. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4118. setMangleFieldVal('ttl', r.ttl, false);
  4119. // Extra tab fields
  4120. setMangleFieldVal('nth', r.nth, false);
  4121. setMangleFieldVal('connlimit', r.connection_limit, false);
  4122. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4123. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4124. setMangleFieldVal('hotspot', r.hotspot, false);
  4125. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4126. setMangleFieldVal('limit', r.limit, false);
  4127. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4128. setMangleFieldVal('time', r.time, false);
  4129. setMangleFieldVal('psd', r.psd, false);
  4130. // Action fields
  4131. if (r.jump_target) {
  4132. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4133. if (jtEl) jtEl.value = r.jump_target;
  4134. }
  4135. if (r.address_list) {
  4136. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4137. if (alEl) alEl.value = r.address_list;
  4138. }
  4139. if (r.address_list_timeout) {
  4140. const toEl = document.getElementById('mangle-modal-action-timeout');
  4141. if (toEl) toEl.value = r.address_list_timeout;
  4142. }
  4143. setMangleFieldVal('logprefix', r.log_prefix, false);
  4144. // Statistics
  4145. const bEl = document.getElementById('mangle-stat-bytes');
  4146. const pEl = document.getElementById('mangle-stat-packets');
  4147. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4148. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4149. state.mangleLastBytes = r.bytes || 0;
  4150. state.mangleLastPackets = r.packets || 0;
  4151. state.mangleLastTimestamp = Date.now();
  4152. state.mangleStatRateHistory = new Array(30).fill(0);
  4153. state.mangleStatPktHistory = new Array(30).fill(0);
  4154. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4155. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4156. toggleMangleActionFields();
  4157. document.getElementById('mangle-modal').classList.remove('hidden');
  4158. }
  4159. function closeMangleModal() {
  4160. stopMangleStatPolling();
  4161. document.getElementById('mangle-modal').classList.add('hidden');
  4162. }
  4163. function copyMangleRule() {
  4164. document.getElementById('mangle-modal-id').value = '';
  4165. const badge = document.getElementById('mangle-modal-badge');
  4166. if (badge) badge.innerText = 'New...';
  4167. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4168. }
  4169. function resetCurrentMangleRuleCounters() {
  4170. state.mangleStatRateHistory = new Array(30).fill(0);
  4171. state.mangleStatPktHistory = new Array(30).fill(0);
  4172. state.mangleLastBytes = 0;
  4173. state.mangleLastPackets = 0;
  4174. state.mangleLastTimestamp = Date.now();
  4175. const bEl = document.getElementById('mangle-stat-bytes');
  4176. const pEl = document.getElementById('mangle-stat-packets');
  4177. const rEl = document.getElementById('mangle-stat-rate');
  4178. const prEl = document.getElementById('mangle-stat-pktrate');
  4179. if (bEl) bEl.value = '0 B';
  4180. if (pEl) pEl.value = '0';
  4181. if (rEl) rEl.value = '0 bps';
  4182. if (prEl) prEl.value = '0 p/s';
  4183. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4184. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4185. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4186. }
  4187. async function applyMangleRule(closeAfter = false) {
  4188. const id = document.getElementById('mangle-modal-id').value;
  4189. const chain = document.getElementById('mangle-modal-chain').value;
  4190. const action = document.getElementById('mangle-modal-action').value;
  4191. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4192. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4193. const src = getMangleFieldVal('src', true);
  4194. const dst = getMangleFieldVal('dst', true);
  4195. const srclist = getMangleFieldVal('srclist', true);
  4196. const dstlist = getMangleFieldVal('dstlist', true);
  4197. const srcgeo = getMangleFieldVal('srcgeo', true);
  4198. const dstgeo = getMangleFieldVal('dstgeo', true);
  4199. const proto = getMangleFieldVal('proto', true);
  4200. const sport = getMangleFieldVal('sport', true);
  4201. const dport = getMangleFieldVal('dport', true);
  4202. const anyport = getMangleFieldVal('anyport', true);
  4203. const iniface = getMangleFieldVal('iniface', true);
  4204. const outiface = getMangleFieldVal('outiface', true);
  4205. const inifacelist = getMangleFieldVal('inifacelist', true);
  4206. const outifacelist = getMangleFieldVal('outifacelist', true);
  4207. const pktmark = getMangleFieldVal('pktmark', true);
  4208. const connmark = getMangleFieldVal('connmark', true);
  4209. const routingmark = getMangleFieldVal('routingmark', true);
  4210. const conntype = getMangleFieldVal('conntype', false);
  4211. const states = [];
  4212. const csBox = document.getElementById('mangle-field-cs');
  4213. if (csBox && !csBox.classList.contains('hidden')) {
  4214. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4215. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4216. });
  4217. }
  4218. const natStates = [];
  4219. const natBox = document.getElementById('mangle-field-natstate');
  4220. if (natBox && !natBox.classList.contains('hidden')) {
  4221. ['srcnat', 'dstnat'].forEach(s => {
  4222. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4223. });
  4224. }
  4225. const payload = {
  4226. id,
  4227. chain,
  4228. action,
  4229. protocol: proto || 'all',
  4230. src_address: src,
  4231. dst_address: dst,
  4232. src_port: sport,
  4233. dst_port: dport,
  4234. any_port: anyport,
  4235. in_interface: iniface,
  4236. out_interface: outiface,
  4237. in_interface_list: inifacelist,
  4238. out_interface_list: outifacelist,
  4239. packet_mark: pktmark,
  4240. connection_mark: connmark,
  4241. routing_mark: routingmark,
  4242. connection_type: conntype,
  4243. connection_state: states,
  4244. connection_nat_state: natStates,
  4245. src_address_list: srclist,
  4246. dst_address_list: dstlist,
  4247. src_geoip: srcgeo,
  4248. dst_geoip: dstgeo,
  4249. comment,
  4250. disabled: !enabled,
  4251. // Advanced tab
  4252. layer7_protocol: getMangleFieldVal('layer7', false),
  4253. content: getMangleFieldVal('content', false),
  4254. connection_bytes: getMangleFieldVal('connbytes', false),
  4255. connection_rate: getMangleFieldVal('connrate', false),
  4256. pcc: getMangleFieldVal('pcc', false),
  4257. src_mac_address: getMangleFieldVal('srcmac', true),
  4258. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4259. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4260. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4261. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4262. ipsec_policy: getMangleFieldVal('ipsec', false),
  4263. tls_host: getMangleFieldVal('tlshost', false),
  4264. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4265. priority: getMangleFieldVal('priority', false),
  4266. dscp: getMangleFieldVal('dscp', false),
  4267. tcp_mss: getMangleFieldVal('tcpmss', false),
  4268. tos: document.getElementById('mangle-val-tos')?.value || '',
  4269. packet_size: getMangleFieldVal('pktsize', false),
  4270. random: getMangleFieldVal('random', false),
  4271. tcp_flags: getMangleFieldVal('tcpflags', false),
  4272. icmp_options: getMangleFieldVal('icmpoptions', false),
  4273. ipv4_options: getMangleFieldVal('ipv4options', false),
  4274. ttl: getMangleFieldVal('ttl', false),
  4275. // Extra tab
  4276. nth: getMangleFieldVal('nth', false),
  4277. connection_limit: getMangleFieldVal('connlimit', false),
  4278. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4279. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4280. hotspot: getMangleFieldVal('hotspot', false),
  4281. ip_fragment: getMangleFieldVal('ipfragment', false),
  4282. limit: getMangleFieldVal('limit', false),
  4283. dst_limit: getMangleFieldVal('dstlimit', false),
  4284. time: getMangleFieldVal('time', false),
  4285. psd: getMangleFieldVal('psd', false),
  4286. // Action tab
  4287. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4288. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4289. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4290. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4291. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4292. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4293. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4294. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4295. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4296. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4297. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4298. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4299. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4300. log: document.getElementById('mangle-modal-log')?.checked || false,
  4301. log_prefix: getMangleFieldVal('logprefix', false)
  4302. };
  4303. try {
  4304. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4305. method: 'POST',
  4306. headers: { 'Content-Type': 'application/json' },
  4307. body: JSON.stringify(payload)
  4308. });
  4309. if (res.ok) {
  4310. const data = await res.json();
  4311. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4312. loadFirewall(false);
  4313. if (closeAfter) {
  4314. closeMangleModal();
  4315. } else {
  4316. if (data.id) {
  4317. document.getElementById('mangle-modal-id').value = data.id;
  4318. const badge = document.getElementById('mangle-modal-badge');
  4319. if (badge) badge.innerText = `#${data.id}`;
  4320. }
  4321. }
  4322. } else {
  4323. const err = await res.json();
  4324. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4325. }
  4326. } catch (err) {
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. }
  4330. function submitSaveMangleRule(e) {
  4331. if (e && e.preventDefault) e.preventDefault();
  4332. return applyMangleRule(true);
  4333. }
  4334. function startMangleStatPolling() {
  4335. stopMangleStatPolling();
  4336. pollMangleRuleStats();
  4337. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4338. }
  4339. function stopMangleStatPolling() {
  4340. if (state.mangleStatInterval) {
  4341. clearInterval(state.mangleStatInterval);
  4342. state.mangleStatInterval = null;
  4343. }
  4344. }
  4345. async function pollMangleRuleStats() {
  4346. const id = document.getElementById('mangle-modal-id')?.value;
  4347. if (!id) {
  4348. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4349. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4350. return;
  4351. }
  4352. try {
  4353. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4354. if (!res.ok) return;
  4355. const rules = await res.json();
  4356. const r = rules.find(x => x.id === id);
  4357. if (!r) return;
  4358. const now = Date.now();
  4359. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4360. state.mangleLastTimestamp = now;
  4361. const curBytes = r.bytes || 0;
  4362. const curPackets = r.packets || 0;
  4363. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4364. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4365. state.mangleLastBytes = curBytes;
  4366. state.mangleLastPackets = curPackets;
  4367. const rateBps = Math.round((deltaBytes * 8) / dt);
  4368. const ratePkt = Math.round(deltaPkts / dt);
  4369. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4370. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4371. state.mangleStatRateHistory.push(rateBps);
  4372. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4373. state.mangleStatPktHistory.push(ratePkt);
  4374. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4375. const bEl = document.getElementById('mangle-stat-bytes');
  4376. const pEl = document.getElementById('mangle-stat-packets');
  4377. const rEl = document.getElementById('mangle-stat-rate');
  4378. const prEl = document.getElementById('mangle-stat-pktrate');
  4379. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4380. if (pEl) pEl.value = curPackets.toLocaleString();
  4381. if (rEl) rEl.value = formatBps(rateBps);
  4382. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4383. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4384. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4385. } catch (e) {
  4386. console.error('Error polling Mangle rule stats', e);
  4387. }
  4388. }
  4389. async function moveMangleRule(id, dir) {
  4390. try {
  4391. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4392. method: 'POST',
  4393. headers: { 'Content-Type': 'application/json' },
  4394. body: JSON.stringify({ direction: dir })
  4395. });
  4396. if (res.ok) loadFirewall(false);
  4397. } catch (err) {
  4398. showToast('Error', err.message, 'error');
  4399. }
  4400. }
  4401. async function toggleMangleRuleState(id, disabled) {
  4402. try {
  4403. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4404. method: 'POST',
  4405. headers: { 'Content-Type': 'application/json' },
  4406. body: JSON.stringify({ disabled })
  4407. });
  4408. if (res.ok) loadFirewall(false);
  4409. } catch (err) {
  4410. showToast('Error', err.message, 'error');
  4411. }
  4412. }
  4413. async function deleteMangleRule(id) {
  4414. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4415. try {
  4416. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4417. if (res.ok) {
  4418. showToast('Deleted', 'Mangle rule removed', 'success');
  4419. loadFirewall(false);
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // ----------------- Address Lists -----------------
  4426. function renderAddressLists() {
  4427. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4428. const tbody = document.getElementById('addrlist-table-body');
  4429. const empty = document.getElementById('addrlist-empty');
  4430. if (!tbody) return;
  4431. tbody.innerHTML = '';
  4432. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4433. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4434. // Update filter select
  4435. const sel = document.getElementById('addrlist-filter-name');
  4436. if (sel) {
  4437. const cur = sel.value;
  4438. sel.innerHTML = '<option value="">All Lists</option>';
  4439. const set = new Set((state.addressLists || []).map(a => a.name));
  4440. set.forEach(n => {
  4441. const opt = document.createElement('option');
  4442. opt.value = n;
  4443. opt.innerText = n;
  4444. if (n === cur) opt.selected = true;
  4445. sel.appendChild(opt);
  4446. });
  4447. }
  4448. if (entries.length === 0) {
  4449. empty?.classList.remove('hidden');
  4450. return;
  4451. }
  4452. empty?.classList.add('hidden');
  4453. entries.forEach((e, idx) => {
  4454. const tr = document.createElement('tr');
  4455. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4456. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4457. tr.innerHTML = `
  4458. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4459. <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>
  4460. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4461. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4463. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4464. <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>
  4465. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4466. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4467. </td>
  4468. `;
  4469. tbody.appendChild(tr);
  4470. });
  4471. populateCommonAddrListDatalist();
  4472. }
  4473. function openAddAddrListModal() {
  4474. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4475. document.getElementById('addrlist-modal-id').value = '';
  4476. document.getElementById('addrlist-modal-name').value = '';
  4477. document.getElementById('addrlist-modal-addr').value = '';
  4478. document.getElementById('addrlist-modal-comment').value = '';
  4479. document.getElementById('addrlist-modal-disabled').checked = false;
  4480. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4481. if (submitBtn) submitBtn.innerText = 'Add to List';
  4482. document.getElementById('addrlist-modal').classList.remove('hidden');
  4483. }
  4484. function openEditAddrListModal(id) {
  4485. const e = (state.addressLists || []).find(item => item.id === id);
  4486. if (!e) return;
  4487. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4488. document.getElementById('addrlist-modal-id').value = e.id;
  4489. document.getElementById('addrlist-modal-name').value = e.name;
  4490. document.getElementById('addrlist-modal-addr').value = e.address;
  4491. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4492. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4493. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4494. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4495. document.getElementById('addrlist-modal').classList.remove('hidden');
  4496. }
  4497. function closeAddrListModal() {
  4498. document.getElementById('addrlist-modal').classList.add('hidden');
  4499. }
  4500. async function submitSaveAddrList(e) {
  4501. e.preventDefault();
  4502. const id = document.getElementById('addrlist-modal-id').value;
  4503. const name = document.getElementById('addrlist-modal-name').value.trim();
  4504. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4505. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4506. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4507. try {
  4508. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4509. method: 'POST',
  4510. headers: { 'Content-Type': 'application/json' },
  4511. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4512. });
  4513. if (res.ok) {
  4514. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4515. closeAddrListModal();
  4516. loadFirewall(false);
  4517. } else {
  4518. const err = await res.json();
  4519. showToast('Error', err.message || 'Failed to save address list', 'error');
  4520. }
  4521. } catch (err) {
  4522. showToast('Error', err.message, 'error');
  4523. }
  4524. }
  4525. async function toggleAddrListState(id, disabled) {
  4526. try {
  4527. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4528. method: 'POST',
  4529. headers: { 'Content-Type': 'application/json' },
  4530. body: JSON.stringify({ disabled })
  4531. });
  4532. if (res.ok) {
  4533. loadFirewall(false);
  4534. }
  4535. } catch (err) {
  4536. showToast('Error', err.message, 'error');
  4537. }
  4538. }
  4539. async function deleteAddrList(id) {
  4540. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4541. try {
  4542. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4543. if (res.ok) {
  4544. showToast('Deleted', 'Address list item removed', 'info');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- Geo-Location IP Management -----------------
  4552. async function loadGeoIP() {
  4553. try {
  4554. const [statusRes, countriesRes] = await Promise.all([
  4555. fetch(`${API_BASE}/firewall/geoip/status`),
  4556. fetch(`${API_BASE}/firewall/geoip/countries`)
  4557. ]);
  4558. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4559. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4560. updateGeoHeader();
  4561. renderGeoCountries();
  4562. } catch (err) {
  4563. console.error('Failed to load GeoIP:', err);
  4564. }
  4565. }
  4566. function getGeoUsageMap() {
  4567. const usage = {};
  4568. const checkRule = (r, type) => {
  4569. ['src_geoip', 'dst_geoip'].forEach(field => {
  4570. let val = (r && r[field]) || '';
  4571. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4572. if (code) {
  4573. if (!usage[code]) usage[code] = [];
  4574. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4575. if (!usage[code].includes(label)) usage[code].push(label);
  4576. }
  4577. });
  4578. };
  4579. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4580. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4581. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4582. return usage;
  4583. }
  4584. function updateGeoHeader() {
  4585. const s = state.geoStatus || {};
  4586. const statusBadge = document.getElementById('geo-status-badge');
  4587. if (statusBadge) {
  4588. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4589. statusBadge.className = s.auto_update
  4590. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4591. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4592. }
  4593. const intervalLabel = document.getElementById('geo-interval-label');
  4594. if (intervalLabel) {
  4595. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4596. }
  4597. const usageMap = getGeoUsageMap();
  4598. const inUseCount = Object.keys(usageMap).length;
  4599. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4600. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4601. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4602. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4603. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4604. if (lastSyncEl) {
  4605. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4606. const d = new Date(s.last_updated);
  4607. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4608. } else {
  4609. lastSyncEl.innerText = 'Never (Sync Pending)';
  4610. }
  4611. }
  4612. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4613. if (nextSyncEl) {
  4614. if (s.next_update && !s.next_update.startsWith('0001')) {
  4615. const d = new Date(s.next_update);
  4616. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4617. } else {
  4618. nextSyncEl.innerText = '-';
  4619. }
  4620. }
  4621. const badge = document.getElementById('fw-badge-geo');
  4622. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4623. }
  4624. function renderGeoCountries() {
  4625. const tbody = document.getElementById('geo-table-body');
  4626. const empty = document.getElementById('geo-empty');
  4627. if (!tbody) return;
  4628. tbody.innerHTML = '';
  4629. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4630. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4631. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4632. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4633. const usageMap = getGeoUsageMap();
  4634. const countries = (state.geoCountries || []).filter(c => {
  4635. const isUsed = !!usageMap[c.code];
  4636. if (inUseOnly && !isUsed) return false;
  4637. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4638. if (continent && c.continent !== continent) return false;
  4639. if (q) {
  4640. const matchCode = c.code.toLowerCase().includes(q);
  4641. const matchName = c.name.toLowerCase().includes(q);
  4642. if (!matchCode && !matchName) return false;
  4643. }
  4644. return true;
  4645. });
  4646. if (countries.length === 0) {
  4647. empty?.classList.remove('hidden');
  4648. return;
  4649. }
  4650. empty?.classList.add('hidden');
  4651. countries.forEach(c => {
  4652. const tr = document.createElement('tr');
  4653. const isUsed = !!usageMap[c.code];
  4654. const rulesUsing = usageMap[c.code] || [];
  4655. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4656. let statusHtml = '';
  4657. if (isUsed) {
  4658. 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>`;
  4659. } else if (c.subnet_count > 0) {
  4660. 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>';
  4661. } else {
  4662. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4663. }
  4664. tr.innerHTML = `
  4665. <td class="py-2.5 px-3 text-center">
  4666. <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'}">
  4667. ${c.code}
  4668. </span>
  4669. </td>
  4670. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4671. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4672. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4673. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4674. </td>
  4675. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4676. <td class="py-2.5 px-3">
  4677. ${statusHtml}
  4678. </td>
  4679. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4680. <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>
  4681. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4682. </td>
  4683. `;
  4684. tbody.appendChild(tr);
  4685. });
  4686. }
  4687. function quickFilterGeo(preset) {
  4688. const searchInput = document.getElementById('geo-search-input');
  4689. const continentSel = document.getElementById('geo-continent-filter');
  4690. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4691. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4692. if (searchInput) searchInput.value = '';
  4693. if (continentSel) continentSel.value = '';
  4694. if (inUseCheck) inUseCheck.checked = false;
  4695. if (cachedCheck) cachedCheck.checked = false;
  4696. if (preset === 'GR') {
  4697. if (searchInput) searchInput.value = 'Greece';
  4698. } else if (preset === 'Europe') {
  4699. if (continentSel) continentSel.value = 'Europe';
  4700. } else if (preset === 'HIGHRISK') {
  4701. if (searchInput) searchInput.value = 'China';
  4702. }
  4703. renderGeoCountries();
  4704. }
  4705. async function toggleGeoCountry(code, enabled) {
  4706. try {
  4707. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4708. method: 'POST',
  4709. headers: { 'Content-Type': 'application/json' },
  4710. body: JSON.stringify({ enabled })
  4711. });
  4712. if (res.ok) {
  4713. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4714. loadGeoIP();
  4715. } else {
  4716. const err = await res.json();
  4717. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. async function updateGeoCountry(code) {
  4724. try {
  4725. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4726. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4727. if (res.ok) {
  4728. const data = await res.json();
  4729. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4730. loadGeoIP();
  4731. } else {
  4732. const err = await res.json();
  4733. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4734. }
  4735. } catch (err) {
  4736. showToast('Error', err.message, 'error');
  4737. }
  4738. }
  4739. async function triggerGeoUpdateNow() {
  4740. const spinner = document.getElementById('geo-update-spinner');
  4741. if (spinner) spinner.classList.remove('hidden');
  4742. try {
  4743. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4744. if (res.ok) {
  4745. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4746. setTimeout(() => {
  4747. loadGeoIP();
  4748. if (spinner) spinner.classList.add('hidden');
  4749. }, 2500);
  4750. } else {
  4751. const err = await res.json();
  4752. showToast('Notice', err.message || 'Update in progress', 'info');
  4753. if (spinner) spinner.classList.add('hidden');
  4754. }
  4755. } catch (err) {
  4756. showToast('Error', err.message, 'error');
  4757. if (spinner) spinner.classList.add('hidden');
  4758. }
  4759. }
  4760. async function applyGeoPreset(preset) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4766. });
  4767. if (res.ok) {
  4768. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4769. loadGeoIP();
  4770. }
  4771. } catch (err) {
  4772. showToast('Error', err.message, 'error');
  4773. }
  4774. }
  4775. function openGeoIntervalModal() {
  4776. const s = state.geoStatus || {};
  4777. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4778. const sel = document.getElementById('geo-cfg-interval');
  4779. const customBox = document.getElementById('geo-cfg-custom-box');
  4780. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4781. const curHours = s.interval_hours || 24;
  4782. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4783. if (matchOption) {
  4784. sel.value = String(curHours);
  4785. customBox.classList.add('hidden');
  4786. } else {
  4787. sel.value = 'custom';
  4788. customHoursInput.value = curHours;
  4789. customBox.classList.remove('hidden');
  4790. }
  4791. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4792. }
  4793. function closeGeoIntervalModal() {
  4794. document.getElementById('geo-interval-modal').classList.add('hidden');
  4795. }
  4796. function toggleCustomGeoInterval() {
  4797. const val = document.getElementById('geo-cfg-interval').value;
  4798. const customBox = document.getElementById('geo-cfg-custom-box');
  4799. if (val === 'custom') {
  4800. customBox.classList.remove('hidden');
  4801. } else {
  4802. customBox.classList.add('hidden');
  4803. }
  4804. }
  4805. async function submitGeoIntervalSettings(e) {
  4806. e.preventDefault();
  4807. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4808. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4809. let hours = 24;
  4810. if (intervalVal === 'custom') {
  4811. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4812. } else {
  4813. hours = parseInt(intervalVal, 10) || 24;
  4814. }
  4815. try {
  4816. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4817. method: 'POST',
  4818. headers: { 'Content-Type': 'application/json' },
  4819. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4820. });
  4821. if (res.ok) {
  4822. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4823. closeGeoIntervalModal();
  4824. loadGeoIP();
  4825. } else {
  4826. const err = await res.json();
  4827. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4828. }
  4829. } catch (err) {
  4830. showToast('Error', err.message, 'error');
  4831. }
  4832. }
  4833. async function viewGeoSubnets(code, name) {
  4834. if (!name) {
  4835. const found = (state.geoCountries || []).find(x => x.code === code);
  4836. name = found ? found.name : code;
  4837. }
  4838. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4839. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4840. const listEl = document.getElementById('geo-subnets-list');
  4841. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4842. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4845. if (res.ok) {
  4846. const data = await res.json();
  4847. const subnets = data.subnets || [];
  4848. if (subnets.length === 0) {
  4849. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4850. } else {
  4851. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4852. }
  4853. } else {
  4854. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4855. }
  4856. } catch (err) {
  4857. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4858. }
  4859. }
  4860. function closeGeoSubnetsModal() {
  4861. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4862. }
  4863. // ----------------- Active Connections Tracking -----------------
  4864. async function loadConnections() {
  4865. try {
  4866. const res = await fetch(`${API_BASE}/firewall/connections`);
  4867. const data = await res.json();
  4868. state.connections = Array.isArray(data) ? data : [];
  4869. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4870. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4871. renderConnections();
  4872. } catch (err) {
  4873. console.error('Failed to load connections:', err);
  4874. }
  4875. }
  4876. function renderConnections() {
  4877. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4878. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4879. const tbody = document.getElementById('conns-table-body');
  4880. const empty = document.getElementById('conns-empty');
  4881. if (!tbody) return;
  4882. tbody.innerHTML = '';
  4883. const conns = (state.connections || []).filter(c => {
  4884. if (protoFilter && c.protocol !== protoFilter) return false;
  4885. if (search) {
  4886. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4887. if (!line.includes(search)) return false;
  4888. }
  4889. return true;
  4890. });
  4891. if (conns.length === 0) {
  4892. empty?.classList.remove('hidden');
  4893. return;
  4894. }
  4895. empty?.classList.add('hidden');
  4896. conns.slice(0, 150).forEach(c => {
  4897. const tr = document.createElement('tr');
  4898. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4899. let stateColor = 'text-slate-400';
  4900. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4901. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4902. tr.innerHTML = `
  4903. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4904. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4905. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4906. <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>
  4907. <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>
  4908. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4909. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4910. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4911. <td class="py-2.5 px-3 text-right font-sans">
  4912. <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>
  4913. </td>
  4914. `;
  4915. tbody.appendChild(tr);
  4916. });
  4917. }
  4918. async function killConnection(protocol, src, sport, dst, dport) {
  4919. try {
  4920. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4921. method: 'POST',
  4922. headers: { 'Content-Type': 'application/json' },
  4923. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4924. });
  4925. if (res.ok) {
  4926. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4927. loadConnections();
  4928. }
  4929. } catch (err) {
  4930. showToast('Error', err.message, 'error');
  4931. }
  4932. }
  4933. async function resetFirewallCounters() {
  4934. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4935. try {
  4936. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4937. if (res.ok) {
  4938. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4939. loadFirewall(false);
  4940. }
  4941. } catch (err) {
  4942. showToast('Error', err.message, 'error');
  4943. }
  4944. }
  4945. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4946. function switchRoutesSubTab(tab) {
  4947. state.routesSubTab = tab;
  4948. const tabs = ['routes', 'rules', 'tables'];
  4949. tabs.forEach(t => {
  4950. const panel = document.getElementById(`routes-subtab-${t}`);
  4951. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4952. if (panel) {
  4953. if (t === tab) panel.classList.remove('hidden');
  4954. else panel.classList.add('hidden');
  4955. }
  4956. if (btn) {
  4957. if (t === tab) {
  4958. 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';
  4959. } else {
  4960. 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';
  4961. }
  4962. }
  4963. });
  4964. setTimeout(initTableSorting, 50);
  4965. }
  4966. async function loadRoutes() {
  4967. try {
  4968. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4969. fetch(`${API_BASE}/routes`),
  4970. fetch(`${API_BASE}/routing/rules`),
  4971. fetch(`${API_BASE}/routing/tables`)
  4972. ]);
  4973. if (routesRes.ok) state.routes = await routesRes.json();
  4974. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4975. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4976. const bRoutes = document.getElementById('routes-badge-routes');
  4977. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4978. const showSystem = document.getElementById('prule-show-system')?.checked;
  4979. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  4980. const bRules = document.getElementById('routes-badge-rules');
  4981. if (bRules) bRules.innerText = userRules.length;
  4982. const bTables = document.getElementById('routes-badge-tables');
  4983. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4984. const bRoutesCount = document.getElementById('badge-routes-count');
  4985. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4986. renderRoutesList();
  4987. renderPolicyRules();
  4988. renderRoutingTables();
  4989. } catch (err) {
  4990. console.error('Failed to load routing:', err);
  4991. }
  4992. }
  4993. function renderRoutesList() {
  4994. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4995. const tbody = document.getElementById('routes-table-body');
  4996. const empty = document.getElementById('routes-empty');
  4997. if (!tbody) return;
  4998. tbody.innerHTML = '';
  4999. // Update table filter select
  5000. const sel = document.getElementById('routes-filter-table');
  5001. if (sel) {
  5002. const cur = sel.value;
  5003. sel.innerHTML = '<option value="">All Tables</option>';
  5004. (state.routingTables || []).forEach(t => {
  5005. const opt = document.createElement('option');
  5006. opt.value = t.name;
  5007. opt.innerText = t.name;
  5008. if (t.name === cur) opt.selected = true;
  5009. sel.appendChild(opt);
  5010. });
  5011. }
  5012. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5013. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5014. if (routes.length === 0) {
  5015. empty?.classList.remove('hidden');
  5016. return;
  5017. }
  5018. empty?.classList.add('hidden');
  5019. routes.forEach(r => {
  5020. const tr = document.createElement('tr');
  5021. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5022. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5023. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5024. let flags = '';
  5025. if (r.dynamic) flags += 'D';
  5026. if (r.active) flags += 'A';
  5027. if (r.connect) flags += 'C';
  5028. if (r.static) flags += 'S';
  5029. if (r.disabled) flags += 'X';
  5030. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5031. tr.innerHTML = `
  5032. <td class="py-2.5 px-3 text-center">
  5033. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${r.active ? 'text-cyan-400 border border-cyan-800/40' : 'text-slate-500'}">
  5034. ${flags || '-'}
  5035. </span>
  5036. </td>
  5037. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5038. <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>
  5039. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5040. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5041. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5042. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5043. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5044. ${r.static ? `
  5045. <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>
  5046. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5047. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5048. ` : `
  5049. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5050. `}
  5051. </td>
  5052. `;
  5053. tbody.appendChild(tr);
  5054. });
  5055. }
  5056. function openAddRouteModal() {
  5057. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5058. document.getElementById('route-modal-id').value = '';
  5059. document.getElementById('route-modal-old-dst').value = '';
  5060. document.getElementById('route-modal-old-gw').value = '';
  5061. document.getElementById('route-modal-old-distance').value = '';
  5062. document.getElementById('route-modal-old-table').value = '';
  5063. document.getElementById('route-modal-old-iface').value = '';
  5064. const dstInput = document.getElementById('route-modal-dst');
  5065. const gwInput = document.getElementById('route-modal-gw');
  5066. const distInput = document.getElementById('route-modal-distance');
  5067. const ifaceSelect = document.getElementById('route-modal-iface');
  5068. const tableSelect = document.getElementById('route-modal-table');
  5069. const commentInput = document.getElementById('route-modal-comment');
  5070. const disCheck = document.getElementById('route-modal-disabled');
  5071. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5072. dstInput.disabled = false;
  5073. dstInput.value = '0.0.0.0/0';
  5074. gwInput.disabled = false;
  5075. gwInput.value = '';
  5076. distInput.disabled = false;
  5077. distInput.value = '1';
  5078. ifaceSelect.disabled = false;
  5079. tableSelect.disabled = false;
  5080. commentInput.disabled = false;
  5081. commentInput.value = '';
  5082. disCheck.disabled = false;
  5083. disCheck.checked = false;
  5084. if (saveBtn) saveBtn.classList.remove('hidden');
  5085. populateInterfaceSelect('route-modal-iface');
  5086. // Populate tables
  5087. tableSelect.innerHTML = '';
  5088. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5089. const opt = document.createElement('option');
  5090. opt.value = t.name;
  5091. opt.innerText = t.name;
  5092. if (t.name === 'main') opt.selected = true;
  5093. tableSelect.appendChild(opt);
  5094. });
  5095. document.getElementById('route-modal').classList.remove('hidden');
  5096. }
  5097. function openEditRouteModal(id) {
  5098. const r = (state.routes || []).find(route => route.id === id);
  5099. if (!r) return;
  5100. const isStatic = !!r.static;
  5101. document.getElementById('route-modal-title').innerText = isStatic
  5102. ? `Edit Route: ${r.dst_address}`
  5103. : `Route Properties (Read Only): ${r.dst_address}`;
  5104. document.getElementById('route-modal-id').value = r.id;
  5105. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5106. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5107. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5108. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5109. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5110. const dstInput = document.getElementById('route-modal-dst');
  5111. const gwInput = document.getElementById('route-modal-gw');
  5112. const distInput = document.getElementById('route-modal-distance');
  5113. const ifaceSelect = document.getElementById('route-modal-iface');
  5114. const tableSelect = document.getElementById('route-modal-table');
  5115. const commentInput = document.getElementById('route-modal-comment');
  5116. const disCheck = document.getElementById('route-modal-disabled');
  5117. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5118. dstInput.value = r.dst_address;
  5119. gwInput.value = r.gateway || '';
  5120. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5121. commentInput.value = r.comment || '';
  5122. disCheck.checked = !!r.disabled;
  5123. dstInput.disabled = !isStatic;
  5124. gwInput.disabled = !isStatic;
  5125. distInput.disabled = !isStatic;
  5126. ifaceSelect.disabled = !isStatic;
  5127. tableSelect.disabled = !isStatic;
  5128. commentInput.disabled = !isStatic;
  5129. disCheck.disabled = !isStatic;
  5130. if (saveBtn) {
  5131. if (isStatic) {
  5132. saveBtn.classList.remove('hidden');
  5133. } else {
  5134. saveBtn.classList.add('hidden');
  5135. }
  5136. }
  5137. populateInterfaceSelect('route-modal-iface', r.interface);
  5138. tableSelect.innerHTML = '';
  5139. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5140. const opt = document.createElement('option');
  5141. opt.value = t.name;
  5142. opt.innerText = t.name;
  5143. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5144. tableSelect.appendChild(opt);
  5145. });
  5146. document.getElementById('route-modal').classList.remove('hidden');
  5147. }
  5148. function closeRouteModal() {
  5149. document.getElementById('route-modal').classList.add('hidden');
  5150. }
  5151. async function submitSaveRoute(e) {
  5152. e.preventDefault();
  5153. const id = document.getElementById('route-modal-id').value;
  5154. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5155. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5156. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5157. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5158. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5159. const dst = document.getElementById('route-modal-dst').value.trim();
  5160. const gw = document.getElementById('route-modal-gw').value.trim();
  5161. const table = document.getElementById('route-modal-table').value;
  5162. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5163. const iface = document.getElementById('route-modal-iface').value;
  5164. const comment = document.getElementById('route-modal-comment').value.trim();
  5165. const disabled = document.getElementById('route-modal-disabled').checked;
  5166. if (!dst) {
  5167. showToast('Error', 'Destination address is required', 'error');
  5168. return;
  5169. }
  5170. if (!gw && !iface) {
  5171. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5172. return;
  5173. }
  5174. const payload = {
  5175. id,
  5176. old_dst_address: oldDst,
  5177. old_gateway: oldGw,
  5178. old_routing_table: oldTable,
  5179. old_interface: oldIface,
  5180. dst_address: dst,
  5181. gateway: gw || iface,
  5182. routing_table: table,
  5183. distance,
  5184. interface: iface,
  5185. comment,
  5186. disabled
  5187. };
  5188. if (oldDistStr !== undefined && oldDistStr !== '') {
  5189. payload.old_distance = parseInt(oldDistStr, 10);
  5190. }
  5191. try {
  5192. const res = await fetch(`${API_BASE}/routes`, {
  5193. method: 'POST',
  5194. headers: { 'Content-Type': 'application/json' },
  5195. body: JSON.stringify(payload)
  5196. });
  5197. if (res.ok) {
  5198. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5199. closeRouteModal();
  5200. loadRoutes();
  5201. } else {
  5202. const err = await res.json();
  5203. showToast('Error', err.message || 'Failed to save route', 'error');
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. async function toggleRouteState(id, disabled) {
  5210. try {
  5211. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5212. method: 'POST',
  5213. headers: { 'Content-Type': 'application/json' },
  5214. body: JSON.stringify({ disabled })
  5215. });
  5216. if (res.ok) loadRoutes();
  5217. } catch (err) {
  5218. showToast('Error', err.message, 'error');
  5219. }
  5220. }
  5221. async function deleteRoute(id) {
  5222. if (!confirm('Are you sure you want to delete this route?')) return;
  5223. try {
  5224. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5225. if (res.ok) {
  5226. showToast('Deleted', 'Route removed', 'success');
  5227. loadRoutes();
  5228. }
  5229. } catch (err) {
  5230. showToast('Error', err.message, 'error');
  5231. }
  5232. }
  5233. // ----------------- Policy Rules (/ip route rule) -----------------
  5234. function renderPolicyRules() {
  5235. const tbody = document.getElementById('rules-table-body');
  5236. const empty = document.getElementById('rules-empty');
  5237. if (!tbody) return;
  5238. tbody.innerHTML = '';
  5239. const showSystem = document.getElementById('prule-show-system')?.checked;
  5240. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5241. const countBadge = document.getElementById('rules-count-badge');
  5242. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5243. const bRules = document.getElementById('routes-badge-rules');
  5244. if (bRules) bRules.innerText = filtered.length;
  5245. if (filtered.length === 0) {
  5246. empty?.classList.remove('hidden');
  5247. return;
  5248. }
  5249. empty?.classList.add('hidden');
  5250. filtered.forEach(pr => {
  5251. const isSys = pr.is_default || pr.is_system;
  5252. const tr = document.createElement('tr');
  5253. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5254. tr.innerHTML = `
  5255. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5256. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5257. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5258. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5259. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5260. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5261. <td class="py-2.5 px-3 text-right font-sans">
  5262. ${!pr.is_default ? `
  5263. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5264. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5265. </td>
  5266. `;
  5267. tbody.appendChild(tr);
  5268. });
  5269. }
  5270. function openAddPolicyRuleModal() {
  5271. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5272. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5273. document.getElementById('prule-modal-mark').value = '';
  5274. document.getElementById('prule-modal-src').value = '';
  5275. document.getElementById('prule-modal-dst').value = '';
  5276. const sel = document.getElementById('prule-modal-table');
  5277. sel.innerHTML = '';
  5278. (state.routingTables || []).forEach(t => {
  5279. const opt = document.createElement('option');
  5280. opt.value = t.name;
  5281. opt.innerText = t.name;
  5282. sel.appendChild(opt);
  5283. });
  5284. document.getElementById('prule-modal').classList.remove('hidden');
  5285. }
  5286. function closePolicyRuleModal() {
  5287. document.getElementById('prule-modal').classList.add('hidden');
  5288. }
  5289. async function submitSavePolicyRule(e) {
  5290. e.preventDefault();
  5291. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5292. const mark = document.getElementById('prule-modal-mark').value.trim();
  5293. const src = document.getElementById('prule-modal-src').value.trim();
  5294. const dst = document.getElementById('prule-modal-dst').value.trim();
  5295. const table = document.getElementById('prule-modal-table').value;
  5296. const action = document.getElementById('prule-modal-action').value;
  5297. try {
  5298. const res = await fetch(`${API_BASE}/routing/rules`, {
  5299. method: 'POST',
  5300. headers: { 'Content-Type': 'application/json' },
  5301. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5302. });
  5303. if (res.ok) {
  5304. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5305. closePolicyRuleModal();
  5306. loadRoutes();
  5307. } else {
  5308. const err = await res.json();
  5309. showToast('Error', err.message, 'error');
  5310. }
  5311. } catch (err) {
  5312. showToast('Error', err.message, 'error');
  5313. }
  5314. }
  5315. async function deletePolicyRule(id) {
  5316. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5317. try {
  5318. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5319. if (res.ok) {
  5320. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5321. loadRoutes();
  5322. }
  5323. } catch (err) {
  5324. showToast('Error', err.message, 'error');
  5325. }
  5326. }
  5327. // ----------------- Routing Tables -----------------
  5328. function renderRoutingTables() {
  5329. const tbody = document.getElementById('tables-table-body');
  5330. if (!tbody) return;
  5331. tbody.innerHTML = '';
  5332. (state.routingTables || []).forEach(t => {
  5333. const tr = document.createElement('tr');
  5334. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5335. tr.innerHTML = `
  5336. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5337. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5338. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5339. `;
  5340. tbody.appendChild(tr);
  5341. });
  5342. }
  5343. function openAddTableModal() {
  5344. document.getElementById('table-modal-name').value = '';
  5345. document.getElementById('table-modal-id').value = '';
  5346. document.getElementById('table-modal-comment').value = '';
  5347. document.getElementById('table-modal').classList.remove('hidden');
  5348. }
  5349. function closeTableModal() {
  5350. document.getElementById('table-modal').classList.add('hidden');
  5351. }
  5352. async function submitSaveTable(e) {
  5353. e.preventDefault();
  5354. const name = document.getElementById('table-modal-name').value.trim();
  5355. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5356. const comment = document.getElementById('table-modal-comment').value.trim();
  5357. try {
  5358. const res = await fetch(`${API_BASE}/routing/tables`, {
  5359. method: 'POST',
  5360. headers: { 'Content-Type': 'application/json' },
  5361. body: JSON.stringify({ name, table_id: id, comment })
  5362. });
  5363. if (res.ok) {
  5364. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5365. closeTableModal();
  5366. loadRoutes();
  5367. } else {
  5368. const err = await res.json();
  5369. showToast('Error', err.message, 'error');
  5370. }
  5371. } catch (err) {
  5372. showToast('Error', err.message, 'error');
  5373. }
  5374. }
  5375. async function loadDebianConfig() {
  5376. const view = document.getElementById('debian-config-view');
  5377. view.innerText = 'Generating live configuration...';
  5378. try {
  5379. const res = await fetch(`${API_BASE}/debian/config`);
  5380. const data = await res.json();
  5381. view.innerText = data.content || '# Empty config';
  5382. } catch (err) {
  5383. view.innerText = 'Failed to generate Debian network config.';
  5384. }
  5385. }
  5386. async function saveDebianConfig() {
  5387. try {
  5388. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5389. const data = await res.json();
  5390. if (res.ok) {
  5391. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5392. loadDebianConfig();
  5393. }
  5394. } catch (err) {
  5395. showToast('Error', err.message, 'error');
  5396. }
  5397. }
  5398. function showToast(title, message, type = 'info') {
  5399. const container = document.getElementById('toast-container');
  5400. const toast = document.createElement('div');
  5401. const borderColors = {
  5402. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5403. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5404. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5405. };
  5406. 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}`;
  5407. toast.innerHTML = `
  5408. <div class="flex-1">
  5409. <div class="font-bold text-xs text-white">${title}</div>
  5410. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5411. </div>
  5412. `;
  5413. container.appendChild(toast);
  5414. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5415. setTimeout(() => {
  5416. toast.classList.add('opacity-0', 'translate-y-2');
  5417. setTimeout(() => toast.remove(), 300);
  5418. }, 4000);
  5419. }
  5420. function formatTraffic(bytesPerSec) {
  5421. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5422. const kb = bytesPerSec / 1024;
  5423. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5424. const mb = kb / 1024;
  5425. return `${mb.toFixed(2)} MB/s`;
  5426. }
  5427. function toggleSidebar() {
  5428. const sb = document.getElementById('sidebar');
  5429. sb.classList.toggle('-translate-x-full');
  5430. }
  5431. // ======================== EoIP (Ethernet over IP) ========================
  5432. async function loadEoIP(populate = true) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5435. const data = await res.json();
  5436. state.eoipTunnels = Array.isArray(data) ? data : [];
  5437. const badge = document.getElementById('eoip-count-badge');
  5438. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5439. const sideBadge = document.getElementById('badge-eoip-count');
  5440. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5441. renderEoIPTunnels();
  5442. } catch (err) {
  5443. console.error('Failed to load EoIP:', err);
  5444. }
  5445. }
  5446. function renderEoIPTunnels() {
  5447. const tbody = document.getElementById('eoip-table-body');
  5448. const empty = document.getElementById('eoip-empty');
  5449. if (!tbody) return;
  5450. tbody.innerHTML = '';
  5451. const tunnels = state.eoipTunnels || [];
  5452. if (tunnels.length === 0) {
  5453. empty?.classList.remove('hidden');
  5454. return;
  5455. }
  5456. empty?.classList.add('hidden');
  5457. tunnels.forEach(t => {
  5458. const tr = document.createElement('tr');
  5459. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5460. tr.innerHTML = `
  5461. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5462. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5463. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5464. <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>
  5465. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5466. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5467. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5468. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5469. <td class="py-2.5 px-3 font-mono text-[11px]">
  5470. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5471. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5472. </td>
  5473. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5474. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5475. <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>
  5476. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5477. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5478. </td>
  5479. `;
  5480. tbody.appendChild(tr);
  5481. });
  5482. }
  5483. function openAddEoIPModal() {
  5484. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5485. document.getElementById('eoip-modal-id').value = '';
  5486. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5487. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5488. document.getElementById('eoip-modal-remote').value = '';
  5489. document.getElementById('eoip-modal-ip').value = '';
  5490. document.getElementById('eoip-modal-local').value = '';
  5491. document.getElementById('eoip-modal-mac').value = '';
  5492. document.getElementById('eoip-modal-mtu').value = '1500';
  5493. document.getElementById('eoip-modal-comment').value = '';
  5494. document.getElementById('eoip-modal-clampmss').checked = true;
  5495. document.getElementById('eoip-modal-disabled').checked = false;
  5496. document.getElementById('eoip-modal').classList.remove('hidden');
  5497. }
  5498. function openEditEoIPModal(id) {
  5499. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5500. if (!t) return;
  5501. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5502. document.getElementById('eoip-modal-id').value = t.id;
  5503. document.getElementById('eoip-modal-name').value = t.name;
  5504. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5505. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5506. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5507. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5508. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5509. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5510. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5511. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5512. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5513. document.getElementById('eoip-modal').classList.remove('hidden');
  5514. }
  5515. function closeEoIPModal() {
  5516. document.getElementById('eoip-modal').classList.add('hidden');
  5517. }
  5518. async function submitSaveEoIP(e) {
  5519. e.preventDefault();
  5520. const id = document.getElementById('eoip-modal-id').value;
  5521. const name = document.getElementById('eoip-modal-name').value.trim();
  5522. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5523. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5524. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5525. const local = document.getElementById('eoip-modal-local').value.trim();
  5526. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5527. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5528. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5529. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5530. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5531. try {
  5532. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5533. method: 'POST',
  5534. headers: { 'Content-Type': 'application/json' },
  5535. body: JSON.stringify({
  5536. id,
  5537. name,
  5538. tunnel_id: tunnelId,
  5539. remote_address: remote,
  5540. ip_address: ipAddress,
  5541. local_address: local,
  5542. mac_address: mac,
  5543. mtu,
  5544. clamp_mss: clampMss,
  5545. comment,
  5546. disabled
  5547. })
  5548. });
  5549. if (res.ok) {
  5550. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5551. closeEoIPModal();
  5552. loadEoIP(false);
  5553. fetchData(false);
  5554. } else {
  5555. const err = await res.json();
  5556. showToast('Error', err.message, 'error');
  5557. }
  5558. } catch (err) {
  5559. showToast('Error', err.message, 'error');
  5560. }
  5561. }
  5562. async function toggleEoIPState(id, disabled) {
  5563. try {
  5564. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5565. method: 'POST',
  5566. headers: { 'Content-Type': 'application/json' },
  5567. body: JSON.stringify({ disabled })
  5568. });
  5569. if (res.ok) {
  5570. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5571. loadEoIP(false);
  5572. fetchData(false);
  5573. }
  5574. } catch (err) {
  5575. showToast('Error', err.message, 'error');
  5576. }
  5577. }
  5578. async function deleteEoIP(id) {
  5579. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5580. try {
  5581. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5582. if (res.ok) {
  5583. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5584. loadEoIP(false);
  5585. fetchData(false);
  5586. }
  5587. } catch (err) {
  5588. showToast('Error', err.message, 'error');
  5589. }
  5590. }
  5591. // ======================== PPP Central Hub & Servers ========================
  5592. function switchPPPSubTab(tab) {
  5593. state.pppSubTab = tab;
  5594. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5595. tabs.forEach(t => {
  5596. const panel = document.getElementById(`ppp-subtab-${t}`);
  5597. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5598. if (panel) {
  5599. if (t === tab) panel.classList.remove('hidden');
  5600. else panel.classList.add('hidden');
  5601. }
  5602. if (btn) {
  5603. if (t === tab) {
  5604. 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';
  5605. } else {
  5606. 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';
  5607. }
  5608. }
  5609. });
  5610. const addBtn = document.getElementById('ppp-primary-add-btn');
  5611. if (addBtn) {
  5612. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5613. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5614. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5615. else addBtn.innerHTML = '<span>Save Config</span>';
  5616. }
  5617. if (tab === 'active') loadPPPSessions();
  5618. }
  5619. function openCurrentPPPModal() {
  5620. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5621. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5622. else if (state.pppSubTab === 'active') loadPPPSessions();
  5623. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5624. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5625. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5626. }
  5627. async function loadPPP(populateDropdowns = true) {
  5628. await Promise.all([
  5629. loadPPPSecrets(),
  5630. loadPPPProfiles(),
  5631. loadPPPServers(),
  5632. loadPPPSessions()
  5633. ]);
  5634. }
  5635. async function loadPPPSecrets() {
  5636. try {
  5637. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5638. const data = await res.json();
  5639. state.pppSecrets = Array.isArray(data) ? data : [];
  5640. const b = document.getElementById('ppp-badge-secrets');
  5641. if (b) b.innerText = state.pppSecrets.length;
  5642. const b2 = document.getElementById('secrets-count-badge');
  5643. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5644. renderPPPSecrets();
  5645. } catch (err) {
  5646. console.error('Failed to load PPP secrets:', err);
  5647. }
  5648. }
  5649. function renderPPPSecrets() {
  5650. const tbody = document.getElementById('secrets-table-body');
  5651. const empty = document.getElementById('secrets-empty');
  5652. if (!tbody) return;
  5653. tbody.innerHTML = '';
  5654. const secrets = state.pppSecrets || [];
  5655. if (secrets.length === 0) {
  5656. empty?.classList.remove('hidden');
  5657. return;
  5658. }
  5659. empty?.classList.add('hidden');
  5660. secrets.forEach(s => {
  5661. const tr = document.createElement('tr');
  5662. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5663. tr.innerHTML = `
  5664. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5665. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5666. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5667. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5668. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5669. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5670. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5671. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5672. <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>
  5673. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5674. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5675. </td>
  5676. `;
  5677. tbody.appendChild(tr);
  5678. });
  5679. }
  5680. async function loadPPPProfiles() {
  5681. try {
  5682. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5683. const data = await res.json();
  5684. state.pppProfiles = Array.isArray(data) ? data : [];
  5685. const b = document.getElementById('ppp-badge-profiles');
  5686. if (b) b.innerText = state.pppProfiles.length;
  5687. const b2 = document.getElementById('profiles-count-badge');
  5688. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5689. // Populate profile selects across modals
  5690. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5691. selects.forEach(sid => {
  5692. const el = document.getElementById(sid);
  5693. if (!el) return;
  5694. const cur = el.value;
  5695. el.innerHTML = '';
  5696. state.pppProfiles.forEach(p => {
  5697. const opt = document.createElement('option');
  5698. opt.value = p.name;
  5699. opt.innerText = `${p.name} (${p.remote_address})`;
  5700. if (p.name === cur) opt.selected = true;
  5701. el.appendChild(opt);
  5702. });
  5703. });
  5704. renderPPPProfiles();
  5705. } catch (err) {
  5706. console.error('Failed to load PPP profiles:', err);
  5707. }
  5708. }
  5709. function renderPPPProfiles() {
  5710. const tbody = document.getElementById('profiles-table-body');
  5711. if (!tbody) return;
  5712. tbody.innerHTML = '';
  5713. (state.pppProfiles || []).forEach(p => {
  5714. const isDefault = p.name.startsWith('default');
  5715. const tr = document.createElement('tr');
  5716. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5717. tr.innerHTML = `
  5718. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5719. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5720. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5721. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5722. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5723. <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>
  5724. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5725. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5726. ${!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>`}
  5727. </td>
  5728. `;
  5729. tbody.appendChild(tr);
  5730. });
  5731. }
  5732. async function loadPPPServers() {
  5733. try {
  5734. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5735. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5736. fetch(`${API_BASE}/vpn/servers/pptp`),
  5737. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5738. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5739. ]);
  5740. if (pppoeRes.ok) {
  5741. state.pppoeServer = await pppoeRes.json();
  5742. const s = state.pppoeServer;
  5743. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5744. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5745. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5746. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5747. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5748. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5749. const pill = document.getElementById('pppoe-server-status-pill');
  5750. if (pill) {
  5751. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5752. 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';
  5753. }
  5754. setDotBadge('ppp-badge-pppoe-state', s.running);
  5755. }
  5756. if (pptpRes.ok) {
  5757. state.pptpServer = await pptpRes.json();
  5758. const s = state.pptpServer;
  5759. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5760. document.getElementById('pptp-server-port').value = s.port || 1723;
  5761. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5762. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5763. const pill = document.getElementById('pptp-server-status-pill');
  5764. if (pill) {
  5765. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5766. 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';
  5767. }
  5768. setDotBadge('ppp-badge-pptp-state', s.running);
  5769. }
  5770. if (l2tpRes.ok) {
  5771. state.l2tpServer = await l2tpRes.json();
  5772. const s = state.l2tpServer;
  5773. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5774. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5775. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5776. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5777. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5778. const pill = document.getElementById('l2tp-server-status-pill');
  5779. if (pill) {
  5780. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5781. 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';
  5782. }
  5783. setDotBadge('ppp-badge-l2tp-state', s.running);
  5784. }
  5785. if (ipsecRes.ok) {
  5786. state.ipsecServer = await ipsecRes.json();
  5787. const s = state.ipsecServer;
  5788. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5789. if (modalEn) modalEn.checked = !!s.enabled;
  5790. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5791. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5792. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5793. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5794. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5795. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5796. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5797. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5798. const pill = document.getElementById('modal-ipsec-server-status');
  5799. if (pill) {
  5800. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5801. 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';
  5802. }
  5803. }
  5804. } catch (err) {
  5805. console.error('Failed to load VPN servers:', err);
  5806. }
  5807. }
  5808. async function loadPPPSessions() {
  5809. try {
  5810. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5811. const data = await res.json();
  5812. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5813. const b = document.getElementById('ppp-badge-active');
  5814. if (b) b.innerText = state.pppActiveSessions.length;
  5815. const sideB = document.getElementById('badge-ppp-sessions');
  5816. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5817. renderPPPSessions();
  5818. } catch (err) {
  5819. console.error('Failed to load active PPP sessions:', err);
  5820. }
  5821. }
  5822. function renderPPPSessions() {
  5823. const tbody = document.getElementById('active-ppp-table-body');
  5824. const empty = document.getElementById('active-ppp-empty');
  5825. if (!tbody) return;
  5826. tbody.innerHTML = '';
  5827. const list = state.pppActiveSessions || [];
  5828. if (list.length === 0) {
  5829. empty?.classList.remove('hidden');
  5830. return;
  5831. }
  5832. empty?.classList.add('hidden');
  5833. list.forEach(s => {
  5834. const tr = document.createElement('tr');
  5835. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5836. tr.innerHTML = `
  5837. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5838. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5839. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5840. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5841. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5842. <td class="py-2.5 px-3 text-[11px]">
  5843. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5844. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5845. </td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function disconnectPPPSession(iface) {
  5854. if (!confirm(`Disconnect session ${iface}?`)) return;
  5855. try {
  5856. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5857. if (res.ok) {
  5858. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5859. loadPPPSessions();
  5860. }
  5861. } catch (err) {
  5862. showToast('Error', err.message, 'error');
  5863. }
  5864. }
  5865. // PPP Secret Modal handlers
  5866. function openAddPPPSecretModal() {
  5867. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5868. document.getElementById('secret-modal-id').value = '';
  5869. document.getElementById('secret-modal-name').value = '';
  5870. document.getElementById('secret-modal-password').value = '';
  5871. document.getElementById('secret-modal-service').value = 'any';
  5872. document.getElementById('secret-modal-profile').value = 'default';
  5873. document.getElementById('secret-modal-local').value = '';
  5874. document.getElementById('secret-modal-remote').value = '';
  5875. document.getElementById('secret-modal-comment').value = '';
  5876. document.getElementById('secret-modal-disabled').checked = false;
  5877. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5878. }
  5879. function openEditPPPSecretModal(id) {
  5880. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5881. if (!s) return;
  5882. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5883. document.getElementById('secret-modal-id').value = s.id;
  5884. document.getElementById('secret-modal-name').value = s.name;
  5885. document.getElementById('secret-modal-password').value = s.password;
  5886. document.getElementById('secret-modal-service').value = s.service || 'any';
  5887. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5888. document.getElementById('secret-modal-local').value = s.local_address || '';
  5889. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5890. document.getElementById('secret-modal-comment').value = s.comment || '';
  5891. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5892. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5893. }
  5894. function closePPPSecretModal() {
  5895. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5896. }
  5897. async function submitSavePPPSecret(e) {
  5898. e.preventDefault();
  5899. const id = document.getElementById('secret-modal-id').value;
  5900. const name = document.getElementById('secret-modal-name').value.trim();
  5901. const password = document.getElementById('secret-modal-password').value.trim();
  5902. const service = document.getElementById('secret-modal-service').value;
  5903. const profile = document.getElementById('secret-modal-profile').value;
  5904. const local = document.getElementById('secret-modal-local').value.trim();
  5905. const remote = document.getElementById('secret-modal-remote').value.trim();
  5906. const comment = document.getElementById('secret-modal-comment').value.trim();
  5907. const disabled = document.getElementById('secret-modal-disabled').checked;
  5908. try {
  5909. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5910. method: 'POST',
  5911. headers: { 'Content-Type': 'application/json' },
  5912. body: JSON.stringify({
  5913. id,
  5914. name,
  5915. password,
  5916. service,
  5917. profile,
  5918. local_address: local,
  5919. remote_address: remote,
  5920. comment,
  5921. disabled
  5922. })
  5923. });
  5924. if (res.ok) {
  5925. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5926. closePPPSecretModal();
  5927. loadPPPSecrets();
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.message, 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function togglePPPSecretState(id, disabled) {
  5937. try {
  5938. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5939. method: 'POST',
  5940. headers: { 'Content-Type': 'application/json' },
  5941. body: JSON.stringify({ disabled })
  5942. });
  5943. if (res.ok) {
  5944. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5945. loadPPPSecrets();
  5946. }
  5947. } catch (err) {
  5948. showToast('Error', err.message, 'error');
  5949. }
  5950. }
  5951. async function deletePPPSecret(id) {
  5952. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5953. try {
  5954. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5955. if (res.ok) {
  5956. showToast('Deleted', 'Secret account removed', 'success');
  5957. loadPPPSecrets();
  5958. }
  5959. } catch (err) {
  5960. showToast('Error', err.message, 'error');
  5961. }
  5962. }
  5963. // PPP Profile Modal handlers
  5964. function openAddPPPProfileModal() {
  5965. document.getElementById('profile-modal-name').value = '';
  5966. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5967. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5968. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5969. document.getElementById('profile-modal-encryption').value = 'required';
  5970. document.getElementById('profile-modal-onlyone').checked = true;
  5971. document.getElementById('profile-modal-comment').value = '';
  5972. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5973. }
  5974. function closePPPProfileModal() {
  5975. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5976. }
  5977. async function submitSavePPPProfile(e) {
  5978. e.preventDefault();
  5979. const name = document.getElementById('profile-modal-name').value.trim();
  5980. const local = document.getElementById('profile-modal-local').value.trim();
  5981. const remote = document.getElementById('profile-modal-remote').value.trim();
  5982. const dns = document.getElementById('profile-modal-dns').value.trim();
  5983. const enc = document.getElementById('profile-modal-encryption').value;
  5984. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5985. const comment = document.getElementById('profile-modal-comment').value.trim();
  5986. try {
  5987. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5988. method: 'POST',
  5989. headers: { 'Content-Type': 'application/json' },
  5990. body: JSON.stringify({
  5991. id: name,
  5992. name,
  5993. local_address: local,
  5994. remote_address: remote,
  5995. dns_servers: dns,
  5996. use_encryption: enc,
  5997. only_one: onlyone,
  5998. comment
  5999. })
  6000. });
  6001. if (res.ok) {
  6002. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6003. closePPPProfileModal();
  6004. loadPPPProfiles();
  6005. } else {
  6006. const err = await res.json();
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. } catch (err) {
  6010. showToast('Error', err.message, 'error');
  6011. }
  6012. }
  6013. async function deletePPPProfile(name) {
  6014. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6015. try {
  6016. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6017. if (res.ok) {
  6018. showToast('Deleted', 'Profile removed', 'success');
  6019. loadPPPProfiles();
  6020. } else {
  6021. const err = await res.json();
  6022. showToast('Error', err.message, 'error');
  6023. }
  6024. } catch (err) {
  6025. showToast('Error', err.message, 'error');
  6026. }
  6027. }
  6028. // Server Config submissions
  6029. async function savePPPoEServerConfig(e) {
  6030. e.preventDefault();
  6031. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6032. const name = document.getElementById('pppoe-server-name').value.trim();
  6033. const iface = document.getElementById('pppoe-server-iface').value;
  6034. const profile = document.getElementById('pppoe-server-profile').value;
  6035. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6036. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6037. try {
  6038. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6039. method: 'POST',
  6040. headers: { 'Content-Type': 'application/json' },
  6041. body: JSON.stringify({
  6042. enabled,
  6043. service_name: name,
  6044. interface: iface,
  6045. default_profile: profile,
  6046. max_mtu: mtu,
  6047. max_mru: mtu,
  6048. one_session_per_host: onesession
  6049. })
  6050. });
  6051. if (res.ok) {
  6052. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6053. loadPPPServers();
  6054. fetchData(false);
  6055. } else {
  6056. const err = await res.json();
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. async function savePPTPServerConfig(e) {
  6064. e.preventDefault();
  6065. const enabled = document.getElementById('pptp-server-enabled').checked;
  6066. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6067. const profile = document.getElementById('pptp-server-profile').value;
  6068. const mppe = document.getElementById('pptp-server-mppe').checked;
  6069. try {
  6070. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6071. method: 'POST',
  6072. headers: { 'Content-Type': 'application/json' },
  6073. body: JSON.stringify({
  6074. enabled,
  6075. port,
  6076. default_profile: profile,
  6077. require_mppe: mppe
  6078. })
  6079. });
  6080. if (res.ok) {
  6081. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6082. loadPPPServers();
  6083. fetchData(false);
  6084. } else {
  6085. const err = await res.json();
  6086. showToast('Error', err.message, 'error');
  6087. }
  6088. } catch (err) {
  6089. showToast('Error', err.message, 'error');
  6090. }
  6091. }
  6092. async function saveL2TPServerConfig(e) {
  6093. e.preventDefault();
  6094. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6095. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6096. const profile = document.getElementById('l2tp-server-profile').value;
  6097. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6098. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6099. try {
  6100. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6101. method: 'POST',
  6102. headers: { 'Content-Type': 'application/json' },
  6103. body: JSON.stringify({
  6104. enabled,
  6105. port,
  6106. default_profile: profile,
  6107. use_ipsec: useipsec,
  6108. ipsec_secret: psk
  6109. })
  6110. });
  6111. if (res.ok) {
  6112. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6113. loadPPPServers();
  6114. fetchData(false);
  6115. } else {
  6116. const err = await res.json();
  6117. showToast('Error', err.message, 'error');
  6118. }
  6119. } catch (err) {
  6120. showToast('Error', err.message, 'error');
  6121. }
  6122. }
  6123. // IPSec Server Modal
  6124. function openIPSecServerModal() {
  6125. loadPPPServers();
  6126. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6127. }
  6128. function closeIPSecServerModal() {
  6129. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6130. }
  6131. async function submitSaveIPSecServer(e) {
  6132. e.preventDefault();
  6133. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6134. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6135. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6136. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6137. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6138. try {
  6139. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6140. method: 'POST',
  6141. headers: { 'Content-Type': 'application/json' },
  6142. body: JSON.stringify({
  6143. enabled,
  6144. preshared_key: psk,
  6145. pool_address: pool,
  6146. dns_servers: dns,
  6147. local_subnet: subnet
  6148. })
  6149. });
  6150. if (res.ok) {
  6151. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6152. closeIPSecServerModal();
  6153. loadPPPServers();
  6154. fetchData(false);
  6155. } else {
  6156. const err = await res.json();
  6157. showToast('Error', err.message, 'error');
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // WireGuard Client Config Viewer
  6164. let currentWGClientConf = '';
  6165. async function openWGClientConfModal(iface, clientIP) {
  6166. try {
  6167. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6168. method: 'POST',
  6169. headers: { 'Content-Type': 'application/json' },
  6170. body: JSON.stringify({
  6171. interface: iface,
  6172. address: clientIP || '10.10.0.2/32',
  6173. dns: '1.1.1.1, 8.8.8.8'
  6174. })
  6175. });
  6176. if (res.ok) {
  6177. const data = await res.json();
  6178. currentWGClientConf = data.config;
  6179. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6180. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6181. } else {
  6182. const err = await res.json();
  6183. showToast('Error', err.message, 'error');
  6184. }
  6185. } catch (err) {
  6186. showToast('Error', err.message, 'error');
  6187. }
  6188. }
  6189. function closeWGClientConfModal() {
  6190. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6191. }
  6192. function copyWGClientConf() {
  6193. if (!currentWGClientConf) return;
  6194. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6195. }
  6196. function downloadWGClientConf() {
  6197. if (!currentWGClientConf) return;
  6198. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6199. const a = document.createElement('a');
  6200. a.href = URL.createObjectURL(blob);
  6201. a.download = 'wireguard-client.conf';
  6202. document.body.appendChild(a);
  6203. a.click();
  6204. document.body.removeChild(a);
  6205. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6206. }
  6207. // =========================================================================
  6208. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6209. // =========================================================================
  6210. state.activeDynSubTab = 'bgp-peers';
  6211. state.activeBgpSubTab = 'bgp-peers';
  6212. state.activeOspfSubTab = 'ospf-ifaces';
  6213. state.bgpInstance = null;
  6214. state.bgpPeers = [];
  6215. state.bgpNets = [];
  6216. state.bgpRoutes = [];
  6217. state.ospfInstance = null;
  6218. state.ospfInterfaces = [];
  6219. state.ospfAreas = [];
  6220. state.ospfNeighbors = [];
  6221. state.ospfRoutes = [];
  6222. function switchBgpSubTab(subTab) {
  6223. state.activeBgpSubTab = subTab;
  6224. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6225. tabs.forEach(t => {
  6226. const el = document.getElementById(`dyn-subtab-${t}`);
  6227. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6228. if (el) el.classList.toggle('hidden', t !== subTab);
  6229. if (btn) {
  6230. if (t === subTab) {
  6231. 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';
  6232. } else {
  6233. 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';
  6234. }
  6235. }
  6236. });
  6237. }
  6238. function switchOspfSubTab(subTab) {
  6239. state.activeOspfSubTab = subTab;
  6240. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  6241. tabs.forEach(t => {
  6242. const el = document.getElementById(`dyn-subtab-${t}`);
  6243. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  6244. if (el) el.classList.toggle('hidden', t !== subTab);
  6245. if (btn) {
  6246. if (t === subTab) {
  6247. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  6248. } else {
  6249. 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';
  6250. }
  6251. }
  6252. });
  6253. }
  6254. function switchDynSubTab(subTab) {
  6255. if (subTab.startsWith('bgp')) {
  6256. if (state.activeTab !== 'bgp') navigate('bgp');
  6257. switchBgpSubTab(subTab);
  6258. } else if (subTab.startsWith('ospf')) {
  6259. if (state.activeTab !== 'ospf') navigate('ospf');
  6260. switchOspfSubTab(subTab);
  6261. }
  6262. }
  6263. async function loadDynamicRouting(showToastMsg = false) {
  6264. try {
  6265. const fetchSafeJson = async (url) => {
  6266. try {
  6267. const r = await fetch(url);
  6268. return r.ok ? await r.json() : null;
  6269. } catch (e) {
  6270. return null;
  6271. }
  6272. };
  6273. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  6274. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6275. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6276. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6277. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6278. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6279. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  6280. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  6281. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6282. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6283. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  6284. fetchSafeJson(`${API_BASE}/routing/filters`)
  6285. ]);
  6286. if (sum) state.dynSummary = sum;
  6287. if (bgpInst) state.bgpInstance = bgpInst;
  6288. if (bgpPeers) state.bgpPeers = bgpPeers;
  6289. if (bgpNets) state.bgpNets = bgpNets;
  6290. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6291. if (ospfInst) state.ospfInstance = ospfInst;
  6292. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  6293. if (ospfAreas) state.ospfAreas = ospfAreas;
  6294. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6295. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  6296. if (filters) state.routingFilters = filters;
  6297. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6298. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6299. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6300. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6301. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  6302. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  6303. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6304. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6305. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  6306. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6307. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6308. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6309. } catch (err) {
  6310. console.error('Failed to load dynamic routing:', err);
  6311. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6312. }
  6313. }
  6314. function renderBgpStatusPill() {
  6315. const pill = document.getElementById('bgp-live-status-pill');
  6316. if (!pill) return;
  6317. const inst = state.bgpInstance;
  6318. if (!inst || !inst.enabled) {
  6319. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6320. pill.innerText = 'BGP DISABLED';
  6321. } else if (inst.running) {
  6322. 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';
  6323. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6324. } else {
  6325. 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';
  6326. pill.innerText = 'BGP STARTING...';
  6327. }
  6328. }
  6329. function renderBgpPeers() {
  6330. const tbody = document.getElementById('bgp-peers-table-body');
  6331. if (!tbody) return;
  6332. const empty = document.getElementById('bgp-peers-empty');
  6333. const countBadge = document.getElementById('bgp-peers-count-badge');
  6334. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6335. const peers = state.bgpPeers || [];
  6336. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6337. if (navBadge) navBadge.innerText = peers.length;
  6338. if (peers.length === 0) {
  6339. tbody.innerHTML = '';
  6340. if (empty) empty.classList.remove('hidden');
  6341. return;
  6342. }
  6343. if (empty) empty.classList.add('hidden');
  6344. tbody.innerHTML = peers.map(p => {
  6345. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6346. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6347. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6348. let stateBadge = '';
  6349. if (p.disabled) {
  6350. 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>';
  6351. } else if (p.state === 'Established') {
  6352. 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>';
  6353. } else if (p.state === 'Connect' || p.state === 'Active') {
  6354. 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>`;
  6355. } else {
  6356. 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>`;
  6357. }
  6358. return `
  6359. <tr class="hover:bg-slate-800/40 transition">
  6360. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6361. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6362. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6363. <td class="py-2.5 px-3">
  6364. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6365. ${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>`}
  6366. </td>
  6367. <td class="py-2.5 px-3">${stateBadge}</td>
  6368. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6369. <td class="py-2.5 px-3 text-slate-300">
  6370. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6371. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6372. </td>
  6373. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6374. ${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> ` : ''}
  6375. ${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>` : ''}
  6376. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6377. </td>
  6378. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6379. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6380. <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'}">
  6381. ${p.disabled ? 'Enable' : 'Disable'}
  6382. </button>
  6383. <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">
  6384. Edit
  6385. </button>
  6386. <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">
  6387. Delete
  6388. </button>
  6389. </td>
  6390. </tr>
  6391. `;
  6392. }).join('');
  6393. }
  6394. function renderBgpNetworks() {
  6395. const tbody = document.getElementById('bgp-nets-table-body');
  6396. if (!tbody) return;
  6397. const empty = document.getElementById('bgp-nets-empty');
  6398. const countBadge = document.getElementById('bgp-nets-count-badge');
  6399. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6400. const nets = state.bgpNets || [];
  6401. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6402. if (navBadge) navBadge.innerText = nets.length;
  6403. if (nets.length === 0) {
  6404. tbody.innerHTML = '';
  6405. if (empty) empty.classList.remove('hidden');
  6406. return;
  6407. }
  6408. if (empty) empty.classList.add('hidden');
  6409. tbody.innerHTML = nets.map(n => `
  6410. <tr class="hover:bg-slate-800/40 transition">
  6411. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6412. <td class="py-2.5 px-3">
  6413. ${n.disabled
  6414. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6415. : '<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>'}
  6416. </td>
  6417. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6418. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6419. <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">
  6420. Delete
  6421. </button>
  6422. </td>
  6423. </tr>
  6424. `).join('');
  6425. }
  6426. function renderBgpRoutes() {
  6427. const tbody = document.getElementById('bgp-routes-table-body');
  6428. if (!tbody) return;
  6429. const empty = document.getElementById('bgp-routes-empty');
  6430. const countBadge = document.getElementById('bgp-routes-count-badge');
  6431. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6432. const routes = state.bgpRoutes || [];
  6433. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6434. if (navBadge) navBadge.innerText = routes.length;
  6435. if (routes.length === 0) {
  6436. tbody.innerHTML = '';
  6437. if (empty) empty.classList.remove('hidden');
  6438. return;
  6439. }
  6440. if (empty) empty.classList.add('hidden');
  6441. tbody.innerHTML = routes.map(r => `
  6442. <tr class="hover:bg-slate-800/40 transition">
  6443. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6444. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6445. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6446. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6447. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6448. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6449. </tr>
  6450. `).join('');
  6451. }
  6452. function renderOspfStatusPill() {
  6453. const pill = document.getElementById('ospf-live-status-pill');
  6454. if (!pill) return;
  6455. const inst = state.ospfInstance;
  6456. if (!inst || !inst.enabled) {
  6457. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6458. pill.innerText = 'OSPF DISABLED';
  6459. } else if (inst.running) {
  6460. 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';
  6461. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  6462. } else {
  6463. 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';
  6464. pill.innerText = 'OSPF STARTING...';
  6465. }
  6466. }
  6467. function renderOspfInterfaces() {
  6468. const tbody = document.getElementById('ospf-ifaces-table-body');
  6469. if (!tbody) return;
  6470. const empty = document.getElementById('ospf-ifaces-empty');
  6471. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  6472. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  6473. const ifaces = state.ospfInterfaces || [];
  6474. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  6475. if (navBadge) navBadge.innerText = ifaces.length;
  6476. if (ifaces.length === 0) {
  6477. tbody.innerHTML = '';
  6478. if (empty) empty.classList.remove('hidden');
  6479. return;
  6480. }
  6481. if (empty) empty.classList.add('hidden');
  6482. tbody.innerHTML = ifaces.map(i => {
  6483. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6484. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  6485. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6486. return `
  6487. <tr class="hover:bg-slate-800/40 transition">
  6488. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  6489. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  6490. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  6491. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  6492. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  6493. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  6494. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  6495. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  6496. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  6497. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6498. <button onclick="toggleOspfInterfaceState('${i.id}', ${!i.disabled})" class="px-2 py-1 rounded text-[11px] ${i.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'}">
  6499. ${i.disabled ? 'Enable' : 'Disable'}
  6500. </button>
  6501. <button onclick="openEditOspfInterfaceModal('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-indigo-300 border border-slate-700">
  6502. Edit
  6503. </button>
  6504. <button onclick="deleteOspfInterface('${i.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">
  6505. Delete
  6506. </button>
  6507. </td>
  6508. </tr>
  6509. `;
  6510. }).join('');
  6511. }
  6512. function renderOspfAreas() {
  6513. const tbody = document.getElementById('ospf-areas-table-body');
  6514. if (!tbody) return;
  6515. const countBadge = document.getElementById('ospf-areas-count-badge');
  6516. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  6517. const areas = state.ospfAreas || [];
  6518. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  6519. if (navBadge) navBadge.innerText = areas.length;
  6520. tbody.innerHTML = areas.map(a => `
  6521. <tr class="hover:bg-slate-800/40 transition">
  6522. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  6523. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  6524. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  6525. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  6526. <td class="py-2.5 px-3 text-right font-sans">
  6527. <button onclick="deleteOspfArea('${a.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">
  6528. Delete
  6529. </button>
  6530. </td>
  6531. </tr>
  6532. `).join('');
  6533. }
  6534. function renderOspfNeighbors() {
  6535. const tbody = document.getElementById('ospf-nbrs-table-body');
  6536. if (!tbody) return;
  6537. const empty = document.getElementById('ospf-nbrs-empty');
  6538. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  6539. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  6540. const nbrs = state.ospfNeighbors || [];
  6541. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  6542. if (navBadge) navBadge.innerText = nbrs.length;
  6543. if (nbrs.length === 0) {
  6544. tbody.innerHTML = '';
  6545. if (empty) empty.classList.remove('hidden');
  6546. return;
  6547. }
  6548. if (empty) empty.classList.add('hidden');
  6549. tbody.innerHTML = nbrs.map(n => {
  6550. let stateBadge = '';
  6551. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  6552. 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">${escapeHtml(n.state)}</span>`;
  6553. } else {
  6554. 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">${escapeHtml(n.state || 'Unknown')}</span>`;
  6555. }
  6556. return `
  6557. <tr class="hover:bg-slate-800/40 transition">
  6558. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  6559. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  6560. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  6561. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  6562. <td class="py-2.5 px-3">${stateBadge}</td>
  6563. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  6564. </tr>
  6565. `;
  6566. }).join('');
  6567. }
  6568. function renderOspfRoutes() {
  6569. const tbody = document.getElementById('ospf-routes-table-body');
  6570. if (!tbody) return;
  6571. const empty = document.getElementById('ospf-routes-empty');
  6572. const countBadge = document.getElementById('ospf-routes-count-badge');
  6573. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  6574. const routes = state.ospfRoutes || [];
  6575. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6576. if (navBadge) navBadge.innerText = routes.length;
  6577. if (routes.length === 0) {
  6578. tbody.innerHTML = '';
  6579. if (empty) empty.classList.remove('hidden');
  6580. return;
  6581. }
  6582. if (empty) empty.classList.add('hidden');
  6583. tbody.innerHTML = routes.map(r => `
  6584. <tr class="hover:bg-slate-800/40 transition">
  6585. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  6586. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  6587. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  6588. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  6589. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  6590. </tr>
  6591. `).join('');
  6592. }
  6593. // BGP Modals & Actions
  6594. function openBgpInstanceModal() {
  6595. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6596. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6597. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6598. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6599. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6600. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6601. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6602. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6603. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6604. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6605. }
  6606. function closeBgpInstanceModal() {
  6607. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6608. }
  6609. async function submitBgpInstance(e) {
  6610. e.preventDefault();
  6611. const payload = {
  6612. enabled: document.getElementById('modal-bgp-enabled').checked,
  6613. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6614. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6615. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6616. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6617. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6618. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6619. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6620. };
  6621. try {
  6622. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6623. method: 'POST',
  6624. headers: { 'Content-Type': 'application/json' },
  6625. body: JSON.stringify(payload)
  6626. });
  6627. if (res.ok) {
  6628. closeBgpInstanceModal();
  6629. showToast('Success', 'BGP instance configuration updated', 'success');
  6630. loadDynamicRouting();
  6631. } else {
  6632. const err = await res.json();
  6633. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6634. }
  6635. } catch (err) {
  6636. showToast('Error', err.message, 'error');
  6637. }
  6638. }
  6639. function openAddBgpPeerModal() {
  6640. document.getElementById('bgp-peer-form').reset();
  6641. document.getElementById('modal-bgp-peer-id').value = '';
  6642. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  6643. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  6644. const localAsEl = document.getElementById('modal-bgp-peer-local-as');
  6645. if (localAsEl) localAsEl.value = '';
  6646. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6647. if (inFilterEl) inFilterEl.value = '';
  6648. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6649. if (outFilterEl) outFilterEl.value = '';
  6650. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6651. }
  6652. function openEditBgpPeerModal(id) {
  6653. const p = (state.bgpPeers || []).find(item => item.id === id);
  6654. if (!p) return;
  6655. document.getElementById('modal-bgp-peer-id').value = p.id;
  6656. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6657. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6658. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6659. const localAsEl = document.getElementById('modal-bgp-peer-local-as');
  6660. if (localAsEl) localAsEl.value = p.local_as || '';
  6661. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6662. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6663. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6664. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  6665. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  6666. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  6667. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6668. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6669. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  6670. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6671. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  6672. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  6673. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6674. }
  6675. function closeBgpPeerModal() {
  6676. document.getElementById('bgp-peer-modal').classList.add('hidden');
  6677. }
  6678. async function submitBgpPeer(e) {
  6679. e.preventDefault();
  6680. const payload = {
  6681. id: document.getElementById('modal-bgp-peer-id').value,
  6682. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  6683. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  6684. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  6685. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  6686. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  6687. password: document.getElementById('modal-bgp-peer-password').value,
  6688. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  6689. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  6690. passive: document.getElementById('modal-bgp-peer-passive').checked,
  6691. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  6692. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  6693. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  6694. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  6695. };
  6696. try {
  6697. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  6698. method: 'POST',
  6699. headers: { 'Content-Type': 'application/json' },
  6700. body: JSON.stringify(payload)
  6701. });
  6702. if (res.ok) {
  6703. closeBgpPeerModal();
  6704. showToast('Success', 'BGP Peer saved', 'success');
  6705. loadDynamicRouting();
  6706. } else {
  6707. const err = await res.json();
  6708. showToast('Error', err.error || 'Failed to save peer', 'error');
  6709. }
  6710. } catch (err) {
  6711. showToast('Error', err.message, 'error');
  6712. }
  6713. }
  6714. async function deleteBgpPeer(id) {
  6715. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  6716. try {
  6717. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6718. if (res.ok) {
  6719. showToast('Deleted', 'BGP peer removed', 'success');
  6720. loadDynamicRouting();
  6721. }
  6722. } catch (err) {
  6723. showToast('Error', err.message, 'error');
  6724. }
  6725. }
  6726. async function toggleBgpPeerState(id, disabled) {
  6727. try {
  6728. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  6729. method: 'POST',
  6730. headers: { 'Content-Type': 'application/json' },
  6731. body: JSON.stringify({ disabled })
  6732. });
  6733. if (res.ok) {
  6734. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6735. loadDynamicRouting();
  6736. }
  6737. } catch (err) {
  6738. showToast('Error', err.message, 'error');
  6739. }
  6740. }
  6741. function openAddBgpNetworkModal() {
  6742. document.getElementById('bgp-network-form').reset();
  6743. document.getElementById('modal-bgp-net-id').value = '';
  6744. document.getElementById('bgp-network-modal').classList.remove('hidden');
  6745. }
  6746. function closeBgpNetworkModal() {
  6747. document.getElementById('bgp-network-modal').classList.add('hidden');
  6748. }
  6749. async function submitBgpNetwork(e) {
  6750. e.preventDefault();
  6751. const payload = {
  6752. id: document.getElementById('modal-bgp-net-id').value,
  6753. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  6754. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  6755. disabled: document.getElementById('modal-bgp-net-disabled').checked
  6756. };
  6757. try {
  6758. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  6759. method: 'POST',
  6760. headers: { 'Content-Type': 'application/json' },
  6761. body: JSON.stringify(payload)
  6762. });
  6763. if (res.ok) {
  6764. closeBgpNetworkModal();
  6765. showToast('Success', 'BGP network advertisement saved', 'success');
  6766. loadDynamicRouting();
  6767. } else {
  6768. const err = await res.json();
  6769. showToast('Error', err.error || 'Failed to save network', 'error');
  6770. }
  6771. } catch (err) {
  6772. showToast('Error', err.message, 'error');
  6773. }
  6774. }
  6775. async function deleteBgpNetwork(id) {
  6776. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  6777. try {
  6778. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6779. if (res.ok) {
  6780. showToast('Deleted', 'Network advertisement removed', 'success');
  6781. loadDynamicRouting();
  6782. }
  6783. } catch (err) {
  6784. showToast('Error', err.message, 'error');
  6785. }
  6786. }
  6787. // OSPF Modals & Actions
  6788. function openOspfInstanceModal() {
  6789. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  6790. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  6791. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  6792. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  6793. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  6794. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  6795. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  6796. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  6797. }
  6798. function closeOspfInstanceModal() {
  6799. document.getElementById('ospf-instance-modal').classList.add('hidden');
  6800. }
  6801. async function submitOspfInstance(e) {
  6802. e.preventDefault();
  6803. const payload = {
  6804. enabled: document.getElementById('modal-ospf-enabled').checked,
  6805. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  6806. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  6807. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  6808. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  6809. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  6810. };
  6811. try {
  6812. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  6813. method: 'POST',
  6814. headers: { 'Content-Type': 'application/json' },
  6815. body: JSON.stringify(payload)
  6816. });
  6817. if (res.ok) {
  6818. closeOspfInstanceModal();
  6819. showToast('Success', 'OSPF instance configuration updated', 'success');
  6820. loadDynamicRouting();
  6821. } else {
  6822. const err = await res.json();
  6823. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  6824. }
  6825. } catch (err) {
  6826. showToast('Error', err.message, 'error');
  6827. }
  6828. }
  6829. function openAddOspfAreaModal() {
  6830. document.getElementById('ospf-area-form').reset();
  6831. document.getElementById('modal-ospf-area-id').value = '';
  6832. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  6833. document.getElementById('ospf-area-modal').classList.remove('hidden');
  6834. }
  6835. function closeOspfAreaModal() {
  6836. document.getElementById('ospf-area-modal').classList.add('hidden');
  6837. }
  6838. async function submitOspfArea(e) {
  6839. e.preventDefault();
  6840. const payload = {
  6841. id: document.getElementById('modal-ospf-area-id').value,
  6842. name: document.getElementById('modal-ospf-area-name').value.trim(),
  6843. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  6844. area_type: document.getElementById('modal-ospf-area-type').value,
  6845. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  6846. };
  6847. try {
  6848. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  6849. method: 'POST',
  6850. headers: { 'Content-Type': 'application/json' },
  6851. body: JSON.stringify(payload)
  6852. });
  6853. if (res.ok) {
  6854. closeOspfAreaModal();
  6855. showToast('Success', 'OSPF area saved', 'success');
  6856. loadDynamicRouting();
  6857. } else {
  6858. const err = await res.json();
  6859. showToast('Error', err.error || 'Failed to save area', 'error');
  6860. }
  6861. } catch (err) {
  6862. showToast('Error', err.message, 'error');
  6863. }
  6864. }
  6865. async function deleteOspfArea(id) {
  6866. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  6867. try {
  6868. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6869. if (res.ok) {
  6870. showToast('Deleted', 'OSPF area removed', 'success');
  6871. loadDynamicRouting();
  6872. }
  6873. } catch (err) {
  6874. showToast('Error', err.message, 'error');
  6875. }
  6876. }
  6877. function populateOspfInterfaceDevices() {
  6878. const select = document.getElementById('modal-ospf-iface-device');
  6879. if (!select) return;
  6880. const current = select.value;
  6881. select.innerHTML = '<option value="">Any matching interface</option>';
  6882. (state.interfaces || []).forEach(iface => {
  6883. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  6884. });
  6885. if (current) select.value = current;
  6886. }
  6887. function openAddOspfInterfaceModal() {
  6888. document.getElementById('ospf-interface-form').reset();
  6889. document.getElementById('modal-ospf-iface-id').value = '';
  6890. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  6891. document.getElementById('modal-ospf-iface-cost').value = '10';
  6892. document.getElementById('modal-ospf-iface-priority').value = '1';
  6893. document.getElementById('modal-ospf-iface-hello').value = '10';
  6894. document.getElementById('modal-ospf-iface-dead').value = '40';
  6895. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  6896. populateOspfInterfaceDevices();
  6897. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6898. }
  6899. function openEditOspfInterfaceModal(id) {
  6900. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  6901. if (!item) return;
  6902. populateOspfInterfaceDevices();
  6903. document.getElementById('modal-ospf-iface-id').value = item.id;
  6904. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  6905. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  6906. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  6907. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  6908. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  6909. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  6910. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  6911. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  6912. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  6913. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  6914. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  6915. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  6916. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  6917. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6918. }
  6919. function closeOspfInterfaceModal() {
  6920. document.getElementById('ospf-interface-modal').classList.add('hidden');
  6921. }
  6922. async function submitOspfInterface(e) {
  6923. e.preventDefault();
  6924. const payload = {
  6925. id: document.getElementById('modal-ospf-iface-id').value,
  6926. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  6927. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  6928. interface: document.getElementById('modal-ospf-iface-device').value,
  6929. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  6930. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  6931. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  6932. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  6933. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  6934. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  6935. passive: document.getElementById('modal-ospf-iface-passive').checked,
  6936. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  6937. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  6938. };
  6939. try {
  6940. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  6941. method: 'POST',
  6942. headers: { 'Content-Type': 'application/json' },
  6943. body: JSON.stringify(payload)
  6944. });
  6945. if (res.ok) {
  6946. closeOspfInterfaceModal();
  6947. showToast('Success', 'OSPF interface template saved', 'success');
  6948. loadDynamicRouting();
  6949. } else {
  6950. const err = await res.json();
  6951. showToast('Error', err.error || 'Failed to save interface', 'error');
  6952. }
  6953. } catch (err) {
  6954. showToast('Error', err.message, 'error');
  6955. }
  6956. }
  6957. async function deleteOspfInterface(id) {
  6958. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  6959. try {
  6960. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6961. if (res.ok) {
  6962. showToast('Deleted', 'OSPF interface removed', 'success');
  6963. loadDynamicRouting();
  6964. }
  6965. } catch (err) {
  6966. showToast('Error', err.message, 'error');
  6967. }
  6968. }
  6969. async function toggleOspfInterfaceState(id, disabled) {
  6970. try {
  6971. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  6972. method: 'POST',
  6973. headers: { 'Content-Type': 'application/json' },
  6974. body: JSON.stringify({ disabled })
  6975. });
  6976. if (res.ok) {
  6977. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6978. loadDynamicRouting();
  6979. }
  6980. } catch (err) {
  6981. showToast('Error', err.message, 'error');
  6982. }
  6983. }
  6984. // ============================================================================
  6985. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  6986. // ============================================================================
  6987. function switchBridgeSubTab(tab) {
  6988. state.bridgeSubTab = tab;
  6989. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  6990. tabs.forEach(t => {
  6991. const panel = document.getElementById(`bridge-subtab-${t}`);
  6992. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  6993. if (panel) {
  6994. if (t === tab) panel.classList.remove('hidden');
  6995. else panel.classList.add('hidden');
  6996. }
  6997. if (btn) {
  6998. if (t === tab) {
  6999. 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';
  7000. } else {
  7001. 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';
  7002. }
  7003. }
  7004. });
  7005. const addBtn = document.getElementById('bridge-top-action-btn');
  7006. if (addBtn) {
  7007. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  7008. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  7009. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  7010. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  7011. }
  7012. if (tab === 'hosts') loadBridgeHosts();
  7013. setTimeout(initTableSorting, 50);
  7014. }
  7015. function openCurrentBridgeModal() {
  7016. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  7017. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  7018. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  7019. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7020. }
  7021. async function loadBridge() {
  7022. try {
  7023. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7024. fetch(`${API_BASE}/bridge/bridges`),
  7025. fetch(`${API_BASE}/bridge/ports`),
  7026. fetch(`${API_BASE}/bridge/vlans`),
  7027. fetch(`${API_BASE}/bridge/summary`),
  7028. fetch(`${API_BASE}/vpn/eoip`),
  7029. fetch(`${API_BASE}/vlans`)
  7030. ]);
  7031. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7032. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7033. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7034. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7035. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7036. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7037. // Badges & Stats
  7038. const bBridges = document.getElementById('bridge-badge-bridges');
  7039. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7040. const bPorts = document.getElementById('bridge-badge-ports');
  7041. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7042. const bVlans = document.getElementById('bridge-badge-vlans');
  7043. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7044. const bHosts = document.getElementById('bridge-badge-hosts');
  7045. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7046. const sBr = document.getElementById('bridge-stat-bridges');
  7047. if (sBr) sBr.innerText = (state.bridges || []).length;
  7048. const sPorts = document.getElementById('bridge-stat-ports');
  7049. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  7050. const sHosts = document.getElementById('bridge-stat-hosts');
  7051. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7052. renderBridges();
  7053. renderBridgePorts();
  7054. renderBridgeVLANs();
  7055. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7056. } catch (err) {
  7057. console.error('Failed to load bridge subsystem:', err);
  7058. }
  7059. }
  7060. // ----------------- Bridges -----------------
  7061. function renderBridges() {
  7062. const tbody = document.getElementById('bridge-table-body');
  7063. const empty = document.getElementById('bridge-empty-bridges');
  7064. const countBadge = document.getElementById('bridge-count-badge');
  7065. if (!tbody) return;
  7066. tbody.innerHTML = '';
  7067. const bridges = state.bridges || [];
  7068. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  7069. if (bridges.length === 0) {
  7070. empty?.classList.remove('hidden');
  7071. return;
  7072. }
  7073. empty?.classList.add('hidden');
  7074. bridges.forEach((b, idx) => {
  7075. const tr = document.createElement('tr');
  7076. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  7077. // Format IP addresses pill list
  7078. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  7079. if (b.ip_addresses && b.ip_addresses.length > 0) {
  7080. ipsHtml = b.ip_addresses.map(ip => `
  7081. <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">
  7082. <span>${ip}</span>
  7083. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  7084. </span>
  7085. `).join(' ');
  7086. }
  7087. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  7088. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  7089. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  7090. tr.innerHTML = `
  7091. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7092. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  7093. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7094. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  7095. </td>
  7096. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  7097. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  7098. <td class="py-2.5 px-3">
  7099. <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>
  7100. </td>
  7101. <td class="py-2.5 px-3 text-center">
  7102. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  7103. </td>
  7104. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  7105. <td class="py-2.5 px-3">
  7106. <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>
  7107. </td>
  7108. <td class="py-2.5 px-3">
  7109. <div class="flex items-center gap-1.5 flex-wrap">
  7110. ${ipsHtml}
  7111. <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>
  7112. </div>
  7113. </td>
  7114. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  7115. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  7116. </td>
  7117. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  7118. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7119. <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>
  7120. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7121. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7122. </td>
  7123. `;
  7124. tbody.appendChild(tr);
  7125. });
  7126. }
  7127. function openAddBridgeModal() {
  7128. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  7129. document.getElementById('bridge-modal-id').value = '';
  7130. document.getElementById('bridge-modal-name').value = 'bridge1';
  7131. document.getElementById('bridge-modal-name').disabled = false;
  7132. document.getElementById('bridge-modal-mtu').value = '1500';
  7133. document.getElementById('bridge-modal-mac').value = '';
  7134. document.getElementById('bridge-modal-stp').value = 'rstp';
  7135. document.getElementById('bridge-modal-priority').value = '32768';
  7136. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  7137. document.getElementById('bridge-modal-pvid').value = '1';
  7138. document.getElementById('bridge-modal-fastforward').checked = true;
  7139. document.getElementById('bridge-modal-comment').value = '';
  7140. document.getElementById('bridge-modal-disabled').checked = false;
  7141. toggleBridgeModalVlanFiltering();
  7142. document.getElementById('bridge-modal').classList.remove('hidden');
  7143. }
  7144. function openEditBridgeModal(id) {
  7145. const b = (state.bridges || []).find(x => x.id === id);
  7146. if (!b) return;
  7147. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  7148. document.getElementById('bridge-modal-id').value = b.id;
  7149. document.getElementById('bridge-modal-name').value = b.name;
  7150. document.getElementById('bridge-modal-name').disabled = true;
  7151. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  7152. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  7153. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  7154. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  7155. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  7156. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  7157. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  7158. document.getElementById('bridge-modal-comment').value = b.comment || '';
  7159. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  7160. toggleBridgeModalVlanFiltering();
  7161. document.getElementById('bridge-modal').classList.remove('hidden');
  7162. }
  7163. function closeBridgeModal() {
  7164. document.getElementById('bridge-modal').classList.add('hidden');
  7165. }
  7166. function toggleBridgeModalVlanFiltering() {
  7167. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  7168. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  7169. if (pvidBox) {
  7170. if (chk) pvidBox.classList.remove('opacity-40');
  7171. else pvidBox.classList.add('opacity-40');
  7172. }
  7173. }
  7174. async function submitSaveBridge(e) {
  7175. e.preventDefault();
  7176. const id = document.getElementById('bridge-modal-id').value;
  7177. const name = document.getElementById('bridge-modal-name').value.trim();
  7178. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  7179. const mac = document.getElementById('bridge-modal-mac').value.trim();
  7180. const stp = document.getElementById('bridge-modal-stp').value;
  7181. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  7182. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  7183. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  7184. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  7185. const comment = document.getElementById('bridge-modal-comment').value.trim();
  7186. const disabled = document.getElementById('bridge-modal-disabled').checked;
  7187. try {
  7188. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  7189. method: 'POST',
  7190. headers: { 'Content-Type': 'application/json' },
  7191. body: JSON.stringify({
  7192. id,
  7193. name,
  7194. mtu,
  7195. mac_address: mac,
  7196. stp,
  7197. priority,
  7198. vlan_filtering: vlanFiltering,
  7199. pvid,
  7200. fast_forward: fastForward,
  7201. comment,
  7202. disabled
  7203. })
  7204. });
  7205. if (res.ok) {
  7206. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  7207. closeBridgeModal();
  7208. loadBridge();
  7209. fetchData(false);
  7210. } else {
  7211. const err = await res.json();
  7212. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  7213. }
  7214. } catch (err) {
  7215. showToast('Error', err.message, 'error');
  7216. }
  7217. }
  7218. async function toggleBridgeState(id, disabled) {
  7219. try {
  7220. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  7221. method: 'POST',
  7222. headers: { 'Content-Type': 'application/json' },
  7223. body: JSON.stringify({ disabled })
  7224. });
  7225. if (res.ok) {
  7226. loadBridge();
  7227. fetchData(false);
  7228. }
  7229. } catch (err) {
  7230. showToast('Error', err.message, 'error');
  7231. }
  7232. }
  7233. async function deleteBridge(id) {
  7234. const b = (state.bridges || []).find(x => x.id === id);
  7235. const name = b ? b.name : id;
  7236. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  7237. try {
  7238. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7239. if (res.ok) {
  7240. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  7241. loadBridge();
  7242. fetchData(false);
  7243. } else {
  7244. const err = await res.json();
  7245. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  7246. }
  7247. } catch (err) {
  7248. showToast('Error', err.message, 'error');
  7249. }
  7250. }
  7251. // ----------------- Bridge IP Assignments -----------------
  7252. function openAddBridgeIPModal(id, name) {
  7253. document.getElementById('bridge-ip-modal-id').value = id;
  7254. document.getElementById('bridge-ip-modal-sub').innerText = name;
  7255. document.getElementById('bridge-ip-modal-cidr').value = '';
  7256. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  7257. }
  7258. function closeBridgeIPModal() {
  7259. document.getElementById('bridge-ip-modal').classList.add('hidden');
  7260. }
  7261. async function submitAddBridgeIP(e) {
  7262. e.preventDefault();
  7263. const id = document.getElementById('bridge-ip-modal-id').value;
  7264. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  7265. try {
  7266. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7267. method: 'POST',
  7268. headers: { 'Content-Type': 'application/json' },
  7269. body: JSON.stringify({ ip })
  7270. });
  7271. if (res.ok) {
  7272. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  7273. closeBridgeIPModal();
  7274. loadBridge();
  7275. fetchData(false);
  7276. } else {
  7277. const err = await res.json();
  7278. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  7279. }
  7280. } catch (err) {
  7281. showToast('Error', err.message, 'error');
  7282. }
  7283. }
  7284. async function deleteBridgeIP(id, ip) {
  7285. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  7286. try {
  7287. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7288. method: 'DELETE',
  7289. headers: { 'Content-Type': 'application/json' },
  7290. body: JSON.stringify({ ip })
  7291. });
  7292. if (res.ok) {
  7293. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  7294. loadBridge();
  7295. fetchData(false);
  7296. }
  7297. } catch (err) {
  7298. showToast('Error', err.message, 'error');
  7299. }
  7300. }
  7301. // ----------------- Bridge Ports -----------------
  7302. function renderBridgePorts() {
  7303. const tbody = document.getElementById('bridge-ports-table-body');
  7304. const empty = document.getElementById('bridge-empty-ports');
  7305. const countBadge = document.getElementById('bridge-ports-count-badge');
  7306. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  7307. if (!tbody) return;
  7308. tbody.innerHTML = '';
  7309. // Update filter select
  7310. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  7311. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  7312. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  7313. if (ports.length === 0) {
  7314. empty?.classList.remove('hidden');
  7315. return;
  7316. }
  7317. empty?.classList.add('hidden');
  7318. ports.forEach((p, idx) => {
  7319. const tr = document.createElement('tr');
  7320. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  7321. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7322. tr.innerHTML = `
  7323. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7324. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7325. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7326. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  7327. </td>
  7328. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  7329. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  7330. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  7331. <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>
  7332. <td class="py-2.5 px-3">
  7333. ${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>'}
  7334. </td>
  7335. <td class="py-2.5 px-3">
  7336. <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>
  7337. </td>
  7338. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  7339. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7340. <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>
  7341. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7342. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7343. </td>
  7344. `;
  7345. tbody.appendChild(tr);
  7346. });
  7347. }
  7348. function openAddBridgePortModal() {
  7349. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  7350. document.getElementById('bridge-port-modal-id').value = '';
  7351. populateBridgeSelect('bridge-port-modal-bridge');
  7352. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  7353. document.getElementById('bridge-port-modal-pvid').value = '1';
  7354. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  7355. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  7356. document.getElementById('bridge-port-modal-horizon').value = '0';
  7357. document.getElementById('bridge-port-modal-pathcost').value = '10';
  7358. document.getElementById('bridge-port-modal-priority').value = '128';
  7359. document.getElementById('bridge-port-modal-learn').checked = true;
  7360. document.getElementById('bridge-port-modal-comment').value = '';
  7361. document.getElementById('bridge-port-modal-disabled').checked = false;
  7362. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7363. }
  7364. function openEditBridgePortModal(id) {
  7365. const p = (state.bridgePorts || []).find(x => x.id === id);
  7366. if (!p) return;
  7367. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  7368. document.getElementById('bridge-port-modal-id').value = p.id;
  7369. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  7370. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  7371. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  7372. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  7373. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  7374. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  7375. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  7376. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  7377. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  7378. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  7379. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  7380. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7381. }
  7382. function closeBridgePortModal() {
  7383. document.getElementById('bridge-port-modal').classList.add('hidden');
  7384. }
  7385. async function submitSaveBridgePort(e) {
  7386. e.preventDefault();
  7387. const id = document.getElementById('bridge-port-modal-id').value;
  7388. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  7389. const iface = document.getElementById('bridge-port-modal-interface').value;
  7390. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  7391. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  7392. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  7393. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  7394. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  7395. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  7396. const learn = document.getElementById('bridge-port-modal-learn').checked;
  7397. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  7398. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  7399. try {
  7400. const res = await fetch(`${API_BASE}/bridge/ports`, {
  7401. method: 'POST',
  7402. headers: { 'Content-Type': 'application/json' },
  7403. body: JSON.stringify({
  7404. id,
  7405. bridge,
  7406. interface: iface,
  7407. pvid,
  7408. frame_types: frameTypes,
  7409. ingress_filtering: ingressFiltering,
  7410. horizon,
  7411. path_cost: pathCost,
  7412. priority,
  7413. learn,
  7414. comment,
  7415. disabled
  7416. })
  7417. });
  7418. if (res.ok) {
  7419. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  7420. closeBridgePortModal();
  7421. loadBridge();
  7422. fetchData(false);
  7423. } else {
  7424. const err = await res.json();
  7425. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  7426. }
  7427. } catch (err) {
  7428. showToast('Error', err.message, 'error');
  7429. }
  7430. }
  7431. async function toggleBridgePortState(id, disabled) {
  7432. try {
  7433. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  7434. method: 'POST',
  7435. headers: { 'Content-Type': 'application/json' },
  7436. body: JSON.stringify({ disabled })
  7437. });
  7438. if (res.ok) {
  7439. loadBridge();
  7440. fetchData(false);
  7441. }
  7442. } catch (err) {
  7443. showToast('Error', err.message, 'error');
  7444. }
  7445. }
  7446. async function deleteBridgePort(id) {
  7447. const p = (state.bridgePorts || []).find(x => x.id === id);
  7448. const iface = p ? p.interface : id;
  7449. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  7450. try {
  7451. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7452. if (res.ok) {
  7453. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  7454. loadBridge();
  7455. fetchData(false);
  7456. }
  7457. } catch (err) {
  7458. showToast('Error', err.message, 'error');
  7459. }
  7460. }
  7461. // ----------------- Bridge VLANs -----------------
  7462. function renderBridgeVLANs() {
  7463. const tbody = document.getElementById('bridge-vlans-table-body');
  7464. const empty = document.getElementById('bridge-empty-vlans');
  7465. const countBadge = document.getElementById('bridge-vlans-count-badge');
  7466. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  7467. if (!tbody) return;
  7468. tbody.innerHTML = '';
  7469. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  7470. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  7471. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  7472. if (vlans.length === 0) {
  7473. empty?.classList.remove('hidden');
  7474. return;
  7475. }
  7476. empty?.classList.add('hidden');
  7477. vlans.forEach((v, idx) => {
  7478. const tr = document.createElement('tr');
  7479. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  7480. const taggedHtml = (v.tagged && v.tagged.length > 0)
  7481. ? 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(' ')
  7482. : '<span class="text-slate-600">none</span>';
  7483. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  7484. ? 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(' ')
  7485. : '<span class="text-slate-600">none</span>';
  7486. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7487. tr.innerHTML = `
  7488. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7489. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7490. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  7491. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  7492. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  7493. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  7494. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  7495. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7496. <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>
  7497. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7498. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7499. </td>
  7500. `;
  7501. tbody.appendChild(tr);
  7502. });
  7503. }
  7504. function openAddBridgeVLANModal() {
  7505. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  7506. document.getElementById('bridge-vlan-modal-id').value = '';
  7507. populateBridgeSelect('bridge-vlan-modal-bridge');
  7508. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  7509. document.getElementById('bridge-vlan-modal-comment').value = '';
  7510. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  7511. updateBridgeVlanPortCheckboxes();
  7512. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7513. }
  7514. function openEditBridgeVLANModal(id) {
  7515. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  7516. if (!v) return;
  7517. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  7518. document.getElementById('bridge-vlan-modal-id').value = v.id;
  7519. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  7520. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  7521. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  7522. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  7523. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  7524. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7525. }
  7526. function closeBridgeVlanModal() {
  7527. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  7528. }
  7529. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  7530. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  7531. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  7532. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  7533. if (!taggedBox || !untaggedBox) return;
  7534. // Ports belonging to the selected bridge
  7535. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  7536. if (memberPorts.length === 0) {
  7537. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7538. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7539. return;
  7540. }
  7541. taggedBox.innerHTML = memberPorts.map(p => `
  7542. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7543. <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">
  7544. <span>${p.interface}</span>
  7545. </label>
  7546. `).join('');
  7547. untaggedBox.innerHTML = memberPorts.map(p => `
  7548. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7549. <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">
  7550. <span>${p.interface}</span>
  7551. </label>
  7552. `).join('');
  7553. }
  7554. async function submitSaveBridgeVLAN(e) {
  7555. e.preventDefault();
  7556. const id = document.getElementById('bridge-vlan-modal-id').value;
  7557. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  7558. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  7559. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  7560. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  7561. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  7562. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  7563. try {
  7564. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  7565. method: 'POST',
  7566. headers: { 'Content-Type': 'application/json' },
  7567. body: JSON.stringify({
  7568. id,
  7569. bridge,
  7570. vlan_ids: vlanIDs,
  7571. tagged,
  7572. untagged,
  7573. comment,
  7574. disabled
  7575. })
  7576. });
  7577. if (res.ok) {
  7578. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  7579. closeBridgeVlanModal();
  7580. loadBridge();
  7581. } else {
  7582. const err = await res.json();
  7583. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  7584. }
  7585. } catch (err) {
  7586. showToast('Error', err.message, 'error');
  7587. }
  7588. }
  7589. async function toggleBridgeVLANState(id, disabled) {
  7590. try {
  7591. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  7592. method: 'POST',
  7593. headers: { 'Content-Type': 'application/json' },
  7594. body: JSON.stringify({ disabled })
  7595. });
  7596. if (res.ok) loadBridge();
  7597. } catch (err) {
  7598. showToast('Error', err.message, 'error');
  7599. }
  7600. }
  7601. async function deleteBridgeVLAN(id) {
  7602. if (!confirm('Delete this bridge VLAN entry?')) return;
  7603. try {
  7604. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7605. if (res.ok) {
  7606. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  7607. loadBridge();
  7608. }
  7609. } catch (err) {
  7610. showToast('Error', err.message, 'error');
  7611. }
  7612. }
  7613. // ----------------- Hosts / MAC Table -----------------
  7614. async function loadBridgeHosts() {
  7615. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  7616. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  7617. try {
  7618. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  7619. const res = await fetch(url);
  7620. if (res.ok) {
  7621. state.bridgeHosts = await res.json();
  7622. renderBridgeHosts();
  7623. }
  7624. } catch (err) {
  7625. console.error('Failed to load bridge hosts:', err);
  7626. }
  7627. }
  7628. function renderBridgeHosts() {
  7629. const tbody = document.getElementById('bridge-hosts-table-body');
  7630. const empty = document.getElementById('bridge-empty-hosts');
  7631. const countBadge = document.getElementById('bridge-hosts-count-badge');
  7632. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  7633. if (!tbody) return;
  7634. tbody.innerHTML = '';
  7635. const hosts = (state.bridgeHosts || []).filter(h => {
  7636. if (!search) return true;
  7637. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  7638. });
  7639. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  7640. if (hosts.length === 0) {
  7641. empty?.classList.remove('hidden');
  7642. return;
  7643. }
  7644. empty?.classList.add('hidden');
  7645. hosts.forEach(h => {
  7646. const tr = document.createElement('tr');
  7647. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  7648. let flagBadges = '';
  7649. 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>';
  7650. 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>';
  7651. 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>';
  7652. tr.innerHTML = `
  7653. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  7654. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  7655. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  7656. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  7657. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  7658. <td class="py-2.5 px-3">${flagBadges}</td>
  7659. `;
  7660. tbody.appendChild(tr);
  7661. });
  7662. }
  7663. async function flushBridgeHosts() {
  7664. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  7665. if (!selBridge) {
  7666. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  7667. return;
  7668. }
  7669. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  7670. try {
  7671. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  7672. method: 'POST',
  7673. headers: { 'Content-Type': 'application/json' },
  7674. body: JSON.stringify({ bridge: selBridge })
  7675. });
  7676. if (res.ok) {
  7677. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  7678. loadBridgeHosts();
  7679. }
  7680. } catch (err) {
  7681. showToast('Error', err.message, 'error');
  7682. }
  7683. }
  7684. // ----------------- Helpers -----------------
  7685. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  7686. const sel = document.getElementById(selectId);
  7687. if (!sel) return;
  7688. const prevVal = currentVal || sel.value;
  7689. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  7690. (state.bridges || []).forEach(b => {
  7691. const opt = document.createElement('option');
  7692. opt.value = b.name;
  7693. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  7694. if (b.name === prevVal) opt.selected = true;
  7695. sel.appendChild(opt);
  7696. });
  7697. }
  7698. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  7699. const sel = document.getElementById(selectId);
  7700. if (!sel) return;
  7701. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  7702. // 1. Physical Interfaces
  7703. const grpPhys = document.createElement('optgroup');
  7704. grpPhys.label = 'Physical Interfaces';
  7705. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  7706. const opt = document.createElement('option');
  7707. opt.value = i.name;
  7708. opt.innerText = `${i.name} (${i.role || i.type})`;
  7709. if (i.name === currentVal) opt.selected = true;
  7710. grpPhys.appendChild(opt);
  7711. });
  7712. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  7713. // 2. VLAN Sub-interfaces
  7714. const grpVlans = document.createElement('optgroup');
  7715. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  7716. (state.vlans || []).forEach(v => {
  7717. const opt = document.createElement('option');
  7718. opt.value = v.name;
  7719. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  7720. if (v.name === currentVal) opt.selected = true;
  7721. grpVlans.appendChild(opt);
  7722. });
  7723. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  7724. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  7725. const grpEoip = document.createElement('optgroup');
  7726. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  7727. (state.eoipTunnels || []).forEach(t => {
  7728. const opt = document.createElement('option');
  7729. opt.value = t.name;
  7730. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  7731. if (t.name === currentVal) opt.selected = true;
  7732. grpEoip.appendChild(opt);
  7733. });
  7734. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  7735. }
  7736. // -------------------------------------------------------------
  7737. // Routing Filters Management (/routing filter)
  7738. // -------------------------------------------------------------
  7739. function renderRoutingFilters() {
  7740. const tbody = document.getElementById('routing-filters-table-body');
  7741. if (!tbody) return;
  7742. const empty = document.getElementById('routing-filters-empty');
  7743. const countBadge = document.getElementById('routing-filters-count-badge');
  7744. const navBadge = document.getElementById('badge-filters-count');
  7745. const chainSelect = document.getElementById('routing-filter-chain-select');
  7746. const allRules = state.routingFilters || [];
  7747. if (navBadge) navBadge.innerText = allRules.length;
  7748. // Populate chain filter select options dynamically
  7749. if (chainSelect) {
  7750. const currentVal = state.filterChainSelected || 'all';
  7751. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  7752. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  7753. uniqueChains.map(ch => {
  7754. const count = allRules.filter(r => r.chain === ch).length;
  7755. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  7756. }).join('');
  7757. chainSelect.value = currentVal;
  7758. }
  7759. // Filter rules by selected chain
  7760. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  7761. ? allRules.filter(r => r.chain === state.filterChainSelected)
  7762. : allRules.slice();
  7763. // Sort by chain then rule_order
  7764. filteredRules.sort((a, b) => {
  7765. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  7766. return (a.rule_order || 0) - (b.rule_order || 0);
  7767. });
  7768. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  7769. if (filteredRules.length === 0) {
  7770. tbody.innerHTML = '';
  7771. if (empty) empty.classList.remove('hidden');
  7772. return;
  7773. }
  7774. if (empty) empty.classList.add('hidden');
  7775. tbody.innerHTML = filteredRules.map(r => {
  7776. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7777. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7778. let actionBadge = '';
  7779. if (r.action === 'accept') {
  7780. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">accept</span>';
  7781. } else if (r.action === 'discard') {
  7782. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20">discard</span>';
  7783. } else if (r.action === 'reject') {
  7784. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-red-950 text-red-300 border border-red-800/40">reject</span>';
  7785. } else {
  7786. actionBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/20">${escapeHtml(r.action || 'accept')}</span>`;
  7787. }
  7788. // Prefix match
  7789. let matchPfx = '';
  7790. if (r.prefix) {
  7791. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  7792. if (r.prefix_len) {
  7793. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  7794. }
  7795. } else {
  7796. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  7797. }
  7798. // Other matches
  7799. const matchExtra = [];
  7800. if (r.match_protocol && r.match_protocol !== 'any') {
  7801. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700">proto:${escapeHtml(r.match_protocol)}</span>`);
  7802. }
  7803. if (r.match_as_path) {
  7804. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">as-path:${escapeHtml(r.match_as_path)}</span>`);
  7805. }
  7806. if (r.match_community) {
  7807. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">comm:${escapeHtml(r.match_community)}</span>`);
  7808. }
  7809. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  7810. // Set modifications
  7811. const setBadges = [];
  7812. if (r.set_local_pref > 0) {
  7813. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950 text-cyan-300 border border-cyan-800/40">loc-pref: ${r.set_local_pref}</span>`);
  7814. }
  7815. if (r.set_metric > 0) {
  7816. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40">med: ${r.set_metric}</span>`);
  7817. }
  7818. if (r.set_as_prepend > 0) {
  7819. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40">prepend: +${r.set_as_prepend}</span>`);
  7820. }
  7821. if (r.set_community) {
  7822. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40">comm: ${escapeHtml(r.set_community)}</span>`);
  7823. }
  7824. if (r.set_next_hop) {
  7825. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/40">nh: ${escapeHtml(r.set_next_hop)}</span>`);
  7826. }
  7827. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  7828. return `
  7829. <tr class="hover:bg-slate-800/40 transition">
  7830. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  7831. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  7832. <td class="py-2.5 px-3">
  7833. <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>
  7834. </td>
  7835. <td class="py-2.5 px-3">${actionBadge}</td>
  7836. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  7837. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  7838. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  7839. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  7840. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7841. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-1 rounded text-[11px] ${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'}">
  7842. ${r.disabled ? 'Enable' : 'Disable'}
  7843. </button>
  7844. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  7845. Edit
  7846. </button>
  7847. <button onclick="deleteRoutingFilter('${r.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">
  7848. Delete
  7849. </button>
  7850. </td>
  7851. </tr>
  7852. `;
  7853. }).join('');
  7854. }
  7855. function filterRoutingFiltersByChain(chain) {
  7856. state.filterChainSelected = chain;
  7857. renderRoutingFilters();
  7858. }
  7859. function openAddRoutingFilterModal(defaultChain = '') {
  7860. const form = document.getElementById('routing-filter-form');
  7861. if (form) form.reset();
  7862. const idEl = document.getElementById('modal-rf-id');
  7863. if (idEl) idEl.value = '';
  7864. const titleEl = document.getElementById('modal-rf-title');
  7865. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  7866. const chainEl = document.getElementById('modal-rf-chain');
  7867. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  7868. const orderEl = document.getElementById('modal-rf-order');
  7869. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  7870. const actEl = document.getElementById('modal-rf-action');
  7871. if (actEl) actEl.value = 'accept';
  7872. const protoEl = document.getElementById('modal-rf-protocol');
  7873. if (protoEl) protoEl.value = 'any';
  7874. const disEl = document.getElementById('modal-rf-disabled');
  7875. if (disEl) disEl.checked = false;
  7876. const modal = document.getElementById('modal-routing-filter');
  7877. if (modal) modal.classList.remove('hidden');
  7878. }
  7879. function openEditRoutingFilterModal(id) {
  7880. const r = (state.routingFilters || []).find(item => item.id === id);
  7881. if (!r) return;
  7882. const idEl = document.getElementById('modal-rf-id');
  7883. if (idEl) idEl.value = r.id;
  7884. const titleEl = document.getElementById('modal-rf-title');
  7885. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  7886. const chainEl = document.getElementById('modal-rf-chain');
  7887. if (chainEl) chainEl.value = r.chain || '';
  7888. const orderEl = document.getElementById('modal-rf-order');
  7889. if (orderEl) orderEl.value = r.rule_order || 10;
  7890. const actEl = document.getElementById('modal-rf-action');
  7891. if (actEl) actEl.value = r.action || 'accept';
  7892. const pfxEl = document.getElementById('modal-rf-prefix');
  7893. if (pfxEl) pfxEl.value = r.prefix || '';
  7894. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  7895. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  7896. const protoEl = document.getElementById('modal-rf-protocol');
  7897. if (protoEl) protoEl.value = r.match_protocol || 'any';
  7898. const aspEl = document.getElementById('modal-rf-as-path');
  7899. if (aspEl) aspEl.value = r.match_as_path || '';
  7900. const commEl = document.getElementById('modal-rf-community');
  7901. if (commEl) commEl.value = r.match_community || '';
  7902. const lpEl = document.getElementById('modal-rf-set-local-pref');
  7903. if (lpEl) lpEl.value = r.set_local_pref || '';
  7904. const metEl = document.getElementById('modal-rf-set-metric');
  7905. if (metEl) metEl.value = r.set_metric || '';
  7906. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  7907. if (prepEl) prepEl.value = r.set_as_prepend || '';
  7908. const setCommEl = document.getElementById('modal-rf-set-community');
  7909. if (setCommEl) setCommEl.value = r.set_community || '';
  7910. const nhEl = document.getElementById('modal-rf-set-next-hop');
  7911. if (nhEl) nhEl.value = r.set_next_hop || '';
  7912. const comEl = document.getElementById('modal-rf-comment');
  7913. if (comEl) comEl.value = r.comment || '';
  7914. const disEl = document.getElementById('modal-rf-disabled');
  7915. if (disEl) disEl.checked = !!r.disabled;
  7916. const modal = document.getElementById('modal-routing-filter');
  7917. if (modal) modal.classList.remove('hidden');
  7918. }
  7919. function closeRoutingFilterModal() {
  7920. const modal = document.getElementById('modal-routing-filter');
  7921. if (modal) modal.classList.add('hidden');
  7922. }
  7923. async function submitRoutingFilter(e) {
  7924. e.preventDefault();
  7925. const payload = {
  7926. id: document.getElementById('modal-rf-id').value,
  7927. chain: document.getElementById('modal-rf-chain').value.trim(),
  7928. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  7929. action: document.getElementById('modal-rf-action').value,
  7930. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  7931. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  7932. match_protocol: document.getElementById('modal-rf-protocol').value,
  7933. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  7934. match_community: document.getElementById('modal-rf-community').value.trim(),
  7935. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  7936. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  7937. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  7938. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  7939. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  7940. comment: document.getElementById('modal-rf-comment').value.trim(),
  7941. disabled: document.getElementById('modal-rf-disabled').checked
  7942. };
  7943. try {
  7944. const res = await fetch(`${API_BASE}/routing/filters`, {
  7945. method: 'POST',
  7946. headers: { 'Content-Type': 'application/json' },
  7947. body: JSON.stringify(payload)
  7948. });
  7949. if (res.ok) {
  7950. closeRoutingFilterModal();
  7951. showToast('Success', 'Routing filter rule saved', 'success');
  7952. loadDynamicRouting();
  7953. } else {
  7954. const err = await res.json();
  7955. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  7956. }
  7957. } catch (err) {
  7958. showToast('Error', err.message, 'error');
  7959. }
  7960. }
  7961. async function deleteRoutingFilter(id) {
  7962. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  7963. try {
  7964. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7965. if (res.ok) {
  7966. showToast('Deleted', 'Routing filter rule removed', 'info');
  7967. loadDynamicRouting();
  7968. } else {
  7969. const err = await res.json();
  7970. showToast('Error', err.error || 'Failed to delete rule', 'error');
  7971. }
  7972. } catch (err) {
  7973. showToast('Error', err.message, 'error');
  7974. }
  7975. }
  7976. async function toggleRoutingFilterState(id, disabled) {
  7977. try {
  7978. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  7979. method: 'POST',
  7980. headers: { 'Content-Type': 'application/json' },
  7981. body: JSON.stringify({ disabled })
  7982. });
  7983. if (res.ok) {
  7984. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  7985. loadDynamicRouting();
  7986. } else {
  7987. const err = await res.json();
  7988. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  7989. }
  7990. } catch (err) {
  7991. showToast('Error', err.message, 'error');
  7992. }
  7993. }
  7994. // ==========================================
  7995. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  7996. // ==========================================
  7997. function loadToolsView() {
  7998. populateToolsInterfaces();
  7999. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  8000. }
  8001. function populateToolsInterfaces() {
  8002. const pingSel = document.getElementById('tools-ping-iface');
  8003. const traceSel = document.getElementById('tools-tr-iface');
  8004. let opts = '<option value="">Auto (Default Route)</option>';
  8005. if (Array.isArray(state.interfaces)) {
  8006. state.interfaces.forEach(iface => {
  8007. if (iface.name) {
  8008. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  8009. }
  8010. });
  8011. }
  8012. if (pingSel) {
  8013. const cur = pingSel.value;
  8014. pingSel.innerHTML = opts;
  8015. if (cur) pingSel.value = cur;
  8016. }
  8017. if (traceSel) {
  8018. const cur = traceSel.value;
  8019. traceSel.innerHTML = opts;
  8020. if (cur) traceSel.value = cur;
  8021. }
  8022. }
  8023. function switchToolsSubTab(subTab) {
  8024. state.activeToolsSubTab = subTab;
  8025. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  8026. tabs.forEach(t => {
  8027. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  8028. const view = document.getElementById(`tools-view-${t}`);
  8029. if (btn) {
  8030. if (t === subTab) {
  8031. 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';
  8032. } else {
  8033. 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';
  8034. }
  8035. }
  8036. if (view) {
  8037. if (t === subTab) {
  8038. view.classList.remove('hidden');
  8039. } else {
  8040. view.classList.add('hidden');
  8041. }
  8042. }
  8043. });
  8044. }
  8045. function setPortPreset(port) {
  8046. const input = document.getElementById('tools-port-num');
  8047. if (input) input.value = port;
  8048. }
  8049. let pingAbortController = null;
  8050. let tracerouteAbortController = null;
  8051. function clearPingTable() {
  8052. const tbody = document.getElementById('tools-ping-tbody');
  8053. if (tbody) tbody.innerHTML = '';
  8054. const rawEl = document.getElementById('tools-ping-raw');
  8055. if (rawEl) rawEl.innerText = '';
  8056. const sentEl = document.getElementById('tools-ping-stat-sent');
  8057. if (sentEl) sentEl.innerText = '0';
  8058. const recvEl = document.getElementById('tools-ping-stat-recv');
  8059. if (recvEl) recvEl.innerText = '0';
  8060. const lossEl = document.getElementById('tools-ping-stat-loss');
  8061. if (lossEl) lossEl.innerText = '0%';
  8062. const avgEl = document.getElementById('tools-ping-stat-avg');
  8063. if (avgEl) avgEl.innerText = '0 ms';
  8064. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8065. if (minMaxEl) minMaxEl.innerText = '-';
  8066. const badge = document.getElementById('tools-ping-status-badge');
  8067. if (badge) {
  8068. badge.className = '';
  8069. badge.innerText = '';
  8070. }
  8071. }
  8072. function clearTracerouteTable() {
  8073. const tbody = document.getElementById('tools-tr-tbody');
  8074. if (tbody) tbody.innerHTML = '';
  8075. const rawEl = document.getElementById('tools-tr-raw');
  8076. if (rawEl) rawEl.innerText = '';
  8077. const statHops = document.getElementById('tools-tr-hops-count');
  8078. if (statHops) statHops.innerText = '0 Hops';
  8079. }
  8080. function resetPingButton() {
  8081. const btn = document.getElementById('tools-ping-btn');
  8082. const btnText = document.getElementById('tools-ping-btn-text');
  8083. const spinner = document.getElementById('tools-ping-spinner');
  8084. if (btn) {
  8085. btn.disabled = false;
  8086. 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';
  8087. }
  8088. if (btnText) btnText.innerText = 'Start Ping';
  8089. if (spinner) spinner.classList.add('hidden');
  8090. }
  8091. function setPingRunningButton() {
  8092. const btn = document.getElementById('tools-ping-btn');
  8093. const btnText = document.getElementById('tools-ping-btn-text');
  8094. const spinner = document.getElementById('tools-ping-spinner');
  8095. if (btn) {
  8096. btn.disabled = false;
  8097. 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';
  8098. }
  8099. if (btnText) btnText.innerText = 'Stop Ping';
  8100. if (spinner) spinner.classList.remove('hidden');
  8101. }
  8102. function resetTracerouteButton() {
  8103. const btn = document.getElementById('tools-tr-btn');
  8104. const btnText = document.getElementById('tools-tr-btn-text');
  8105. const spinner = document.getElementById('tools-tr-spinner');
  8106. if (btn) {
  8107. btn.disabled = false;
  8108. 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';
  8109. }
  8110. if (btnText) btnText.innerText = 'Start Traceroute';
  8111. if (spinner) spinner.classList.add('hidden');
  8112. }
  8113. function setTracerouteRunningButton() {
  8114. const btn = document.getElementById('tools-tr-btn');
  8115. const btnText = document.getElementById('tools-tr-btn-text');
  8116. const spinner = document.getElementById('tools-tr-spinner');
  8117. if (btn) {
  8118. btn.disabled = false;
  8119. 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';
  8120. }
  8121. if (btnText) btnText.innerText = 'Stop Traceroute';
  8122. if (spinner) spinner.classList.remove('hidden');
  8123. }
  8124. async function executePing(e) {
  8125. if (e) e.preventDefault();
  8126. // If already running, clicking the button stops the stream!
  8127. if (pingAbortController) {
  8128. pingAbortController.abort();
  8129. pingAbortController = null;
  8130. resetPingButton();
  8131. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  8132. return;
  8133. }
  8134. const target = document.getElementById('tools-ping-target')?.value?.trim();
  8135. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  8136. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  8137. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  8138. const iface = document.getElementById('tools-ping-iface')?.value || '';
  8139. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  8140. if (!target) {
  8141. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8142. return;
  8143. }
  8144. clearPingTable();
  8145. const resCard = document.getElementById('tools-ping-results');
  8146. if (resCard) resCard.classList.remove('hidden');
  8147. pingAbortController = new AbortController();
  8148. setPingRunningButton();
  8149. try {
  8150. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  8151. method: 'POST',
  8152. headers: { 'Content-Type': 'application/json' },
  8153. body: JSON.stringify({
  8154. target,
  8155. count,
  8156. size,
  8157. timeout,
  8158. interface: iface,
  8159. dont_frag: dontFrag
  8160. }),
  8161. signal: pingAbortController.signal
  8162. });
  8163. if (!res.ok) {
  8164. const errText = await res.text();
  8165. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  8166. resetPingButton();
  8167. pingAbortController = null;
  8168. return;
  8169. }
  8170. const reader = res.body.getReader();
  8171. const decoder = new TextDecoder('utf-8');
  8172. let buffer = '';
  8173. while (true) {
  8174. const { done, value } = await reader.read();
  8175. if (done) break;
  8176. buffer += decoder.decode(value, { stream: true });
  8177. const blocks = buffer.split('\n\n');
  8178. buffer = blocks.pop() || '';
  8179. for (const block of blocks) {
  8180. const trimmed = block.trim();
  8181. if (!trimmed) continue;
  8182. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8183. try {
  8184. const evt = JSON.parse(line);
  8185. handleLivePingEvent(evt);
  8186. } catch (parseErr) {
  8187. console.warn('Ping SSE parse error:', parseErr, line);
  8188. }
  8189. }
  8190. }
  8191. } catch (err) {
  8192. if (err.name === 'AbortError') {
  8193. // User aborted normally
  8194. } else {
  8195. showToast('Ping Error', err.message, 'error');
  8196. }
  8197. } finally {
  8198. pingAbortController = null;
  8199. resetPingButton();
  8200. }
  8201. }
  8202. function handleLivePingEvent(evt) {
  8203. const sentEl = document.getElementById('tools-ping-stat-sent');
  8204. const recvEl = document.getElementById('tools-ping-stat-recv');
  8205. const lossEl = document.getElementById('tools-ping-stat-loss');
  8206. const avgEl = document.getElementById('tools-ping-stat-avg');
  8207. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8208. const badge = document.getElementById('tools-ping-status-badge');
  8209. const tbody = document.getElementById('tools-ping-tbody');
  8210. const rawEl = document.getElementById('tools-ping-raw');
  8211. if (evt.raw && rawEl) {
  8212. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8213. rawEl.scrollTop = rawEl.scrollHeight;
  8214. }
  8215. if (evt.type === 'reply') {
  8216. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8217. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8218. if (lossEl && evt.packet_loss_pct !== undefined) {
  8219. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8220. lossEl.className = evt.packet_loss_pct === 0
  8221. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  8222. : (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');
  8223. }
  8224. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8225. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8226. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8227. }
  8228. if (badge) {
  8229. if (evt.packet_loss_pct === 0) {
  8230. 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';
  8231. badge.innerText = '100% OK';
  8232. } else {
  8233. 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';
  8234. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  8235. }
  8236. }
  8237. if (tbody) {
  8238. const tr = document.createElement('tr');
  8239. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8240. tr.innerHTML = `
  8241. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  8242. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  8243. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  8244. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  8245. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  8246. <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>
  8247. `;
  8248. tbody.appendChild(tr);
  8249. }
  8250. } else if (evt.type === 'timeout') {
  8251. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8252. if (lossEl && evt.packet_loss_pct !== undefined) {
  8253. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8254. 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';
  8255. }
  8256. if (badge) {
  8257. 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';
  8258. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  8259. }
  8260. if (tbody) {
  8261. const tr = document.createElement('tr');
  8262. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  8263. tr.innerHTML = `
  8264. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8265. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  8266. <td class="py-2 px-3 text-slate-600">--</td>
  8267. <td class="py-2 px-3 text-slate-600">--</td>
  8268. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  8269. <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>
  8270. `;
  8271. tbody.appendChild(tr);
  8272. }
  8273. } else if (evt.type === 'unreach') {
  8274. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8275. if (lossEl && evt.packet_loss_pct !== undefined) {
  8276. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8277. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  8278. }
  8279. if (badge) {
  8280. 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';
  8281. badge.innerText = 'UNREACHABLE';
  8282. }
  8283. if (tbody) {
  8284. const tr = document.createElement('tr');
  8285. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8286. tr.innerHTML = `
  8287. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8288. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  8289. <td class="py-2 px-3 text-slate-600">--</td>
  8290. <td class="py-2 px-3 text-slate-600">--</td>
  8291. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  8292. <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>
  8293. `;
  8294. tbody.appendChild(tr);
  8295. }
  8296. } else if (evt.type === 'stats') {
  8297. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8298. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8299. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8300. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8301. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8302. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8303. }
  8304. } else if (evt.type === 'done') {
  8305. 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');
  8306. }
  8307. }
  8308. async function executeTraceroute(e) {
  8309. if (e) e.preventDefault();
  8310. if (tracerouteAbortController) {
  8311. tracerouteAbortController.abort();
  8312. tracerouteAbortController = null;
  8313. resetTracerouteButton();
  8314. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  8315. return;
  8316. }
  8317. const target = document.getElementById('tools-tr-target')?.value?.trim();
  8318. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  8319. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  8320. const iface = document.getElementById('tools-tr-iface')?.value || '';
  8321. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  8322. if (!target) {
  8323. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8324. return;
  8325. }
  8326. clearTracerouteTable();
  8327. const resCard = document.getElementById('tools-tr-results');
  8328. if (resCard) resCard.classList.remove('hidden');
  8329. tracerouteAbortController = new AbortController();
  8330. setTracerouteRunningButton();
  8331. try {
  8332. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  8333. method: 'POST',
  8334. headers: { 'Content-Type': 'application/json' },
  8335. body: JSON.stringify({
  8336. target,
  8337. max_hops: maxHops,
  8338. protocol,
  8339. interface: iface,
  8340. resolve
  8341. }),
  8342. signal: tracerouteAbortController.signal
  8343. });
  8344. if (!res.ok) {
  8345. const errText = await res.text();
  8346. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  8347. resetTracerouteButton();
  8348. tracerouteAbortController = null;
  8349. return;
  8350. }
  8351. const reader = res.body.getReader();
  8352. const decoder = new TextDecoder('utf-8');
  8353. let buffer = '';
  8354. while (true) {
  8355. const { done, value } = await reader.read();
  8356. if (done) break;
  8357. buffer += decoder.decode(value, { stream: true });
  8358. const blocks = buffer.split('\n\n');
  8359. buffer = blocks.pop() || '';
  8360. for (const block of blocks) {
  8361. const trimmed = block.trim();
  8362. if (!trimmed) continue;
  8363. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8364. try {
  8365. const evt = JSON.parse(line);
  8366. handleLiveTracerouteEvent(evt);
  8367. } catch (parseErr) {
  8368. console.warn('Traceroute SSE parse error:', parseErr, line);
  8369. }
  8370. }
  8371. }
  8372. } catch (err) {
  8373. if (err.name === 'AbortError') {
  8374. // User aborted normally
  8375. } else {
  8376. showToast('Traceroute Error', err.message, 'error');
  8377. }
  8378. } finally {
  8379. tracerouteAbortController = null;
  8380. resetTracerouteButton();
  8381. }
  8382. }
  8383. function handleLiveTracerouteEvent(evt) {
  8384. const statHops = document.getElementById('tools-tr-hops-count');
  8385. const tbody = document.getElementById('tools-tr-tbody');
  8386. const rawEl = document.getElementById('tools-tr-raw');
  8387. if (evt.raw && rawEl) {
  8388. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8389. rawEl.scrollTop = rawEl.scrollHeight;
  8390. }
  8391. if (evt.hops_count !== undefined && statHops) {
  8392. statHops.innerText = `${evt.hops_count} Hops`;
  8393. }
  8394. if (evt.type === 'hop' && evt.hop && tbody) {
  8395. const h = evt.hop;
  8396. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  8397. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  8398. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  8399. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  8400. const tr = document.createElement('tr');
  8401. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  8402. tr.innerHTML = `
  8403. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8404. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  8405. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  8406. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  8407. <td class="py-2.5 px-3 text-right">
  8408. ${isTimeout
  8409. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  8410. : '<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>'}
  8411. </td>
  8412. `;
  8413. tbody.appendChild(tr);
  8414. } else if (evt.type === 'done') {
  8415. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  8416. }
  8417. }
  8418. async function executeMTR(e) {
  8419. if (e) e.preventDefault();
  8420. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  8421. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  8422. if (!target) {
  8423. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8424. return;
  8425. }
  8426. const btn = document.getElementById('tools-mtr-btn');
  8427. const spinner = document.getElementById('tools-mtr-spinner');
  8428. if (btn) btn.disabled = true;
  8429. if (spinner) spinner.classList.remove('hidden');
  8430. try {
  8431. const res = await fetch(`${API_BASE}/tools/mtr`, {
  8432. method: 'POST',
  8433. headers: { 'Content-Type': 'application/json' },
  8434. body: JSON.stringify({ target, count: cycles })
  8435. });
  8436. const data = await res.json();
  8437. if (!res.ok) {
  8438. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  8439. return;
  8440. }
  8441. const resCard = document.getElementById('tools-mtr-results');
  8442. if (resCard) resCard.classList.remove('hidden');
  8443. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  8444. const statHops = document.getElementById('tools-mtr-hops-count');
  8445. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  8446. const tbody = document.getElementById('tools-mtr-tbody');
  8447. if (tbody) {
  8448. if (hopsCount > 0) {
  8449. tbody.innerHTML = data.hops.map(h => {
  8450. 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');
  8451. return `
  8452. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8453. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8454. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  8455. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  8456. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  8457. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  8458. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  8459. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  8460. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  8461. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  8462. </tr>
  8463. `;
  8464. }).join('');
  8465. } else {
  8466. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  8467. }
  8468. }
  8469. const rawEl = document.getElementById('tools-mtr-raw');
  8470. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8471. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  8472. } catch (err) {
  8473. showToast('MTR Error', err.message, 'error');
  8474. } finally {
  8475. if (btn) btn.disabled = false;
  8476. if (spinner) spinner.classList.add('hidden');
  8477. }
  8478. }
  8479. async function executeDNS(e) {
  8480. if (e) e.preventDefault();
  8481. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  8482. const type = document.getElementById('tools-dns-type')?.value || 'A';
  8483. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  8484. if (!domain) {
  8485. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  8486. return;
  8487. }
  8488. const btn = document.getElementById('tools-dns-btn');
  8489. const spinner = document.getElementById('tools-dns-spinner');
  8490. if (btn) btn.disabled = true;
  8491. if (spinner) spinner.classList.remove('hidden');
  8492. try {
  8493. const res = await fetch(`${API_BASE}/tools/dns`, {
  8494. method: 'POST',
  8495. headers: { 'Content-Type': 'application/json' },
  8496. body: JSON.stringify({ domain, type, server })
  8497. });
  8498. const data = await res.json();
  8499. if (!res.ok) {
  8500. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  8501. return;
  8502. }
  8503. const resCard = document.getElementById('tools-dns-results');
  8504. if (resCard) resCard.classList.remove('hidden');
  8505. const metaEl = document.getElementById('tools-dns-meta');
  8506. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  8507. const tbody = document.getElementById('tools-dns-tbody');
  8508. if (tbody) {
  8509. if (Array.isArray(data.records) && data.records.length > 0) {
  8510. tbody.innerHTML = data.records.map(r => `
  8511. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8512. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  8513. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  8514. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  8515. <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>
  8516. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  8517. </tr>
  8518. `).join('');
  8519. } else {
  8520. 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>`;
  8521. }
  8522. }
  8523. const rawEl = document.getElementById('tools-dns-raw');
  8524. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8525. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  8526. } catch (err) {
  8527. showToast('DNS Error', err.message, 'error');
  8528. } finally {
  8529. if (btn) btn.disabled = false;
  8530. if (spinner) spinner.classList.add('hidden');
  8531. }
  8532. }
  8533. async function executePortProbe(e) {
  8534. if (e) e.preventDefault();
  8535. const target = document.getElementById('tools-port-target')?.value?.trim();
  8536. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  8537. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  8538. if (!target || !port) {
  8539. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  8540. return;
  8541. }
  8542. const btn = document.getElementById('tools-port-btn');
  8543. const spinner = document.getElementById('tools-port-spinner');
  8544. if (btn) btn.disabled = true;
  8545. if (spinner) spinner.classList.remove('hidden');
  8546. try {
  8547. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  8548. method: 'POST',
  8549. headers: { 'Content-Type': 'application/json' },
  8550. body: JSON.stringify({ target, port, timeout })
  8551. });
  8552. const data = await res.json();
  8553. if (!res.ok) {
  8554. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  8555. return;
  8556. }
  8557. const resCard = document.getElementById('tools-port-results');
  8558. if (resCard) resCard.classList.remove('hidden');
  8559. const banner = document.getElementById('tools-port-banner');
  8560. const icon = document.getElementById('tools-port-icon');
  8561. const title = document.getElementById('tools-port-title');
  8562. const sub = document.getElementById('tools-port-sub');
  8563. const latency = document.getElementById('tools-port-latency');
  8564. if (data.open) {
  8565. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  8566. if (icon) {
  8567. 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';
  8568. icon.innerText = '✓';
  8569. }
  8570. if (title) {
  8571. title.className = 'text-sm font-bold text-emerald-300';
  8572. title.innerText = `PORT ${port} OPEN / LISTENING`;
  8573. }
  8574. if (sub) {
  8575. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  8576. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  8577. }
  8578. if (latency) {
  8579. latency.className = 'text-base font-bold font-mono text-emerald-300';
  8580. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  8581. }
  8582. } else {
  8583. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  8584. if (icon) {
  8585. 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';
  8586. icon.innerText = '✕';
  8587. }
  8588. if (title) {
  8589. title.className = 'text-sm font-bold text-rose-300';
  8590. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  8591. }
  8592. if (sub) {
  8593. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  8594. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  8595. }
  8596. if (latency) {
  8597. latency.className = 'text-base font-bold font-mono text-slate-500';
  8598. latency.innerText = '--';
  8599. }
  8600. }
  8601. const rawEl = document.getElementById('tools-port-raw');
  8602. 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'}`);
  8603. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  8604. } catch (err) {
  8605. showToast('Probe Error', err.message, 'error');
  8606. } finally {
  8607. if (btn) btn.disabled = false;
  8608. if (spinner) spinner.classList.add('hidden');
  8609. }
  8610. }
  8611. // ==========================================
  8612. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  8613. // ==========================================
  8614. async function loadDHCPClients(showToastMsg = false) {
  8615. try {
  8616. const [clientsRes, sumRes] = await Promise.all([
  8617. fetch(`${API_BASE}/dhcp/clients`),
  8618. fetch(`${API_BASE}/dhcp/clients/summary`)
  8619. ]);
  8620. if (clientsRes.ok) {
  8621. state.dhcpClients = await clientsRes.json();
  8622. }
  8623. if (sumRes.ok) {
  8624. state.dhcpSummary = await sumRes.json();
  8625. }
  8626. renderDHCPClients();
  8627. updateDHCPSummaryCards();
  8628. const bDhcp = document.getElementById('badge-dhcp-client-count');
  8629. if (bDhcp && state.dhcpSummary) {
  8630. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  8631. }
  8632. if (showToastMsg) {
  8633. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  8634. }
  8635. } catch (err) {
  8636. console.error('Failed to load DHCP clients:', err);
  8637. if (showToastMsg) {
  8638. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  8639. }
  8640. }
  8641. }
  8642. function updateDHCPSummaryCards() {
  8643. const sum = state.dhcpSummary || {
  8644. total_clients: (state.dhcpClients || []).length,
  8645. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  8646. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  8647. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  8648. };
  8649. const totalEl = document.getElementById('dhcp-stat-total');
  8650. const boundEl = document.getElementById('dhcp-stat-bound');
  8651. const searchEl = document.getElementById('dhcp-stat-searching');
  8652. const disEl = document.getElementById('dhcp-stat-disabled');
  8653. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  8654. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  8655. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  8656. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  8657. }
  8658. function renderDHCPClients() {
  8659. const tbody = document.getElementById('dhcp-clients-tbody');
  8660. const emptyState = document.getElementById('dhcp-clients-empty');
  8661. if (!tbody) return;
  8662. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  8663. if (clients.length === 0) {
  8664. tbody.innerHTML = '';
  8665. if (emptyState) emptyState.classList.remove('hidden');
  8666. return;
  8667. }
  8668. if (emptyState) emptyState.classList.add('hidden');
  8669. tbody.innerHTML = clients.map(c => {
  8670. let statusBadge = '';
  8671. if (!c.enabled) {
  8672. 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>';
  8673. } else if (c.status === 'bound') {
  8674. 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>';
  8675. } else if (c.status === 'searching') {
  8676. 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>';
  8677. } else if (c.status === 'stopped') {
  8678. 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>';
  8679. } else {
  8680. 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>`;
  8681. }
  8682. 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>';
  8683. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  8684. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  8685. 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>';
  8686. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  8687. // Option flags
  8688. const flags = [];
  8689. 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>');
  8690. 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>');
  8691. 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>');
  8692. 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>`);
  8693. return `
  8694. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  8695. <td class="py-3 px-4">
  8696. <div class="flex items-center gap-2">
  8697. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  8698. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  8699. </div>
  8700. </td>
  8701. <td class="py-3 px-4">${statusBadge}</td>
  8702. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  8703. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  8704. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  8705. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  8706. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  8707. <td class="py-3 px-4">
  8708. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  8709. </td>
  8710. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  8711. ${c.enabled ? `
  8712. <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>
  8713. <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>
  8714. <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>
  8715. ` : `
  8716. <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>
  8717. `}
  8718. <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>
  8719. <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>
  8720. </td>
  8721. </tr>
  8722. `;
  8723. }).join('');
  8724. }
  8725. function openDHCPClientModal(clientId = null) {
  8726. const modal = document.getElementById('modal-dhcp-client');
  8727. if (!modal) return;
  8728. const title = document.getElementById('modal-dhcp-title');
  8729. const idInput = document.getElementById('modal-dhcp-id');
  8730. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8731. const distInput = document.getElementById('modal-dhcp-distance');
  8732. const commentInput = document.getElementById('modal-dhcp-comment');
  8733. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  8734. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  8735. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  8736. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  8737. // Populate interfaces
  8738. if (ifaceSelect) {
  8739. let opts = '<option value="">Select interface...</option>';
  8740. const allIfaces = state.interfaces || [];
  8741. const allVlans = state.vlans || [];
  8742. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  8743. // Group 1: Physical & Bridge Interfaces
  8744. opts += '<optgroup label="Physical & Bridge Interfaces">';
  8745. allIfaces.forEach(i => {
  8746. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  8747. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  8748. });
  8749. opts += '</optgroup>';
  8750. // Group 2: VLAN Interfaces
  8751. if (allVlans.length > 0) {
  8752. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  8753. allVlans.forEach(v => {
  8754. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  8755. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  8756. });
  8757. opts += '</optgroup>';
  8758. }
  8759. ifaceSelect.innerHTML = opts;
  8760. }
  8761. if (clientId) {
  8762. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  8763. if (client) {
  8764. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  8765. if (idInput) idInput.value = client.id;
  8766. if (ifaceSelect) {
  8767. ifaceSelect.value = client.interface;
  8768. ifaceSelect.disabled = true; // interface cannot be changed on edit
  8769. }
  8770. if (distInput) distInput.value = client.default_route_distance || 1;
  8771. if (commentInput) commentInput.value = client.comment || '';
  8772. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  8773. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  8774. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  8775. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  8776. }
  8777. } else {
  8778. if (title) title.innerText = 'Add DHCP Client';
  8779. if (idInput) idInput.value = '';
  8780. if (ifaceSelect) {
  8781. ifaceSelect.value = '';
  8782. ifaceSelect.disabled = false;
  8783. }
  8784. if (distInput) distInput.value = 1;
  8785. if (commentInput) commentInput.value = '';
  8786. if (defRouteCheck) defRouteCheck.checked = true;
  8787. if (peerDnsCheck) peerDnsCheck.checked = true;
  8788. if (peerNtpCheck) peerNtpCheck.checked = true;
  8789. if (enabledCheck) enabledCheck.checked = true;
  8790. }
  8791. modal.classList.remove('hidden');
  8792. }
  8793. function openDHCPClientModalForIface(ifaceName) {
  8794. openDHCPClientModal();
  8795. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8796. if (ifaceSelect && ifaceName) {
  8797. ifaceSelect.value = ifaceName;
  8798. }
  8799. }
  8800. function closeDHCPClientModal() {
  8801. const modal = document.getElementById('modal-dhcp-client');
  8802. if (modal) modal.classList.add('hidden');
  8803. }
  8804. async function submitSaveDHCPClient(e) {
  8805. if (e) e.preventDefault();
  8806. const id = document.getElementById('modal-dhcp-id')?.value;
  8807. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  8808. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  8809. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  8810. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  8811. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  8812. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  8813. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  8814. if (!id && !iface) {
  8815. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  8816. return;
  8817. }
  8818. try {
  8819. let res;
  8820. if (id) {
  8821. // PUT update
  8822. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8823. method: 'PUT',
  8824. headers: { 'Content-Type': 'application/json' },
  8825. body: JSON.stringify({
  8826. enabled,
  8827. add_default_route: defRoute,
  8828. default_route_distance: distance,
  8829. use_peer_dns: peerDns,
  8830. use_peer_ntp: peerNtp,
  8831. comment
  8832. })
  8833. });
  8834. } else {
  8835. // POST create
  8836. res = await fetch(`${API_BASE}/dhcp/clients`, {
  8837. method: 'POST',
  8838. headers: { 'Content-Type': 'application/json' },
  8839. body: JSON.stringify({
  8840. interface: iface,
  8841. enabled,
  8842. add_default_route: defRoute,
  8843. default_route_distance: distance,
  8844. use_peer_dns: peerDns,
  8845. use_peer_ntp: peerNtp,
  8846. comment
  8847. })
  8848. });
  8849. }
  8850. const data = await res.json();
  8851. if (!res.ok) {
  8852. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  8853. return;
  8854. }
  8855. closeDHCPClientModal();
  8856. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  8857. await loadDHCPClients();
  8858. fetchData(); // refresh interfaces list with new lease/status
  8859. } catch (err) {
  8860. showToast('Error', err.message, 'error');
  8861. }
  8862. }
  8863. async function toggleDHCPClientState(id, enabled) {
  8864. try {
  8865. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  8866. method: 'POST',
  8867. headers: { 'Content-Type': 'application/json' },
  8868. body: JSON.stringify({ enabled })
  8869. });
  8870. const data = await res.json();
  8871. if (!res.ok) {
  8872. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  8873. return;
  8874. }
  8875. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  8876. await loadDHCPClients();
  8877. fetchData();
  8878. } catch (err) {
  8879. showToast('Error', err.message, 'error');
  8880. }
  8881. }
  8882. async function renewDHCPClient(id) {
  8883. try {
  8884. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  8885. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  8886. method: 'POST'
  8887. });
  8888. const data = await res.json();
  8889. if (!res.ok) {
  8890. showToast('Error', data.error || 'Failed to renew lease', 'error');
  8891. return;
  8892. }
  8893. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  8894. setTimeout(() => {
  8895. loadDHCPClients();
  8896. fetchData();
  8897. }, 1500);
  8898. } catch (err) {
  8899. showToast('Error', err.message, 'error');
  8900. }
  8901. }
  8902. async function releaseDHCPClient(id) {
  8903. try {
  8904. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  8905. method: 'POST'
  8906. });
  8907. const data = await res.json();
  8908. if (!res.ok) {
  8909. showToast('Error', data.error || 'Failed to release lease', 'error');
  8910. return;
  8911. }
  8912. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  8913. await loadDHCPClients();
  8914. fetchData();
  8915. } catch (err) {
  8916. showToast('Error', err.message, 'error');
  8917. }
  8918. }
  8919. async function deleteDHCPClient(id, ifaceName) {
  8920. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  8921. return;
  8922. }
  8923. try {
  8924. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8925. method: 'DELETE'
  8926. });
  8927. const data = await res.json();
  8928. if (!res.ok) {
  8929. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  8930. return;
  8931. }
  8932. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  8933. await loadDHCPClients();
  8934. fetchData();
  8935. } catch (err) {
  8936. showToast('Error', err.message, 'error');
  8937. }
  8938. }
  8939. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  8940. function initTableSorting() {
  8941. document.querySelectorAll('table').forEach(setupSortableTable);
  8942. }
  8943. function setupSortableTable(table) {
  8944. const thead = table.querySelector('thead');
  8945. const tbody = table.querySelector('tbody');
  8946. if (!thead || !tbody) return;
  8947. const headerRows = thead.querySelectorAll('tr');
  8948. if (headerRows.length === 0) return;
  8949. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  8950. ths.forEach((th, colIdx) => {
  8951. if (th._sortBound) return;
  8952. th._sortBound = true;
  8953. const rawText = th.innerText.trim().toLowerCase();
  8954. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  8955. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  8956. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  8957. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  8958. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  8959. return;
  8960. }
  8961. th.classList.add('table-sortable', 'group');
  8962. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  8963. let icon = th.querySelector('.table-sort-icon');
  8964. if (!icon) {
  8965. icon = document.createElement('span');
  8966. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  8967. icon.innerHTML = '⇅';
  8968. th.appendChild(icon);
  8969. }
  8970. th.addEventListener('click', (e) => {
  8971. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  8972. handleHeaderClick(table, th, colIdx);
  8973. });
  8974. });
  8975. if (!tbody._sortObserved) {
  8976. tbody._sortObserved = true;
  8977. let sortDebounceTimer = null;
  8978. const observer = new MutationObserver((mutations) => {
  8979. if (tbody._isSorting) return;
  8980. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  8981. if (!hasChildChanges) return;
  8982. clearTimeout(sortDebounceTimer);
  8983. sortDebounceTimer = setTimeout(() => {
  8984. if (tbody._isSorting) return;
  8985. if (table._activeSort && table._activeSort.dir !== 'none') {
  8986. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  8987. } else {
  8988. tagOriginalRowOrder(tbody);
  8989. }
  8990. }, 10);
  8991. });
  8992. observer.observe(tbody, { childList: true });
  8993. }
  8994. tagOriginalRowOrder(tbody);
  8995. }
  8996. function tagOriginalRowOrder(tbody) {
  8997. let idx = 0;
  8998. Array.from(tbody.children).forEach(tr => {
  8999. if (!tr.querySelector('td[colspan]')) {
  9000. if (!tr.hasAttribute('data-orig-idx')) {
  9001. tr.setAttribute('data-orig-idx', idx++);
  9002. }
  9003. }
  9004. });
  9005. }
  9006. function handleHeaderClick(table, th, colIdx) {
  9007. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  9008. let newDir = 'asc';
  9009. if (currentSort.colIdx === colIdx) {
  9010. if (currentSort.dir === 'asc') newDir = 'desc';
  9011. else if (currentSort.dir === 'desc') newDir = 'none';
  9012. else newDir = 'asc';
  9013. } else {
  9014. newDir = 'asc';
  9015. }
  9016. table._activeSort = { colIdx, dir: newDir };
  9017. updateHeaderIcons(table, colIdx, newDir);
  9018. applyTableSort(table, colIdx, newDir, true);
  9019. }
  9020. function updateHeaderIcons(table, activeColIdx, dir) {
  9021. const thead = table.querySelector('thead');
  9022. if (!thead) return;
  9023. const ths = thead.querySelectorAll('th');
  9024. ths.forEach((th, idx) => {
  9025. const icon = th.querySelector('.table-sort-icon');
  9026. if (!icon) return;
  9027. if (idx === activeColIdx && dir !== 'none') {
  9028. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  9029. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  9030. th.classList.add('table-sorted-active');
  9031. } else {
  9032. icon.innerHTML = '⇅';
  9033. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  9034. th.classList.remove('table-sorted-active');
  9035. }
  9036. });
  9037. }
  9038. function applyTableSort(table, colIdx, dir, userInitiated) {
  9039. const tbody = table.querySelector('tbody');
  9040. if (!tbody || tbody.children.length <= 1) return;
  9041. tbody._isSorting = true;
  9042. tagOriginalRowOrder(tbody);
  9043. // Group parent rows and any attached drawer/sub-rows
  9044. const groups = [];
  9045. let currentGroup = null;
  9046. Array.from(tbody.children).forEach(tr => {
  9047. if (tr.querySelector('td[colspan]')) {
  9048. if (currentGroup) {
  9049. currentGroup.subRows.push(tr);
  9050. } else {
  9051. groups.push({ mainRow: tr, subRows: [] });
  9052. }
  9053. } else {
  9054. currentGroup = { mainRow: tr, subRows: [] };
  9055. groups.push(currentGroup);
  9056. }
  9057. });
  9058. if (dir === 'none') {
  9059. groups.sort((a, b) => {
  9060. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9061. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  9062. return idxA - idxB;
  9063. });
  9064. } else {
  9065. groups.sort((a, b) => {
  9066. const cellA = a.mainRow.children[colIdx];
  9067. const cellB = b.mainRow.children[colIdx];
  9068. const res = compareTableCells(cellA, cellB);
  9069. return dir === 'asc' ? res : -res;
  9070. });
  9071. }
  9072. // Re-append rows in sorted order
  9073. groups.forEach(g => {
  9074. tbody.appendChild(g.mainRow);
  9075. g.subRows.forEach(sub => tbody.appendChild(sub));
  9076. });
  9077. tbody._isSorting = false;
  9078. }
  9079. function getCellRawText(cell) {
  9080. if (!cell) return '';
  9081. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  9082. const input = cell.querySelector('input, select');
  9083. if (input) {
  9084. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  9085. return input.value;
  9086. }
  9087. return cell.innerText.trim();
  9088. }
  9089. function parseTrafficToNumber(str) {
  9090. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  9091. if (!m) return null;
  9092. const num = parseFloat(m[1].replace(/,/g, ''));
  9093. if (isNaN(num)) return null;
  9094. const unit = m[2].toUpperCase();
  9095. let mult = 1;
  9096. if (unit.startsWith('K')) mult = 1024;
  9097. else if (unit.startsWith('M')) mult = 1024 * 1024;
  9098. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  9099. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  9100. return num * mult;
  9101. }
  9102. function parseIpToNumber(str) {
  9103. const clean = str.replace(/^[!~]/, '').trim();
  9104. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  9105. if (!m) return null;
  9106. const o1 = parseInt(m[1], 10);
  9107. const o2 = parseInt(m[2], 10);
  9108. const o3 = parseInt(m[3], 10);
  9109. const o4 = parseInt(m[4], 10);
  9110. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  9111. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  9112. }
  9113. function parseCompoundPackets(str) {
  9114. const m = str.match(/^([\d,]+)p/);
  9115. if (!m) return null;
  9116. return parseInt(m[1].replace(/,/g, ''), 10);
  9117. }
  9118. function compareTableCells(cellA, cellB) {
  9119. const a = getCellRawText(cellA);
  9120. const b = getCellRawText(cellB);
  9121. if (a === '' && b !== '') return 1;
  9122. if (b === '' && a !== '') return -1;
  9123. if (a === b) return 0;
  9124. // 1. IP Addresses / CIDR
  9125. const ipA = parseIpToNumber(a);
  9126. const ipB = parseIpToNumber(b);
  9127. if (ipA !== null && ipB !== null) return ipA - ipB;
  9128. // 2. Packet counts (e.g. "1,250p / 45 KB")
  9129. const pktA = parseCompoundPackets(a);
  9130. const pktB = parseCompoundPackets(b);
  9131. if (pktA !== null && pktB !== null) return pktA - pktB;
  9132. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  9133. const trafA = parseTrafficToNumber(a);
  9134. const trafB = parseTrafficToNumber(b);
  9135. if (trafA !== null && trafB !== null) return trafA - trafB;
  9136. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  9137. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9138. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  9139. const numA = Number(cleanNumA);
  9140. const numB = Number(cleanNumB);
  9141. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  9142. return numA - numB;
  9143. }
  9144. // 5. Natural case-insensitive string compare
  9145. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  9146. }
  9147. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  9148. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  9149. const docTableObserver = new MutationObserver((mutations) => {
  9150. let needsInit = false;
  9151. for (const m of mutations) {
  9152. for (const node of m.addedNodes) {
  9153. if (node.nodeType === 1) {
  9154. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  9155. needsInit = true;
  9156. break;
  9157. }
  9158. }
  9159. }
  9160. if (needsInit) break;
  9161. }
  9162. if (needsInit) {
  9163. initTableSorting();
  9164. }
  9165. });
  9166. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  9167. }