app.js 318 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510
  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. };
  47. const API_BASE = '/api';
  48. function escapeHtml(str) {
  49. if (str === null || str === undefined) return '';
  50. return String(str)
  51. .replace(/&/g, '&')
  52. .replace(/</g, '&lt;')
  53. .replace(/>/g, '&gt;')
  54. .replace(/"/g, '&quot;')
  55. .replace(/'/g, '&#039;');
  56. }
  57. // Initialize on page load
  58. document.addEventListener('DOMContentLoaded', () => {
  59. const hash = window.location.hash.replace('#', '') || 'dashboard';
  60. navigate(hash);
  61. fetchData();
  62. // Live polling every 2.5 seconds
  63. setInterval(() => {
  64. if (state.isPolling) {
  65. fetchData(false);
  66. }
  67. }, 2500);
  68. });
  69. // Navigation Handler
  70. function navigate(tabName) {
  71. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  72. navigate('bgp');
  73. return;
  74. }
  75. if (tabName === 'vlans') {
  76. navigate('interfaces');
  77. return;
  78. }
  79. state.activeTab = tabName;
  80. window.location.hash = tabName;
  81. // Update nav links styling
  82. document.querySelectorAll('.nav-link').forEach(link => {
  83. 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';
  84. });
  85. const activeNav = document.getElementById(`nav-${tabName}`);
  86. if (activeNav) {
  87. 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';
  88. }
  89. // Update page headers
  90. const titles = {
  91. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  92. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  93. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  94. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  95. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  96. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  97. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  98. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  99. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'MikroTik-style route filter chains, prefix matching, BGP attributes & policy maps' },
  100. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  101. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  102. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  103. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  104. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  105. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  106. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  107. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  108. tools: { title: 'Troubleshoot & Diagnostic Tools (/tool)', sub: 'RouterOS-style Ping, Traceroute, MTR Telemetry, DNS resolution, and TCP Port probing' },
  109. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  110. };
  111. const header = titles[tabName] || titles.dashboard;
  112. const pTitle = document.getElementById('page-title');
  113. if (pTitle) pTitle.innerText = header.title;
  114. const pSub = document.getElementById('page-subtitle');
  115. if (pSub) pSub.innerText = header.sub;
  116. // Toggle sections dynamically for all section elements
  117. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  118. if (el.id === `section-${tabName}`) {
  119. el.classList.remove('hidden');
  120. } else {
  121. el.classList.add('hidden');
  122. }
  123. });
  124. if (tabName === 'bridge') loadBridge();
  125. if (tabName === 'firewall') loadFirewall();
  126. if (tabName === 'routes') loadRoutes();
  127. if (tabName === 'bgp') {
  128. loadDynamicRouting();
  129. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  130. }
  131. if (tabName === 'ospf') {
  132. loadDynamicRouting();
  133. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  134. }
  135. if (tabName === 'routing-filters') loadDynamicRouting();
  136. if (tabName === 'dynamic-routing') loadDynamicRouting();
  137. if (tabName === 'ppp') loadPPP();
  138. if (tabName === 'eoip') loadEoIP();
  139. if (tabName === 'persistence') loadDebianConfig();
  140. if (tabName === 'pppoe') loadPPPoE();
  141. if (tabName === 'wireguard') loadWireGuard();
  142. if (tabName === 'ipsec') loadIPSec();
  143. if (tabName === 'l2tp') loadL2TP();
  144. if (tabName === 'pptp') loadPPTP();
  145. if (tabName === 'tools') loadToolsView();
  146. }
  147. // Fetch all core system, network and VPN telemetry
  148. async function fetchData(isManual = false) {
  149. const spinner = document.getElementById('refresh-spinner');
  150. if (isManual && spinner) spinner.classList.add('animate-spin');
  151. try {
  152. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes] = await Promise.all([
  153. fetch(`${API_BASE}/system/status`),
  154. fetch(`${API_BASE}/interfaces`),
  155. fetch(`${API_BASE}/vlans`),
  156. fetch(`${API_BASE}/vpn/status`),
  157. fetch(`${API_BASE}/firewall/summary`),
  158. fetch(`${API_BASE}/routing/dynamic/summary`),
  159. fetch(`${API_BASE}/bridge/summary`)
  160. ]);
  161. if (brSummaryRes.ok) {
  162. state.bridgeSummary = await brSummaryRes.json();
  163. const bBridge = document.getElementById('badge-bridge-count');
  164. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  165. const sBr = document.getElementById('bridge-stat-bridges');
  166. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  167. const sPorts = document.getElementById('bridge-stat-ports');
  168. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  169. const sHosts = document.getElementById('bridge-stat-hosts');
  170. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  171. }
  172. if (statusRes.ok) state.systemStatus = await statusRes.json();
  173. if (ifacesRes.ok) {
  174. const ifacesData = await ifacesRes.json();
  175. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  176. state.interfaces = rawIfaces.filter(i => {
  177. if (!i.name) return false;
  178. if (i.name.startsWith('ep_')) return false;
  179. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  180. });
  181. }
  182. if (vlansRes.ok) {
  183. const vlansData = await vlansRes.json();
  184. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  185. }
  186. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  187. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  188. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  189. updateSystemMetrics();
  190. updateBadges();
  191. if (state.activeTab === 'dashboard') renderDashboard();
  192. if (state.activeTab === 'interfaces') renderInterfacesList();
  193. if (state.activeTab === 'vlans') renderVlansList();
  194. if (state.activeTab === 'firewall') loadFirewall(false);
  195. if (state.activeTab === 'routes') loadRoutes(false);
  196. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  197. if (state.activeTab === 'ppp') loadPPP(false);
  198. if (state.activeTab === 'eoip') loadEoIP(false);
  199. if (state.activeTab === 'pppoe') loadPPPoE(false);
  200. if (state.activeTab === 'wireguard') loadWireGuard(false);
  201. if (state.activeTab === 'ipsec') loadIPSec(false);
  202. if (state.activeTab === 'l2tp') loadL2TP(false);
  203. if (state.activeTab === 'pptp') loadPPTP(false);
  204. } catch (err) {
  205. console.error('Failed to fetch router state:', err);
  206. } finally {
  207. if (isManual && spinner) {
  208. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  209. }
  210. }
  211. }
  212. // Update Top KPI and Sidebar Telemetry
  213. function updateSystemMetrics() {
  214. const s = state.systemStatus;
  215. const v = state.vpnStatus;
  216. if (!s) return;
  217. // Sidebar
  218. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  219. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  220. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  221. if (s.cpu_pct !== undefined) {
  222. const pct = s.cpu_pct;
  223. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  224. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  225. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  226. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  227. } else if (s.cpu_load && s.cpu_load.length > 0) {
  228. const cores = s.cpu_cores || 4;
  229. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  230. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  231. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  232. }
  233. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  234. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  235. // Dashboard Stats
  236. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  237. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  238. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  239. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  240. // VPN Status Indicators
  241. if (v) {
  242. const totalActive = v.total_active_tunnels || 0;
  243. const statVpnActive = document.getElementById('stat-vpn-active');
  244. if (statVpnActive) statVpnActive.innerText = totalActive;
  245. const tunnelsDot = document.getElementById('tunnels-dot');
  246. const tunnelsLabel = document.getElementById('tunnels-label');
  247. if (tunnelsDot && tunnelsLabel) {
  248. if (totalActive > 0) {
  249. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  250. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  251. } else {
  252. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  253. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  254. }
  255. }
  256. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  257. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  258. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  259. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  260. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  261. }
  262. // Total Live Bandwidth Rate
  263. let totalRx = 0;
  264. let totalTx = 0;
  265. (state.interfaces || []).forEach(i => {
  266. if (i.rate) {
  267. totalRx += i.rate.rx_bytes_sec || 0;
  268. totalTx += i.rate.tx_bytes_sec || 0;
  269. }
  270. });
  271. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  272. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  273. }
  274. function setDotBadge(id, active) {
  275. const el = document.getElementById(id);
  276. if (!el) return;
  277. if (active) {
  278. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  279. } else {
  280. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  281. }
  282. }
  283. function updateBadges() {
  284. const bIfaces = document.getElementById('badge-ifaces-count');
  285. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  286. const bVlans = document.getElementById('badge-vlans-count');
  287. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  288. if (state.fwSummary) {
  289. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  290. const badgeFw = document.getElementById('badge-firewall-count');
  291. if (badgeFw) badgeFw.innerText = totalFwRules;
  292. }
  293. if (state.vpnStatus) {
  294. const v = state.vpnStatus;
  295. const bEoIP = document.getElementById('badge-eoip-count');
  296. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  297. const bPPPSess = document.getElementById('badge-ppp-sessions');
  298. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  299. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  300. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  301. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  302. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  303. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  304. }
  305. if (state.dynSummary) {
  306. const d = state.dynSummary;
  307. setDotBadge('badge-bgp-dot', d.bgp_running);
  308. setDotBadge('badge-ospf-dot', d.ospf_running);
  309. const bBgp = document.getElementById('badge-bgp-count');
  310. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  311. const bOspf = document.getElementById('badge-ospf-count');
  312. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  313. const bFilters = document.getElementById('badge-filters-count');
  314. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  315. }
  316. }
  317. // Render Dashboard View
  318. function renderDashboard() {
  319. const matrix = document.getElementById('port-matrix');
  320. matrix.innerHTML = '';
  321. (state.interfaces || []).forEach(iface => {
  322. const isUp = iface.state === 'UP';
  323. const isVlan = iface.is_vlan;
  324. const portCard = document.createElement('div');
  325. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  326. isUp
  327. ? (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')
  328. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  329. }`;
  330. portCard.onclick = () => openIfaceModal(iface.name);
  331. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  332. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  333. portCard.innerHTML = `
  334. <div class="flex items-center justify-between mb-2">
  335. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  336. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  337. </div>
  338. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  339. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  340. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  341. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  342. </div>
  343. `;
  344. matrix.appendChild(portCard);
  345. });
  346. const ifaceTbody = document.getElementById('quick-interfaces-table');
  347. ifaceTbody.innerHTML = '';
  348. (state.interfaces || []).slice(0, 6).forEach(i => {
  349. const isUp = i.state === 'UP';
  350. const tr = document.createElement('tr');
  351. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  352. tr.onclick = () => openIfaceModal(i.name);
  353. tr.innerHTML = `
  354. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  355. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  356. <span>${i.name}</span>
  357. </td>
  358. <td class="py-2.5 text-slate-300 font-sans"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300">${i.role || 'LAN'}</span></td>
  359. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  360. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  361. `;
  362. ifaceTbody.appendChild(tr);
  363. });
  364. const vlanTbody = document.getElementById('quick-vlans-table');
  365. vlanTbody.innerHTML = '';
  366. const vlans = state.vlans || [];
  367. if (vlans.length === 0) {
  368. vlanTbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-500 font-sans">No VLANs configured. Click "+ Add" above to create one.</td></tr>`;
  369. } else {
  370. vlans.slice(0, 6).forEach(v => {
  371. const tr = document.createElement('tr');
  372. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  373. tr.onclick = () => openIfaceModal(v.name);
  374. tr.innerHTML = `
  375. <td class="py-2.5"><span class="px-2 py-0.5 rounded text-[11px] bg-cyan-950 text-cyan-400 border border-cyan-800 font-bold">VLAN ${v.vlan_id}</span></td>
  376. <td class="py-2.5 text-white font-bold">${v.name}</td>
  377. <td class="py-2.5 text-slate-300">${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600">Unnumbered</span>'}</td>
  378. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  379. `;
  380. vlanTbody.appendChild(tr);
  381. });
  382. }
  383. }
  384. // Expand / Collapse Handlers
  385. function toggleExpand(parentName) {
  386. if (state.expandedParents.has(parentName)) {
  387. state.expandedParents.delete(parentName);
  388. } else {
  389. state.expandedParents.add(parentName);
  390. }
  391. renderInterfacesList();
  392. }
  393. function expandAllIfaces(expand) {
  394. if (expand) {
  395. (state.interfaces || []).forEach(i => {
  396. if (!i.is_vlan) state.expandedParents.add(i.name);
  397. });
  398. } else {
  399. state.expandedParents.clear();
  400. }
  401. renderInterfacesList();
  402. }
  403. // Filter and Render Hierarchical Interfaces List
  404. function filterIfaces(filter) {
  405. state.ifaceFilter = filter;
  406. document.querySelectorAll('.filter-btn').forEach(btn => {
  407. btn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:bg-slate-800 hover:text-white';
  408. });
  409. const activeBtn = document.getElementById(`filter-${filter}`);
  410. if (activeBtn) {
  411. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  412. }
  413. renderInterfacesList();
  414. }
  415. function renderInterfacesList() {
  416. const tbody = document.getElementById('interfaces-tree-tbody');
  417. const emptyState = document.getElementById('interfaces-empty-state');
  418. const summary = document.getElementById('ifaces-list-summary');
  419. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  420. tbody.innerHTML = '';
  421. const allIfaces = state.interfaces || [];
  422. const allVlans = state.vlans || [];
  423. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  424. const filteredParents = parentIfaces.filter(parent => {
  425. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  426. if (query) {
  427. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  428. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  429. if (!matchParent && !matchVlan) return false;
  430. }
  431. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  432. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  433. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  434. return true;
  435. });
  436. if (summary) {
  437. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  438. }
  439. if (filteredParents.length === 0) {
  440. emptyState?.classList.remove('hidden');
  441. return;
  442. }
  443. emptyState?.classList.add('hidden');
  444. filteredParents.forEach(parent => {
  445. const isUp = parent.state === 'UP';
  446. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  447. const isExpanded = state.expandedParents.has(parent.name);
  448. const parentRow = document.createElement('tr');
  449. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  450. parentRow.innerHTML = `
  451. <td class="py-3 px-3 text-center">
  452. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  453. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  454. <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">
  455. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  456. </svg>
  457. </button>
  458. </td>
  459. <td class="py-3 px-4">
  460. <div class="flex items-center space-x-2.5">
  461. <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">
  462. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  463. </div>
  464. <div>
  465. <div class="flex items-center gap-2">
  466. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  467. ${childVlans.length > 0
  468. ? `<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>`
  469. : `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-slate-800/60 text-slate-500 px-1.5 py-0.5 rounded font-mono hover:text-slate-300">0 VLANs</span>`
  470. }
  471. </div>
  472. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  473. </div>
  474. </div>
  475. </td>
  476. <td class="py-3 px-4 font-sans">
  477. <div class="flex items-center gap-1.5">
  478. <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>
  479. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  480. </div>
  481. </td>
  482. <td class="py-3 px-4">
  483. ${parent.ipv4 && parent.ipv4.length > 0
  484. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  485. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  486. }
  487. </td>
  488. <td class="py-3 px-4 text-slate-400 text-[11px]">
  489. <div>${parent.mac || 'N/A'}</div>
  490. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  491. </td>
  492. <td class="py-3 px-4 text-[11px]">
  493. <div class="flex items-center space-x-2">
  494. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  495. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  496. </div>
  497. </td>
  498. <td class="py-3 px-4 font-sans">
  499. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  500. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  501. 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'
  502. }" title="Click to toggle link status">
  503. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  504. <span>${parent.state}</span>
  505. </button>
  506. </td>
  507. <td class="py-3 px-4 text-right space-x-2 font-sans">
  508. <button onclick="openVlanModal('${parent.name}')"
  509. 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">
  510. + Add VLAN
  511. </button>
  512. <button onclick="openIfaceModal('${parent.name}')"
  513. 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">
  514. Configure
  515. </button>
  516. </td>
  517. `;
  518. tbody.appendChild(parentRow);
  519. if (isExpanded) {
  520. const drawerRow = document.createElement('tr');
  521. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  522. const drawerCell = document.createElement('td');
  523. drawerCell.colSpan = 8;
  524. drawerCell.className = 'p-0';
  525. drawerCell.innerHTML = `
  526. <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">
  527. <div class="flex items-center justify-between mb-3">
  528. <div class="flex items-center space-x-3">
  529. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  530. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  531. </span>
  532. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  533. ${childVlans.length} Attached
  534. </span>
  535. </div>
  536. <button onclick="openVlanModal('${parent.name}')"
  537. 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">
  538. <span>+ Create VLAN on ${parent.name}</span>
  539. </button>
  540. </div>
  541. ${childVlans.length === 0 ? `
  542. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  543. <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>
  544. <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">
  545. <span>+ Create Your First VLAN on ${parent.name}</span>
  546. </button>
  547. </div>
  548. ` : `
  549. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  550. <table class="w-full text-left text-xs font-mono">
  551. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  552. <tr>
  553. <th class="py-2.5 px-4">VLAN ID</th>
  554. <th class="py-2.5 px-4">Interface Device</th>
  555. <th class="py-2.5 px-4">Subnet Gateway</th>
  556. <th class="py-2.5 px-4">Role / Alias</th>
  557. <th class="py-2.5 px-4">MTU</th>
  558. <th class="py-2.5 px-4">Throughput</th>
  559. <th class="py-2.5 px-4">Status</th>
  560. <th class="py-2.5 px-4 text-right">Actions</th>
  561. </tr>
  562. </thead>
  563. <tbody class="divide-y divide-slate-800/70">
  564. ${childVlans.map(v => {
  565. const isVlanUp = v.state === 'UP';
  566. return `
  567. <tr class="hover:bg-slate-800/40 transition">
  568. <td class="py-2.5 px-4">
  569. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  570. VLAN ${v.vlan_id}
  571. </span>
  572. </td>
  573. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  574. <span class="text-cyan-500">└─</span>
  575. <span>${v.name}</span>
  576. </td>
  577. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  578. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  579. </td>
  580. <td class="py-2.5 px-4 font-sans text-slate-300">
  581. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  582. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  583. </td>
  584. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  585. <td class="py-2.5 px-4 text-[11px]">
  586. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  587. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  588. </td>
  589. <td class="py-2.5 px-4 font-sans">
  590. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  591. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  592. 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'
  593. }">
  594. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  595. <span>${v.state}</span>
  596. </button>
  597. </td>
  598. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  599. <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>
  600. <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>
  601. </td>
  602. </tr>
  603. `;
  604. }).join('')}
  605. </tbody>
  606. </table>
  607. </div>
  608. `}
  609. </div>
  610. `;
  611. drawerRow.appendChild(drawerCell);
  612. tbody.appendChild(drawerRow);
  613. }
  614. });
  615. }
  616. // Render VLANs Dedicated View
  617. function renderVlansList() {
  618. const tbody = document.getElementById('vlans-table-body');
  619. if (!tbody) return;
  620. const emptyState = document.getElementById('vlans-empty-state');
  621. const countBadge = document.getElementById('vlans-table-count');
  622. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  623. tbody.innerHTML = '';
  624. const allVlans = state.vlans || [];
  625. if (countBadge) countBadge.innerText = allVlans.length;
  626. const filtered = allVlans.filter(v => {
  627. if (!query) return true;
  628. return v.name.toLowerCase().includes(query) ||
  629. String(v.vlan_id).includes(query) ||
  630. (v.description || '').toLowerCase().includes(query) ||
  631. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  632. });
  633. if (allVlans.length === 0) {
  634. emptyState.classList.remove('hidden');
  635. return;
  636. }
  637. emptyState.classList.add('hidden');
  638. filtered.forEach(v => {
  639. const isUp = v.state === 'UP';
  640. const tr = document.createElement('tr');
  641. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  642. tr.innerHTML = `
  643. <td class="py-3 px-4">
  644. <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">
  645. VLAN ${v.vlan_id}
  646. </span>
  647. </td>
  648. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  649. <td class="py-3 px-4 text-slate-300">
  650. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  651. </td>
  652. <td class="py-3 px-4 text-emerald-400 font-medium">
  653. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  654. </td>
  655. <td class="py-3 px-4 text-slate-300 font-sans">
  656. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  657. </td>
  658. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  659. <td class="py-3 px-4 font-sans">
  660. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  661. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  662. 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'
  663. }">
  664. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  665. <span>${v.state}</span>
  666. </button>
  667. </td>
  668. <td class="py-3 px-4 text-right space-x-2 font-sans">
  669. <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>
  670. <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>
  671. </td>
  672. `;
  673. tbody.appendChild(tr);
  674. });
  675. }
  676. // Toggle interface UP / DOWN
  677. async function toggleInterfaceState(name, newState) {
  678. try {
  679. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  680. method: 'POST',
  681. headers: { 'Content-Type': 'application/json' },
  682. body: JSON.stringify({ state: newState })
  683. });
  684. const data = await res.json();
  685. if (res.ok) {
  686. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  687. fetchData(false);
  688. } else {
  689. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  690. }
  691. } catch (err) {
  692. showToast('Error', err.message, 'error');
  693. }
  694. }
  695. // ---------------- MikroTik Flag & Utilities ----------------
  696. function renderMikroTikFlag(running, disabled) {
  697. if (running) {
  698. 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>`;
  699. }
  700. if (disabled) {
  701. 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>`;
  702. }
  703. 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>`;
  704. }
  705. function copyToClipboard(text, label = 'Text') {
  706. navigator.clipboard.writeText(text).then(() => {
  707. showToast('Copied', `${label} copied to clipboard`, 'success');
  708. }).catch(() => {
  709. prompt('Copy value:', text);
  710. });
  711. }
  712. // ======================== PPPoE Multi-Instance ========================
  713. async function loadPPPoE(populateInputs = true) {
  714. try {
  715. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  716. const list = await res.json();
  717. state.pppoeList = Array.isArray(list) ? list : [];
  718. const badge = document.getElementById('pppoe-count-badge');
  719. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  720. const tbody = document.getElementById('pppoe-table-body');
  721. const empty = document.getElementById('pppoe-empty');
  722. if (!tbody) return;
  723. tbody.innerHTML = '';
  724. if (state.pppoeList.length === 0) {
  725. if (empty) empty.classList.remove('hidden');
  726. } else {
  727. if (empty) empty.classList.add('hidden');
  728. state.pppoeList.forEach(inst => {
  729. const tr = document.createElement('tr');
  730. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  731. tr.innerHTML = `
  732. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  733. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  734. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  735. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  736. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  737. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  738. <td class="py-2.5 px-3 text-center">
  739. <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'}">
  740. ${inst.default_route ? 'Yes' : 'No'}
  741. </span>
  742. </td>
  743. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  744. ${inst.running ? `
  745. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  746. ` : `
  747. <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>
  748. `}
  749. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  750. ${inst.disabled ? 'Enable' : 'Disable'}
  751. </button>
  752. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  753. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  754. </td>
  755. `;
  756. tbody.appendChild(tr);
  757. });
  758. }
  759. } catch (err) {
  760. console.error('Failed to load PPPoE:', err);
  761. }
  762. }
  763. function openAddPPPoEModal() {
  764. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  765. document.getElementById('pppoe-modal-edit-orig').value = '';
  766. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  767. document.getElementById('pppoe-modal-name').readOnly = false;
  768. document.getElementById('pppoe-modal-user').value = '';
  769. document.getElementById('pppoe-modal-pass').value = '';
  770. document.getElementById('pppoe-modal-service').value = '';
  771. document.getElementById('pppoe-modal-mtu').value = '1492';
  772. document.getElementById('pppoe-modal-defroute').checked = true;
  773. document.getElementById('pppoe-modal-reconnect').checked = true;
  774. document.getElementById('pppoe-modal-disabled').checked = false;
  775. // Populate interfaces
  776. const sel = document.getElementById('pppoe-modal-iface');
  777. sel.innerHTML = '';
  778. (state.interfaces || []).forEach(i => {
  779. if (i.name === 'lo') return;
  780. const opt = document.createElement('option');
  781. opt.value = i.name;
  782. opt.innerText = `${i.name} (${i.role || i.type})`;
  783. sel.appendChild(opt);
  784. });
  785. document.getElementById('pppoe-modal').classList.remove('hidden');
  786. }
  787. function openEditPPPoEModal(name) {
  788. const inst = (state.pppoeList || []).find(i => i.name === name);
  789. if (!inst) return;
  790. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  791. document.getElementById('pppoe-modal-edit-orig').value = name;
  792. document.getElementById('pppoe-modal-name').value = inst.name;
  793. document.getElementById('pppoe-modal-name').readOnly = true;
  794. document.getElementById('pppoe-modal-user').value = inst.username || '';
  795. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  796. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  797. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  798. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  799. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  800. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  801. const sel = document.getElementById('pppoe-modal-iface');
  802. sel.innerHTML = '';
  803. (state.interfaces || []).forEach(i => {
  804. if (i.name === 'lo') return;
  805. const opt = document.createElement('option');
  806. opt.value = i.name;
  807. opt.innerText = `${i.name} (${i.role || i.type})`;
  808. if (i.name === inst.interface) opt.selected = true;
  809. sel.appendChild(opt);
  810. });
  811. document.getElementById('pppoe-modal').classList.remove('hidden');
  812. }
  813. function closePPPoEModal() {
  814. document.getElementById('pppoe-modal').classList.add('hidden');
  815. }
  816. async function submitSavePPPoE(e) {
  817. e.preventDefault();
  818. const name = document.getElementById('pppoe-modal-name').value.trim();
  819. const iface = document.getElementById('pppoe-modal-iface').value;
  820. const user = document.getElementById('pppoe-modal-user').value.trim();
  821. const pass = document.getElementById('pppoe-modal-pass').value;
  822. const service = document.getElementById('pppoe-modal-service').value.trim();
  823. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  824. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  825. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  826. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  827. try {
  828. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  829. method: 'POST',
  830. headers: { 'Content-Type': 'application/json' },
  831. body: JSON.stringify({
  832. name,
  833. interface: iface,
  834. username: user,
  835. password: pass,
  836. service_name: service,
  837. mtu,
  838. default_route: defRoute,
  839. auto_reconnect: reconnect,
  840. disabled
  841. })
  842. });
  843. if (res.ok) {
  844. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  845. closePPPoEModal();
  846. loadPPPoE(false);
  847. fetchData(false);
  848. } else {
  849. const err = await res.json();
  850. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  851. }
  852. } catch (err) {
  853. showToast('Error', err.message, 'error');
  854. }
  855. }
  856. async function connectPPPoEInstance(name) {
  857. try {
  858. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  859. if (res.ok) {
  860. showToast('Connecting', `Dialing ${name}...`, 'info');
  861. setTimeout(() => loadPPPoE(false), 2000);
  862. }
  863. } catch (err) {
  864. showToast('Error', err.message, 'error');
  865. }
  866. }
  867. async function disconnectPPPoEInstance(name) {
  868. try {
  869. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  870. if (res.ok) {
  871. showToast('Disconnected', `${name} session terminated`, 'info');
  872. setTimeout(() => loadPPPoE(false), 1000);
  873. }
  874. } catch (err) {
  875. showToast('Error', err.message, 'error');
  876. }
  877. }
  878. async function togglePPPoEState(name, enable) {
  879. try {
  880. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  881. method: 'POST',
  882. headers: { 'Content-Type': 'application/json' },
  883. body: JSON.stringify({ enabled: enable })
  884. });
  885. if (res.ok) {
  886. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  887. loadPPPoE(false);
  888. }
  889. } catch (err) {
  890. showToast('Error', err.message, 'error');
  891. }
  892. }
  893. async function deletePPPoEInstance(name) {
  894. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  895. try {
  896. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  897. if (res.ok) {
  898. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  899. loadPPPoE(false);
  900. fetchData(false);
  901. }
  902. } catch (err) {
  903. showToast('Error', err.message, 'error');
  904. }
  905. }
  906. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  907. state.wgSubTab = 'ifaces';
  908. function switchWGSubTab(tab) {
  909. state.wgSubTab = tab;
  910. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  911. const peersPanel = document.getElementById('wg-subtab-peers');
  912. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  913. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  914. if (tab === 'ifaces') {
  915. ifacesPanel?.classList.remove('hidden');
  916. peersPanel?.classList.add('hidden');
  917. 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';
  918. 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';
  919. } else {
  920. ifacesPanel?.classList.add('hidden');
  921. peersPanel?.classList.remove('hidden');
  922. 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';
  923. 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';
  924. renderWGPeers();
  925. }
  926. }
  927. async function loadWireGuard(populateInputs = true) {
  928. try {
  929. const [ifacesRes, peersRes] = await Promise.all([
  930. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  931. fetch(`${API_BASE}/vpn/wireguard/peers`)
  932. ]);
  933. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  934. const peers = peersRes.ok ? await peersRes.json() : [];
  935. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  936. state.wgPeers = Array.isArray(peers) ? peers : [];
  937. // Badges
  938. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  939. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  940. const peersCountBadge = document.getElementById('wg-peers-count');
  941. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  942. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  943. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  944. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  945. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  946. // Render Interfaces
  947. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  948. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  949. if (ifacesTbody) {
  950. ifacesTbody.innerHTML = '';
  951. if (state.wgInterfaces.length === 0) {
  952. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  953. } else {
  954. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  955. state.wgInterfaces.forEach(iface => {
  956. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  957. const tr = document.createElement('tr');
  958. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  959. tr.innerHTML = `
  960. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  961. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  962. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  963. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  964. <td class="py-2.5 px-3 text-slate-300 font-mono">
  965. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  966. ${(iface.public_key || '').substring(0, 10)}... 📋
  967. </span>
  968. </td>
  969. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  970. <td class="py-2.5 px-3 text-center">
  971. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  972. </td>
  973. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  974. ${iface.running ? `
  975. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  976. ` : `
  977. <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">Start</button>
  978. `}
  979. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  980. ${iface.disabled ? 'Enable' : 'Disable'}
  981. </button>
  982. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  983. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  984. </td>
  985. `;
  986. ifacesTbody.appendChild(tr);
  987. });
  988. }
  989. }
  990. // Populate filter dropdown in peers tab
  991. const filterSel = document.getElementById('wg-peers-filter-iface');
  992. if (filterSel) {
  993. const currentVal = filterSel.value;
  994. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  995. state.wgInterfaces.forEach(i => {
  996. const opt = document.createElement('option');
  997. opt.value = i.name;
  998. opt.innerText = i.name;
  999. if (i.name === currentVal) opt.selected = true;
  1000. filterSel.appendChild(opt);
  1001. });
  1002. }
  1003. renderWGPeers();
  1004. } catch (err) {
  1005. console.error('Failed to load WireGuard:', err);
  1006. }
  1007. }
  1008. function renderWGPeers() {
  1009. const filterSel = document.getElementById('wg-peers-filter-iface');
  1010. const selectedIface = filterSel ? filterSel.value : '';
  1011. const tbody = document.getElementById('wg-peers-table-body');
  1012. const empty = document.getElementById('wg-peers-empty');
  1013. if (!tbody) return;
  1014. tbody.innerHTML = '';
  1015. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1016. if (filtered.length === 0) {
  1017. if (empty) empty.classList.remove('hidden');
  1018. } else {
  1019. if (empty) empty.classList.add('hidden');
  1020. filtered.forEach(p => {
  1021. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1022. const tr = document.createElement('tr');
  1023. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1024. tr.innerHTML = `
  1025. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1026. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  1027. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  1028. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1029. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1030. ${p.public_key.substring(0, 10)}... 📋
  1031. </span>
  1032. </td>
  1033. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1034. <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>
  1035. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1036. <td class="py-2.5 px-3 font-mono text-[11px]">
  1037. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1038. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1039. </td>
  1040. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1041. <button onclick="openWGClientConfModal('${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>
  1042. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1043. </td>
  1044. `;
  1045. tbody.appendChild(tr);
  1046. });
  1047. }
  1048. }
  1049. function openAddWGInterfaceModal() {
  1050. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1051. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1052. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1053. document.getElementById('wg-iface-modal-name').readOnly = false;
  1054. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1055. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1056. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1057. document.getElementById('wg-iface-modal-pubkey').value = '';
  1058. document.getElementById('wg-iface-modal-privkey').value = '';
  1059. document.getElementById('wg-iface-modal-disabled').checked = false;
  1060. generateWGInterfaceKeys();
  1061. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1062. }
  1063. function openEditWGInterfaceModal(name) {
  1064. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1065. if (!iface) return;
  1066. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1067. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1068. document.getElementById('wg-iface-modal-name').value = iface.name;
  1069. document.getElementById('wg-iface-modal-name').readOnly = true;
  1070. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1071. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1072. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1073. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1074. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1075. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1076. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1077. }
  1078. function closeAddWGInterfaceModal() {
  1079. document.getElementById('wg-iface-modal').classList.add('hidden');
  1080. }
  1081. async function generateWGInterfaceKeys() {
  1082. try {
  1083. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1084. const keys = await res.json();
  1085. if (res.ok) {
  1086. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1087. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1088. }
  1089. } catch (err) {
  1090. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1091. }
  1092. }
  1093. async function submitSaveWGInterface(e) {
  1094. e.preventDefault();
  1095. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1096. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1097. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1098. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1099. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1100. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1101. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1102. try {
  1103. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1104. method: 'POST',
  1105. headers: { 'Content-Type': 'application/json' },
  1106. body: JSON.stringify({
  1107. name,
  1108. listen_port: port,
  1109. address: addr,
  1110. mtu,
  1111. public_key: pub,
  1112. private_key: priv,
  1113. disabled
  1114. })
  1115. });
  1116. if (res.ok) {
  1117. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1118. closeAddWGInterfaceModal();
  1119. loadWireGuard(false);
  1120. fetchData(false);
  1121. }
  1122. } catch (err) {
  1123. showToast('Error', err.message, 'error');
  1124. }
  1125. }
  1126. async function startWGInterface(name) {
  1127. try {
  1128. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1129. if (res.ok) {
  1130. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1131. loadWireGuard(false);
  1132. fetchData(false);
  1133. }
  1134. } catch (err) {
  1135. showToast('Error', err.message, 'error');
  1136. }
  1137. }
  1138. async function stopWGInterface(name) {
  1139. try {
  1140. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1141. if (res.ok) {
  1142. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1143. loadWireGuard(false);
  1144. fetchData(false);
  1145. }
  1146. } catch (err) {
  1147. showToast('Error', err.message, 'error');
  1148. }
  1149. }
  1150. async function toggleWGInterfaceState(name, enable) {
  1151. try {
  1152. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1153. method: 'POST',
  1154. headers: { 'Content-Type': 'application/json' },
  1155. body: JSON.stringify({ enabled: enable })
  1156. });
  1157. if (res.ok) {
  1158. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1159. loadWireGuard(false);
  1160. }
  1161. } catch (err) {
  1162. showToast('Error', err.message, 'error');
  1163. }
  1164. }
  1165. async function deleteWGInterface(name) {
  1166. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1167. try {
  1168. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1169. if (res.ok) {
  1170. showToast('Deleted', `Interface ${name} removed`, 'success');
  1171. loadWireGuard(false);
  1172. fetchData(false);
  1173. }
  1174. } catch (err) {
  1175. showToast('Error', err.message, 'error');
  1176. }
  1177. }
  1178. function openAddWGPeerModal() {
  1179. const sel = document.getElementById('wg-peer-modal-iface');
  1180. sel.innerHTML = '';
  1181. (state.wgInterfaces || []).forEach(i => {
  1182. const opt = document.createElement('option');
  1183. opt.value = i.name;
  1184. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1185. sel.appendChild(opt);
  1186. });
  1187. if ((state.wgInterfaces || []).length === 0) {
  1188. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1189. openAddWGInterfaceModal();
  1190. return;
  1191. }
  1192. document.getElementById('wg-peer-modal-name').value = '';
  1193. document.getElementById('wg-peer-modal-pubkey').value = '';
  1194. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1195. document.getElementById('wg-peer-modal-endpoint').value = '';
  1196. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1197. document.getElementById('wg-peer-modal-preshared').value = '';
  1198. document.getElementById('wg-peer-modal-disabled').checked = false;
  1199. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1200. }
  1201. function closeAddWGPeerModal() {
  1202. document.getElementById('wg-peer-modal').classList.add('hidden');
  1203. }
  1204. async function submitSaveWGPeer(e) {
  1205. e.preventDefault();
  1206. const iface = document.getElementById('wg-peer-modal-iface').value;
  1207. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1208. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1209. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1210. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1211. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1212. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1213. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1214. let epAddr = ep;
  1215. let epPort = 0;
  1216. if (ep.includes(':')) {
  1217. const parts = ep.split(':');
  1218. epAddr = parts[0];
  1219. epPort = parseInt(parts[1], 10) || 0;
  1220. }
  1221. try {
  1222. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1223. method: 'POST',
  1224. headers: { 'Content-Type': 'application/json' },
  1225. body: JSON.stringify({
  1226. interface: iface,
  1227. name,
  1228. public_key: pub,
  1229. allowed_ips: allowed,
  1230. endpoint_address: epAddr,
  1231. endpoint_port: epPort,
  1232. persistent_keepalive: keepalive,
  1233. preshared_key: psk,
  1234. disabled
  1235. })
  1236. });
  1237. if (res.ok) {
  1238. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1239. closeAddWGPeerModal();
  1240. loadWireGuard(false);
  1241. }
  1242. } catch (err) {
  1243. showToast('Error', err.message, 'error');
  1244. }
  1245. }
  1246. async function deleteWGPeer(iface, pubkey) {
  1247. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1248. try {
  1249. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1250. method: 'DELETE'
  1251. });
  1252. if (res.ok) {
  1253. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1254. loadWireGuard(false);
  1255. }
  1256. } catch (err) {
  1257. showToast('Error', err.message, 'error');
  1258. }
  1259. }
  1260. // ======================== IPSec Multi-Tunnel ========================
  1261. async function loadIPSec(populateInputs = true) {
  1262. try {
  1263. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1264. const list = await res.json();
  1265. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1266. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1267. const badge = document.getElementById('ipsec-sas-badge');
  1268. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1269. const tbody = document.getElementById('ipsec-table-body');
  1270. const empty = document.getElementById('ipsec-empty');
  1271. if (!tbody) return;
  1272. tbody.innerHTML = '';
  1273. if (state.ipsecTunnels.length === 0) {
  1274. if (empty) empty.classList.remove('hidden');
  1275. } else {
  1276. if (empty) empty.classList.add('hidden');
  1277. state.ipsecTunnels.forEach(c => {
  1278. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1279. const tr = document.createElement('tr');
  1280. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1281. tr.innerHTML = `
  1282. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1283. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1284. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1285. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1286. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1287. <td class="py-2.5 px-4 font-sans">
  1288. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1289. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1290. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1291. </td>
  1292. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1293. ${isEstablished ? `
  1294. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1295. ` : `
  1296. <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>
  1297. `}
  1298. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1299. ${c.disabled ? 'Enable' : 'Disable'}
  1300. </button>
  1301. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1302. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1303. </td>
  1304. `;
  1305. tbody.appendChild(tr);
  1306. });
  1307. }
  1308. } catch (err) {
  1309. console.error('Failed to load IPSec:', err);
  1310. }
  1311. }
  1312. function openAddIPSecModal() {
  1313. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1314. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1315. document.getElementById('ipsec-modal-name').readOnly = false;
  1316. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1317. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1318. document.getElementById('ipsec-modal-remotegw').value = '';
  1319. document.getElementById('ipsec-modal-psk').value = '';
  1320. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1321. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1322. document.getElementById('ipsec-modal-autostart').checked = true;
  1323. document.getElementById('ipsec-modal-disabled').checked = false;
  1324. document.getElementById('ipsec-modal').classList.remove('hidden');
  1325. }
  1326. function openEditIPSecModal(name) {
  1327. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1328. if (!conn) return;
  1329. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1330. document.getElementById('ipsec-modal-name').value = conn.name;
  1331. document.getElementById('ipsec-modal-name').readOnly = true;
  1332. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1333. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1334. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1335. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1336. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1337. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1338. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1339. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1340. document.getElementById('ipsec-modal').classList.remove('hidden');
  1341. }
  1342. function closeAddIPSecModal() {
  1343. document.getElementById('ipsec-modal').classList.add('hidden');
  1344. }
  1345. async function submitSaveIPSec(e) {
  1346. e.preventDefault();
  1347. const name = document.getElementById('ipsec-modal-name').value.trim();
  1348. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1349. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1350. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1351. const psk = document.getElementById('ipsec-modal-psk').value;
  1352. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1353. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1354. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1355. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1356. try {
  1357. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1358. method: 'POST',
  1359. headers: { 'Content-Type': 'application/json' },
  1360. body: JSON.stringify({
  1361. name,
  1362. local_addrs: '%any',
  1363. remote_addrs: remotegw,
  1364. local_subnet: localts,
  1365. remote_subnet: remotets,
  1366. preshared_key: psk,
  1367. ike_proposals: ike,
  1368. esp_proposals: esp,
  1369. auto_start: autostart,
  1370. disabled
  1371. })
  1372. });
  1373. if (res.ok) {
  1374. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1375. closeAddIPSecModal();
  1376. loadIPSec(false);
  1377. fetchData(false);
  1378. }
  1379. } catch (err) {
  1380. showToast('Error', err.message, 'error');
  1381. }
  1382. }
  1383. async function startIPSecTunnel(name) {
  1384. try {
  1385. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1386. if (res.ok) {
  1387. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1388. setTimeout(() => loadIPSec(false), 2000);
  1389. }
  1390. } catch (err) {
  1391. showToast('Error', err.message, 'error');
  1392. }
  1393. }
  1394. async function stopIPSecTunnel(name) {
  1395. try {
  1396. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1397. if (res.ok) {
  1398. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1399. loadIPSec(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function toggleIPSecState(name, enable) {
  1406. try {
  1407. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1408. method: 'POST',
  1409. headers: { 'Content-Type': 'application/json' },
  1410. body: JSON.stringify({ enabled: enable })
  1411. });
  1412. if (res.ok) {
  1413. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1414. loadIPSec(false);
  1415. }
  1416. } catch (err) {
  1417. showToast('Error', err.message, 'error');
  1418. }
  1419. }
  1420. async function deleteIPSecConn(name) {
  1421. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1422. try {
  1423. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1424. if (res.ok) {
  1425. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1426. loadIPSec(false);
  1427. fetchData(false);
  1428. }
  1429. } catch (err) {
  1430. showToast('Error', err.message, 'error');
  1431. }
  1432. }
  1433. // ======================== L2TP Multi-Instance ========================
  1434. async function loadL2TP(populateInputs = true) {
  1435. try {
  1436. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1437. const list = await res.json();
  1438. state.l2tpList = Array.isArray(list) ? list : [];
  1439. const badge = document.getElementById('l2tp-count-badge');
  1440. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1441. const tbody = document.getElementById('l2tp-table-body');
  1442. const empty = document.getElementById('l2tp-empty');
  1443. if (!tbody) return;
  1444. tbody.innerHTML = '';
  1445. if (state.l2tpList.length === 0) {
  1446. if (empty) empty.classList.remove('hidden');
  1447. } else {
  1448. if (empty) empty.classList.add('hidden');
  1449. state.l2tpList.forEach(inst => {
  1450. const tr = document.createElement('tr');
  1451. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1452. tr.innerHTML = `
  1453. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1454. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1455. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1456. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1457. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1458. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1459. <td class="py-2.5 px-3 text-center">
  1460. <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'}">
  1461. ${inst.default_route ? 'Yes' : 'No'}
  1462. </span>
  1463. </td>
  1464. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1465. ${inst.running ? `
  1466. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1467. ` : `
  1468. <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>
  1469. `}
  1470. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1471. ${inst.disabled ? 'Enable' : 'Disable'}
  1472. </button>
  1473. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1474. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1475. </td>
  1476. `;
  1477. tbody.appendChild(tr);
  1478. });
  1479. }
  1480. } catch (err) {
  1481. console.error('Failed to load L2TP:', err);
  1482. }
  1483. }
  1484. function openAddL2TPModal() {
  1485. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1486. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1487. document.getElementById('l2tp-modal-name').readOnly = false;
  1488. document.getElementById('l2tp-modal-server').value = '';
  1489. document.getElementById('l2tp-modal-user').value = '';
  1490. document.getElementById('l2tp-modal-pass').value = '';
  1491. document.getElementById('l2tp-modal-ipsec').value = '';
  1492. document.getElementById('l2tp-modal-defroute').checked = true;
  1493. document.getElementById('l2tp-modal-disabled').checked = false;
  1494. document.getElementById('l2tp-modal').classList.remove('hidden');
  1495. }
  1496. function openEditL2TPModal(name) {
  1497. const inst = (state.l2tpList || []).find(i => i.name === name);
  1498. if (!inst) return;
  1499. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1500. document.getElementById('l2tp-modal-name').value = inst.name;
  1501. document.getElementById('l2tp-modal-name').readOnly = true;
  1502. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1503. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1504. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1505. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1506. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1507. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1508. document.getElementById('l2tp-modal').classList.remove('hidden');
  1509. }
  1510. function closeL2TPModal() {
  1511. document.getElementById('l2tp-modal').classList.add('hidden');
  1512. }
  1513. async function submitSaveL2TP(e) {
  1514. e.preventDefault();
  1515. const name = document.getElementById('l2tp-modal-name').value.trim();
  1516. const server = document.getElementById('l2tp-modal-server').value.trim();
  1517. const user = document.getElementById('l2tp-modal-user').value.trim();
  1518. const pass = document.getElementById('l2tp-modal-pass').value;
  1519. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1520. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1521. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1522. try {
  1523. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1524. method: 'POST',
  1525. headers: { 'Content-Type': 'application/json' },
  1526. body: JSON.stringify({
  1527. name,
  1528. connect_to: server,
  1529. username: user,
  1530. password: pass,
  1531. ipsec_secret: ipsec,
  1532. default_route: defRoute,
  1533. disabled
  1534. })
  1535. });
  1536. if (res.ok) {
  1537. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1538. closeL2TPModal();
  1539. loadL2TP(false);
  1540. fetchData(false);
  1541. }
  1542. } catch (err) {
  1543. showToast('Error', err.message, 'error');
  1544. }
  1545. }
  1546. async function connectL2TPInstance(name) {
  1547. try {
  1548. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1549. if (res.ok) {
  1550. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1551. setTimeout(() => loadL2TP(false), 2000);
  1552. }
  1553. } catch (err) {
  1554. showToast('Error', err.message, 'error');
  1555. }
  1556. }
  1557. async function disconnectL2TPInstance(name) {
  1558. try {
  1559. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1560. if (res.ok) {
  1561. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1562. loadL2TP(false);
  1563. }
  1564. } catch (err) {
  1565. showToast('Error', err.message, 'error');
  1566. }
  1567. }
  1568. async function toggleL2TPState(name, enable) {
  1569. try {
  1570. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1571. method: 'POST',
  1572. headers: { 'Content-Type': 'application/json' },
  1573. body: JSON.stringify({ enabled: enable })
  1574. });
  1575. if (res.ok) {
  1576. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1577. loadL2TP(false);
  1578. }
  1579. } catch (err) {
  1580. showToast('Error', err.message, 'error');
  1581. }
  1582. }
  1583. async function deleteL2TPInstance(name) {
  1584. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1585. try {
  1586. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1587. if (res.ok) {
  1588. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1589. loadL2TP(false);
  1590. fetchData(false);
  1591. }
  1592. } catch (err) {
  1593. showToast('Error', err.message, 'error');
  1594. }
  1595. }
  1596. // ======================== PPTP Multi-Instance ========================
  1597. async function loadPPTP(populateInputs = true) {
  1598. try {
  1599. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1600. const list = await res.json();
  1601. state.pptpList = Array.isArray(list) ? list : [];
  1602. const badge = document.getElementById('pptp-count-badge');
  1603. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1604. const tbody = document.getElementById('pptp-table-body');
  1605. const empty = document.getElementById('pptp-empty');
  1606. if (!tbody) return;
  1607. tbody.innerHTML = '';
  1608. if (state.pptpList.length === 0) {
  1609. if (empty) empty.classList.remove('hidden');
  1610. } else {
  1611. if (empty) empty.classList.add('hidden');
  1612. state.pptpList.forEach(inst => {
  1613. const tr = document.createElement('tr');
  1614. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1615. tr.innerHTML = `
  1616. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1617. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1618. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1619. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1620. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1621. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1622. <td class="py-2.5 px-3 text-center">
  1623. <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'}">
  1624. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1625. </span>
  1626. </td>
  1627. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1628. ${inst.running ? `
  1629. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1630. ` : `
  1631. <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>
  1632. `}
  1633. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1634. ${inst.disabled ? 'Enable' : 'Disable'}
  1635. </button>
  1636. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1637. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1638. </td>
  1639. `;
  1640. tbody.appendChild(tr);
  1641. });
  1642. }
  1643. } catch (err) {
  1644. console.error('Failed to load PPTP:', err);
  1645. }
  1646. }
  1647. function openAddPPTPModal() {
  1648. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1649. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1650. document.getElementById('pptp-modal-name').readOnly = false;
  1651. document.getElementById('pptp-modal-server').value = '';
  1652. document.getElementById('pptp-modal-user').value = '';
  1653. document.getElementById('pptp-modal-pass').value = '';
  1654. document.getElementById('pptp-modal-mppe').checked = true;
  1655. document.getElementById('pptp-modal-defroute').checked = true;
  1656. document.getElementById('pptp-modal-disabled').checked = false;
  1657. document.getElementById('pptp-modal').classList.remove('hidden');
  1658. }
  1659. function openEditPPTPModal(name) {
  1660. const inst = (state.pptpList || []).find(i => i.name === name);
  1661. if (!inst) return;
  1662. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1663. document.getElementById('pptp-modal-name').value = inst.name;
  1664. document.getElementById('pptp-modal-name').readOnly = true;
  1665. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1666. document.getElementById('pptp-modal-user').value = inst.username || '';
  1667. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1668. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1669. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1670. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1671. document.getElementById('pptp-modal').classList.remove('hidden');
  1672. }
  1673. function closePPTPModal() {
  1674. document.getElementById('pptp-modal').classList.add('hidden');
  1675. }
  1676. async function submitSavePPTP(e) {
  1677. e.preventDefault();
  1678. const name = document.getElementById('pptp-modal-name').value.trim();
  1679. const server = document.getElementById('pptp-modal-server').value.trim();
  1680. const user = document.getElementById('pptp-modal-user').value.trim();
  1681. const pass = document.getElementById('pptp-modal-pass').value;
  1682. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1683. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1684. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1685. try {
  1686. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1687. method: 'POST',
  1688. headers: { 'Content-Type': 'application/json' },
  1689. body: JSON.stringify({
  1690. name,
  1691. connect_to: server,
  1692. username: user,
  1693. password: pass,
  1694. require_mppe: mppe,
  1695. default_route: defRoute,
  1696. auto_reconnect: true,
  1697. disabled
  1698. })
  1699. });
  1700. if (res.ok) {
  1701. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1702. closePPTPModal();
  1703. loadPPTP(false);
  1704. fetchData(false);
  1705. }
  1706. } catch (err) {
  1707. showToast('Error', err.message, 'error');
  1708. }
  1709. }
  1710. async function connectPPTPInstance(name) {
  1711. try {
  1712. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1713. if (res.ok) {
  1714. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1715. setTimeout(() => loadPPTP(false), 2000);
  1716. }
  1717. } catch (err) {
  1718. showToast('Error', err.message, 'error');
  1719. }
  1720. }
  1721. async function disconnectPPTPInstance(name) {
  1722. try {
  1723. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1724. if (res.ok) {
  1725. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1726. loadPPTP(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. async function togglePPTPState(name, enable) {
  1733. try {
  1734. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1735. method: 'POST',
  1736. headers: { 'Content-Type': 'application/json' },
  1737. body: JSON.stringify({ enabled: enable })
  1738. });
  1739. if (res.ok) {
  1740. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1741. loadPPTP(false);
  1742. }
  1743. } catch (err) {
  1744. showToast('Error', err.message, 'error');
  1745. }
  1746. }
  1747. async function deletePPTPInstance(name) {
  1748. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1749. try {
  1750. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1751. if (res.ok) {
  1752. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1753. loadPPTP(false);
  1754. fetchData(false);
  1755. }
  1756. } catch (err) {
  1757. showToast('Error', err.message, 'error');
  1758. }
  1759. }
  1760. // ---------------- Modal & Helper Functions ----------------
  1761. function openVlanModal(defaultParent = '') {
  1762. const select = document.getElementById('vlan-parent');
  1763. select.innerHTML = '';
  1764. const allIfaces = state.interfaces || [];
  1765. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1766. if (eligible.length === 0) {
  1767. allIfaces.forEach(i => eligible.push(i));
  1768. }
  1769. eligible.forEach(i => {
  1770. const opt = document.createElement('option');
  1771. opt.value = i.name;
  1772. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1773. if (i.name === defaultParent) opt.selected = true;
  1774. select.appendChild(opt);
  1775. });
  1776. document.getElementById('vlan-id').value = '';
  1777. document.getElementById('vlan-name').value = '';
  1778. document.getElementById('vlan-ip').value = '';
  1779. document.getElementById('vlan-desc').value = '';
  1780. autoSuggestVlanName();
  1781. document.getElementById('vlan-modal').classList.remove('hidden');
  1782. }
  1783. function closeVlanModal() {
  1784. document.getElementById('vlan-modal').classList.add('hidden');
  1785. }
  1786. function autoSuggestVlanName() {
  1787. const parent = document.getElementById('vlan-parent').value;
  1788. const id = document.getElementById('vlan-id').value;
  1789. const nameInput = document.getElementById('vlan-name');
  1790. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1791. }
  1792. function setSubnetPreset(cidr) {
  1793. const ipInput = document.getElementById('vlan-ip');
  1794. const id = document.getElementById('vlan-id').value || '10';
  1795. ipInput.value = `192.168.${id}.1${cidr}`;
  1796. }
  1797. async function submitCreateVlan(e) {
  1798. e.preventDefault();
  1799. const btn = document.getElementById('vlan-submit-btn');
  1800. btn.disabled = true;
  1801. btn.innerText = 'Creating...';
  1802. const parent = document.getElementById('vlan-parent').value;
  1803. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1804. const name = document.getElementById('vlan-name').value.trim();
  1805. const ip = document.getElementById('vlan-ip').value.trim();
  1806. const role = document.getElementById('vlan-role').value;
  1807. const desc = document.getElementById('vlan-desc').value.trim();
  1808. try {
  1809. const res = await fetch(`${API_BASE}/vlans`, {
  1810. method: 'POST',
  1811. headers: { 'Content-Type': 'application/json' },
  1812. body: JSON.stringify({
  1813. parent_name: parent,
  1814. vlan_id: id,
  1815. name: name,
  1816. ip_address: ip,
  1817. role: role,
  1818. description: desc,
  1819. mtu: 1500,
  1820. auto_up: true
  1821. })
  1822. });
  1823. const data = await res.json();
  1824. if (res.ok) {
  1825. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1826. state.expandedParents.add(parent);
  1827. closeVlanModal();
  1828. await fetchData(true);
  1829. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1830. } else {
  1831. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1832. }
  1833. } catch (err) {
  1834. showToast('Error', err.message, 'error');
  1835. } finally {
  1836. btn.disabled = false;
  1837. btn.innerText = 'Create VLAN';
  1838. }
  1839. }
  1840. async function confirmDeleteVlan(name) {
  1841. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1842. try {
  1843. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1844. if (res.ok) {
  1845. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1846. closeIfaceModal();
  1847. fetchData(true);
  1848. }
  1849. } catch (err) {
  1850. showToast('Error', err.message, 'error');
  1851. }
  1852. }
  1853. function openIfaceModal(name) {
  1854. const iface = (state.interfaces || []).find(i => i.name === name);
  1855. if (!iface) return;
  1856. state.currentModalIface = iface.name;
  1857. document.getElementById('modal-iface-name').innerText = iface.name;
  1858. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1859. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1860. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1861. document.getElementById('modal-iface-desc').value = iface.description || '';
  1862. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1863. if (iface.is_vlan) {
  1864. delBtn.classList.remove('hidden');
  1865. } else {
  1866. delBtn.classList.add('hidden');
  1867. }
  1868. renderModalIPs(iface);
  1869. document.getElementById('iface-modal').classList.remove('hidden');
  1870. }
  1871. function renderModalIPs(iface) {
  1872. const container = document.getElementById('modal-ip-list');
  1873. container.innerHTML = '';
  1874. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1875. if (addrs.length === 0) {
  1876. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1877. return;
  1878. }
  1879. addrs.forEach(addr => {
  1880. const row = document.createElement('div');
  1881. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1882. row.innerHTML = `
  1883. <span class="text-white">${addr}</span>
  1884. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1885. `;
  1886. container.appendChild(row);
  1887. });
  1888. }
  1889. function closeIfaceModal() {
  1890. document.getElementById('iface-modal').classList.add('hidden');
  1891. state.currentModalIface = null;
  1892. }
  1893. async function setIfaceState(name, newState) {
  1894. await toggleInterfaceState(name, newState);
  1895. const updated = (state.interfaces || []).find(i => i.name === name);
  1896. if (updated) openIfaceModal(name);
  1897. }
  1898. async function applyMTU() {
  1899. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1900. try {
  1901. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1902. method: 'POST',
  1903. headers: { 'Content-Type': 'application/json' },
  1904. body: JSON.stringify({ mtu })
  1905. });
  1906. if (res.ok) {
  1907. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1908. fetchData(false);
  1909. }
  1910. } catch (err) {
  1911. showToast('Error', err.message, 'error');
  1912. }
  1913. }
  1914. async function addInterfaceIP() {
  1915. const ip = document.getElementById('modal-new-ip').value.trim();
  1916. if (!ip) return;
  1917. try {
  1918. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1919. method: 'POST',
  1920. headers: { 'Content-Type': 'application/json' },
  1921. body: JSON.stringify({ ip })
  1922. });
  1923. if (res.ok) {
  1924. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1925. document.getElementById('modal-new-ip').value = '';
  1926. await fetchData(false);
  1927. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1928. if (iface) renderModalIPs(iface);
  1929. } else {
  1930. const err = await res.json();
  1931. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1932. }
  1933. } catch (err) {
  1934. showToast('Error', err.message, 'error');
  1935. }
  1936. }
  1937. async function removeInterfaceIP(ip) {
  1938. if (!confirm(`Remove IP ${ip}?`)) return;
  1939. try {
  1940. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1941. method: 'DELETE',
  1942. headers: { 'Content-Type': 'application/json' },
  1943. body: JSON.stringify({ ip })
  1944. });
  1945. if (res.ok) {
  1946. showToast('IP Removed', `Removed ${ip}`, 'success');
  1947. await fetchData(false);
  1948. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1949. if (iface) renderModalIPs(iface);
  1950. }
  1951. } catch (err) {
  1952. showToast('Error', err.message, 'error');
  1953. }
  1954. }
  1955. async function saveInterfaceMetadata() {
  1956. const role = document.getElementById('modal-iface-role').value;
  1957. const desc = document.getElementById('modal-iface-desc').value.trim();
  1958. try {
  1959. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1960. method: 'POST',
  1961. headers: { 'Content-Type': 'application/json' },
  1962. body: JSON.stringify({ role, description: desc })
  1963. });
  1964. if (res.ok) {
  1965. showToast('Saved', 'Metadata updated', 'success');
  1966. closeIfaceModal();
  1967. fetchData(false);
  1968. }
  1969. } catch (err) {
  1970. showToast('Error', err.message, 'error');
  1971. }
  1972. }
  1973. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1974. state.fwSubTab = 'filter';
  1975. state.routesSubTab = 'routes';
  1976. function renderRuleFlag(disabled, hasComment) {
  1977. let flags = '';
  1978. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1979. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1980. return flags || '<span class="text-slate-600">-</span>';
  1981. }
  1982. function renderActionBadge(action) {
  1983. const act = (action || '').toLowerCase();
  1984. let color = 'bg-slate-800 text-slate-300';
  1985. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1986. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1987. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1988. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1989. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1990. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1991. }
  1992. function switchFWSubTab(tab) {
  1993. state.fwSubTab = tab;
  1994. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1995. tabs.forEach(t => {
  1996. const panel = document.getElementById(`fw-subtab-${t}`);
  1997. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1998. if (panel) {
  1999. if (t === tab) panel.classList.remove('hidden');
  2000. else panel.classList.add('hidden');
  2001. }
  2002. if (btn) {
  2003. if (t === tab) {
  2004. 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';
  2005. } else {
  2006. 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';
  2007. }
  2008. }
  2009. });
  2010. const addBtn = document.getElementById('fw-primary-add-btn');
  2011. if (addBtn) {
  2012. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2013. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2014. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2015. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2016. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2017. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2018. }
  2019. if (tab === 'geo') loadGeoIP();
  2020. if (tab === 'connections') loadConnections();
  2021. }
  2022. function openCurrentFWModal() {
  2023. if (state.fwSubTab === 'filter') openAddFilterModal();
  2024. else if (state.fwSubTab === 'nat') openAddNATModal();
  2025. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2026. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2027. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2028. else if (state.fwSubTab === 'connections') loadConnections();
  2029. }
  2030. async function loadFirewall(populateDropdowns = true) {
  2031. try {
  2032. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2033. fetch(`${API_BASE}/firewall/summary`),
  2034. fetch(`${API_BASE}/firewall/filter`),
  2035. fetch(`${API_BASE}/firewall/nat`),
  2036. fetch(`${API_BASE}/firewall/mangle`),
  2037. fetch(`${API_BASE}/firewall/address-lists`),
  2038. fetch(`${API_BASE}/firewall/geoip/status`),
  2039. fetch(`${API_BASE}/firewall/geoip/countries`)
  2040. ]);
  2041. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2042. if (filterRes.ok) state.filterRules = await filterRes.json();
  2043. if (natRes.ok) state.natRules = await natRes.json();
  2044. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2045. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2046. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2047. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2048. // Badges
  2049. const bFilter = document.getElementById('fw-badge-filter');
  2050. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2051. const bNat = document.getElementById('fw-badge-nat');
  2052. if (bNat) bNat.innerText = (state.natRules || []).length;
  2053. const bMangle = document.getElementById('fw-badge-mangle');
  2054. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2055. const bAddr = document.getElementById('fw-badge-addrlist');
  2056. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2057. const bGeo = document.getElementById('fw-badge-geo');
  2058. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2059. renderFilterRules();
  2060. renderNATRules();
  2061. renderMangleRules();
  2062. renderAddressLists();
  2063. renderGeoCountries();
  2064. if (state.fwSubTab === 'connections') {
  2065. loadConnections();
  2066. }
  2067. } catch (err) {
  2068. console.error('Failed to load firewall:', err);
  2069. }
  2070. }
  2071. // ----------------- Filter Rules -----------------
  2072. function renderFilterRules() {
  2073. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2074. const tbody = document.getElementById('filter-table-body');
  2075. const empty = document.getElementById('filter-empty');
  2076. if (!tbody) return;
  2077. tbody.innerHTML = '';
  2078. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2079. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2080. if (rules.length === 0) {
  2081. empty?.classList.remove('hidden');
  2082. return;
  2083. }
  2084. empty?.classList.add('hidden');
  2085. rules.forEach((r, idx) => {
  2086. const tr = document.createElement('tr');
  2087. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2088. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2089. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2090. tr.innerHTML = `
  2091. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2092. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2093. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2094. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2095. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2096. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2097. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2098. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2099. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2100. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2101. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2102. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2103. </td>
  2104. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2105. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2106. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2107. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2108. <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>
  2109. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2110. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2111. </td>
  2112. `;
  2113. tbody.appendChild(tr);
  2114. });
  2115. }
  2116. function formatTarget(addr, list, geo) {
  2117. const parts = [];
  2118. if (addr) parts.push(`<span>${addr}</span>`);
  2119. if (list) {
  2120. const inv = list.startsWith('!') ? '!' : '';
  2121. const clean = list.replace(/^!/, '');
  2122. 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>`);
  2123. }
  2124. if (geo) {
  2125. const inv = geo.startsWith('!') ? '!' : '';
  2126. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2127. 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>`);
  2128. }
  2129. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2130. return parts.join(' ');
  2131. }
  2132. function populateInterfaceSelect(selectId, currentVal = '') {
  2133. const sel = document.getElementById(selectId);
  2134. if (!sel) return;
  2135. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2136. (state.interfaces || []).forEach(i => {
  2137. const opt = document.createElement('option');
  2138. opt.value = i.name;
  2139. opt.innerText = `${i.name} (${i.role || i.type})`;
  2140. if (i.name === currentVal) opt.selected = true;
  2141. sel.appendChild(opt);
  2142. });
  2143. }
  2144. function populateAddressListSelect(selectId, currentVal = '') {
  2145. const sel = document.getElementById(selectId);
  2146. if (!sel) return;
  2147. sel.innerHTML = '<option value="">(None)</option>';
  2148. const cleanVal = (currentVal || '').replace(/^!/, '');
  2149. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2150. customNames.forEach(name => {
  2151. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2152. const opt = document.createElement('option');
  2153. opt.value = name;
  2154. opt.innerText = `${name} (${count} entries)`;
  2155. if (name === cleanVal) opt.selected = true;
  2156. sel.appendChild(opt);
  2157. });
  2158. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2159. const opt = document.createElement('option');
  2160. opt.value = cleanVal;
  2161. opt.innerText = cleanVal;
  2162. opt.selected = true;
  2163. sel.appendChild(opt);
  2164. }
  2165. }
  2166. function populateGeoIPSelect(selectId, currentVal = '') {
  2167. const sel = document.getElementById(selectId);
  2168. if (!sel) return;
  2169. sel.innerHTML = '<option value="">(None)</option>';
  2170. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2171. // Presets optgroup
  2172. const grpPresets = document.createElement('optgroup');
  2173. grpPresets.label = '⚡ Regional Presets';
  2174. const presets = [
  2175. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2176. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2177. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2178. ];
  2179. presets.forEach(p => {
  2180. const opt = document.createElement('option');
  2181. opt.value = p.code;
  2182. opt.innerText = p.label;
  2183. if (p.code === cleanVal) opt.selected = true;
  2184. grpPresets.appendChild(opt);
  2185. });
  2186. sel.appendChild(grpPresets);
  2187. // All Countries optgroup
  2188. const grpCountries = document.createElement('optgroup');
  2189. grpCountries.label = '🌍 All Countries';
  2190. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2191. countries.forEach(c => {
  2192. const opt = document.createElement('option');
  2193. opt.value = c.code;
  2194. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2195. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2196. if (c.code === cleanVal) opt.selected = true;
  2197. grpCountries.appendChild(opt);
  2198. });
  2199. sel.appendChild(grpCountries);
  2200. }
  2201. function openAddFilterModal() {
  2202. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2203. document.getElementById('filter-modal-id').value = '';
  2204. document.getElementById('filter-modal-chain').value = 'forward';
  2205. document.getElementById('filter-modal-action').value = 'accept';
  2206. document.getElementById('filter-modal-proto').value = 'all';
  2207. document.getElementById('filter-modal-src').value = '';
  2208. document.getElementById('filter-modal-dst').value = '';
  2209. document.getElementById('filter-modal-sport').value = '';
  2210. document.getElementById('filter-modal-dport').value = '';
  2211. document.getElementById('filter-modal-connmark').value = '';
  2212. document.getElementById('filter-modal-comment').value = '';
  2213. document.getElementById('filter-modal-disabled').checked = false;
  2214. document.getElementById('filter-modal-cs-established').checked = false;
  2215. document.getElementById('filter-modal-cs-related').checked = false;
  2216. document.getElementById('filter-modal-cs-new').checked = false;
  2217. document.getElementById('filter-modal-cs-invalid').checked = false;
  2218. populateInterfaceSelect('filter-modal-iniface');
  2219. populateInterfaceSelect('filter-modal-outiface');
  2220. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2221. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2222. populateAddressListSelect('filter-modal-srclist');
  2223. populateAddressListSelect('filter-modal-dstlist');
  2224. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2225. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2226. populateGeoIPSelect('filter-modal-srcgeoip');
  2227. populateGeoIPSelect('filter-modal-dstgeoip');
  2228. toggleFilterActionFields();
  2229. document.getElementById('filter-modal').classList.remove('hidden');
  2230. }
  2231. function openEditFilterModal(id) {
  2232. const r = (state.filterRules || []).find(rule => rule.id === id);
  2233. if (!r) return;
  2234. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2235. document.getElementById('filter-modal-id').value = r.id;
  2236. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2237. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2238. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2239. document.getElementById('filter-modal-src').value = r.src_address || '';
  2240. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2241. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2242. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2243. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2244. document.getElementById('filter-modal-comment').value = r.comment || '';
  2245. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2246. const states = r.connection_state || [];
  2247. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2248. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2249. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2250. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2251. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2252. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2253. const srcInv = (r.src_address_list || '').startsWith('!');
  2254. const dstInv = (r.dst_address_list || '').startsWith('!');
  2255. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2256. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2257. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2258. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2259. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2260. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2261. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2262. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2263. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2264. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2265. toggleFilterActionFields();
  2266. document.getElementById('filter-modal').classList.remove('hidden');
  2267. }
  2268. function closeFilterModal() {
  2269. document.getElementById('filter-modal').classList.add('hidden');
  2270. }
  2271. function toggleFilterActionFields() {
  2272. const act = document.getElementById('filter-modal-action').value;
  2273. const rejectBox = document.getElementById('filter-action-reject-box');
  2274. if (rejectBox) {
  2275. if (act === 'reject') rejectBox.classList.remove('hidden');
  2276. else rejectBox.classList.add('hidden');
  2277. }
  2278. }
  2279. async function submitSaveFilterRule(e) {
  2280. e.preventDefault();
  2281. const id = document.getElementById('filter-modal-id').value;
  2282. const chain = document.getElementById('filter-modal-chain').value;
  2283. const action = document.getElementById('filter-modal-action').value;
  2284. const proto = document.getElementById('filter-modal-proto').value;
  2285. const src = document.getElementById('filter-modal-src').value.trim();
  2286. const dst = document.getElementById('filter-modal-dst').value.trim();
  2287. const sport = document.getElementById('filter-modal-sport').value.trim();
  2288. const dport = document.getElementById('filter-modal-dport').value.trim();
  2289. const inIface = document.getElementById('filter-modal-iniface').value;
  2290. const outIface = document.getElementById('filter-modal-outiface').value;
  2291. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2292. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2293. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2294. srclist = '!' + srclist.replace(/^!/, '');
  2295. }
  2296. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2297. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2298. dstlist = '!' + dstlist.replace(/^!/, '');
  2299. }
  2300. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2301. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2302. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2303. }
  2304. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2305. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2306. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2307. }
  2308. const comment = document.getElementById('filter-modal-comment').value.trim();
  2309. const disabled = document.getElementById('filter-modal-disabled').checked;
  2310. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2311. const states = [];
  2312. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2313. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2314. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2315. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2316. try {
  2317. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2318. method: 'POST',
  2319. headers: { 'Content-Type': 'application/json' },
  2320. body: JSON.stringify({
  2321. id,
  2322. chain,
  2323. action,
  2324. reject_with: rejectWith,
  2325. protocol: proto,
  2326. src_address: src,
  2327. dst_address: dst,
  2328. src_port: sport,
  2329. dst_port: dport,
  2330. in_interface: inIface,
  2331. out_interface: outIface,
  2332. connection_state: states,
  2333. connection_mark: connmark,
  2334. src_address_list: srclist,
  2335. dst_address_list: dstlist,
  2336. src_geoip: srcgeoip,
  2337. dst_geoip: dstgeoip,
  2338. comment,
  2339. disabled
  2340. })
  2341. });
  2342. if (res.ok) {
  2343. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2344. closeFilterModal();
  2345. loadFirewall(false);
  2346. } else {
  2347. const err = await res.json();
  2348. showToast('Error', err.message, 'error');
  2349. }
  2350. } catch (err) {
  2351. showToast('Error', err.message, 'error');
  2352. }
  2353. }
  2354. async function moveFilterRule(id, dir) {
  2355. try {
  2356. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2357. method: 'POST',
  2358. headers: { 'Content-Type': 'application/json' },
  2359. body: JSON.stringify({ direction: dir })
  2360. });
  2361. if (res.ok) loadFirewall(false);
  2362. } catch (err) {
  2363. showToast('Error', err.message, 'error');
  2364. }
  2365. }
  2366. async function toggleFilterRuleState(id, disabled) {
  2367. try {
  2368. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2369. method: 'POST',
  2370. headers: { 'Content-Type': 'application/json' },
  2371. body: JSON.stringify({ disabled })
  2372. });
  2373. if (res.ok) loadFirewall(false);
  2374. } catch (err) {
  2375. showToast('Error', err.message, 'error');
  2376. }
  2377. }
  2378. async function deleteFilterRule(id) {
  2379. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2380. try {
  2381. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2382. if (res.ok) {
  2383. showToast('Deleted', 'Filter rule removed', 'success');
  2384. loadFirewall(false);
  2385. }
  2386. } catch (err) {
  2387. showToast('Error', err.message, 'error');
  2388. }
  2389. }
  2390. // ----------------- NAT Rules -----------------
  2391. function renderNATRules() {
  2392. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2393. const tbody = document.getElementById('nat-table-body');
  2394. const empty = document.getElementById('nat-empty');
  2395. if (!tbody) return;
  2396. tbody.innerHTML = '';
  2397. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2398. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2399. if (rules.length === 0) {
  2400. empty?.classList.remove('hidden');
  2401. return;
  2402. }
  2403. empty?.classList.add('hidden');
  2404. rules.forEach((r, idx) => {
  2405. const tr = document.createElement('tr');
  2406. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2407. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2408. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2409. tr.innerHTML = `
  2410. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2411. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2412. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2413. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2414. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2415. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2416. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2417. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2418. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2419. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2420. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2421. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2422. </td>
  2423. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2424. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2425. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2426. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2427. <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>
  2428. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2429. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2430. </td>
  2431. `;
  2432. tbody.appendChild(tr);
  2433. });
  2434. }
  2435. function openAddNATModal() {
  2436. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2437. document.getElementById('nat-modal-id').value = '';
  2438. document.getElementById('nat-modal-chain').value = 'srcnat';
  2439. document.getElementById('nat-modal-action').value = 'masquerade';
  2440. document.getElementById('nat-modal-toaddr').value = '';
  2441. document.getElementById('nat-modal-toport').value = '';
  2442. document.getElementById('nat-modal-proto').value = 'all';
  2443. document.getElementById('nat-modal-src').value = '';
  2444. document.getElementById('nat-modal-dst').value = '';
  2445. document.getElementById('nat-modal-dport').value = '';
  2446. document.getElementById('nat-modal-comment').value = '';
  2447. document.getElementById('nat-modal-disabled').checked = false;
  2448. populateInterfaceSelect('nat-modal-iniface');
  2449. populateInterfaceSelect('nat-modal-outiface');
  2450. populateAddressListSelect('nat-modal-srclist');
  2451. populateAddressListSelect('nat-modal-dstlist');
  2452. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2453. if (srcInvEl) srcInvEl.checked = false;
  2454. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2455. if (dstInvEl) dstInvEl.checked = false;
  2456. populateGeoIPSelect('nat-modal-srcgeoip');
  2457. populateGeoIPSelect('nat-modal-dstgeoip');
  2458. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2459. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2460. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2461. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2462. toggleNATActionFields();
  2463. document.getElementById('nat-modal').classList.remove('hidden');
  2464. }
  2465. function openEditNATModal(id) {
  2466. const r = (state.natRules || []).find(rule => rule.id === id);
  2467. if (!r) return;
  2468. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2469. document.getElementById('nat-modal-id').value = r.id;
  2470. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2471. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2472. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2473. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2474. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2475. document.getElementById('nat-modal-src').value = r.src_address || '';
  2476. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2477. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2478. document.getElementById('nat-modal-comment').value = r.comment || '';
  2479. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2480. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2481. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2482. const srcInv = (r.src_address_list || '').startsWith('!');
  2483. const dstInv = (r.dst_address_list || '').startsWith('!');
  2484. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2485. if (srcInvEl) srcInvEl.checked = srcInv;
  2486. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2487. if (dstInvEl) dstInvEl.checked = dstInv;
  2488. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2489. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2490. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2491. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2492. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2493. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2494. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2495. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2496. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2497. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2498. toggleNATActionFields();
  2499. document.getElementById('nat-modal').classList.remove('hidden');
  2500. }
  2501. function closeNATModal() {
  2502. document.getElementById('nat-modal').classList.add('hidden');
  2503. }
  2504. function toggleNATChainFields() {
  2505. const ch = document.getElementById('nat-modal-chain').value;
  2506. const actSel = document.getElementById('nat-modal-action');
  2507. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2508. actSel.value = 'masquerade';
  2509. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2510. actSel.value = 'dst-nat';
  2511. }
  2512. toggleNATActionFields();
  2513. }
  2514. function toggleNATActionFields() {
  2515. const act = document.getElementById('nat-modal-action').value;
  2516. const toBox = document.getElementById('nat-action-to-box');
  2517. if (toBox) {
  2518. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2519. else toBox.classList.remove('hidden');
  2520. }
  2521. }
  2522. async function submitSaveNATRule(e) {
  2523. e.preventDefault();
  2524. const id = document.getElementById('nat-modal-id').value;
  2525. const chain = document.getElementById('nat-modal-chain').value;
  2526. const action = document.getElementById('nat-modal-action').value;
  2527. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2528. const toport = document.getElementById('nat-modal-toport').value.trim();
  2529. const proto = document.getElementById('nat-modal-proto').value;
  2530. const src = document.getElementById('nat-modal-src').value.trim();
  2531. const dst = document.getElementById('nat-modal-dst').value.trim();
  2532. const dport = document.getElementById('nat-modal-dport').value.trim();
  2533. const inIface = document.getElementById('nat-modal-iniface').value;
  2534. const outIface = document.getElementById('nat-modal-outiface').value;
  2535. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2536. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2537. srclist = '!' + srclist.replace(/^!/, '');
  2538. }
  2539. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2540. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2541. dstlist = '!' + dstlist.replace(/^!/, '');
  2542. }
  2543. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2544. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2545. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2546. }
  2547. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2548. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2549. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2550. }
  2551. const comment = document.getElementById('nat-modal-comment').value.trim();
  2552. const disabled = document.getElementById('nat-modal-disabled').checked;
  2553. try {
  2554. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2555. method: 'POST',
  2556. headers: { 'Content-Type': 'application/json' },
  2557. body: JSON.stringify({
  2558. id,
  2559. chain,
  2560. action,
  2561. to_addresses: toaddr,
  2562. to_ports: toport,
  2563. protocol: proto,
  2564. src_address: src,
  2565. dst_address: dst,
  2566. dst_port: dport,
  2567. in_interface: inIface,
  2568. out_interface: outIface,
  2569. src_address_list: srclist,
  2570. dst_address_list: dstlist,
  2571. src_geoip: srcgeoip,
  2572. dst_geoip: dstgeoip,
  2573. comment,
  2574. disabled
  2575. })
  2576. });
  2577. if (res.ok) {
  2578. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2579. closeNATModal();
  2580. loadFirewall(false);
  2581. }
  2582. } catch (err) {
  2583. showToast('Error', err.message, 'error');
  2584. }
  2585. }
  2586. async function moveNATRule(id, dir) {
  2587. try {
  2588. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2589. method: 'POST',
  2590. headers: { 'Content-Type': 'application/json' },
  2591. body: JSON.stringify({ direction: dir })
  2592. });
  2593. if (res.ok) loadFirewall(false);
  2594. } catch (err) {
  2595. showToast('Error', err.message, 'error');
  2596. }
  2597. }
  2598. async function toggleNATRuleState(id, disabled) {
  2599. try {
  2600. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2601. method: 'POST',
  2602. headers: { 'Content-Type': 'application/json' },
  2603. body: JSON.stringify({ disabled })
  2604. });
  2605. if (res.ok) loadFirewall(false);
  2606. } catch (err) {
  2607. showToast('Error', err.message, 'error');
  2608. }
  2609. }
  2610. async function deleteNATRule(id) {
  2611. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2612. try {
  2613. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2614. if (res.ok) {
  2615. showToast('Deleted', 'NAT rule removed', 'success');
  2616. loadFirewall(false);
  2617. }
  2618. } catch (err) {
  2619. showToast('Error', err.message, 'error');
  2620. }
  2621. }
  2622. // ----------------- Mangle Rules -----------------
  2623. function renderMangleRules() {
  2624. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2625. const tbody = document.getElementById('mangle-table-body');
  2626. const empty = document.getElementById('mangle-empty');
  2627. if (!tbody) return;
  2628. tbody.innerHTML = '';
  2629. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2630. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2631. if (rules.length === 0) {
  2632. empty?.classList.remove('hidden');
  2633. return;
  2634. }
  2635. empty?.classList.add('hidden');
  2636. rules.forEach((r, idx) => {
  2637. const tr = document.createElement('tr');
  2638. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2639. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2640. tr.innerHTML = `
  2641. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2642. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2643. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2644. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2645. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2646. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2647. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2648. <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>
  2649. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2650. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2651. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2652. </td>
  2653. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2654. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2655. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2656. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2657. <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>
  2658. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2659. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2660. </td>
  2661. `;
  2662. tbody.appendChild(tr);
  2663. });
  2664. }
  2665. function openAddMangleModal() {
  2666. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2667. document.getElementById('mangle-modal-id').value = '';
  2668. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2669. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2670. document.getElementById('mangle-modal-newmark').value = '';
  2671. document.getElementById('mangle-modal-passthrough').checked = true;
  2672. document.getElementById('mangle-modal-src').value = '';
  2673. document.getElementById('mangle-modal-dst').value = '';
  2674. document.getElementById('mangle-modal-connmark').value = '';
  2675. document.getElementById('mangle-modal-comment').value = '';
  2676. document.getElementById('mangle-modal-disabled').checked = false;
  2677. populateInterfaceSelect('mangle-modal-iniface');
  2678. populateAddressListSelect('mangle-modal-srclist');
  2679. populateAddressListSelect('mangle-modal-dstlist');
  2680. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2681. if (srcInvEl) srcInvEl.checked = false;
  2682. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2683. if (dstInvEl) dstInvEl.checked = false;
  2684. populateGeoIPSelect('mangle-modal-srcgeoip');
  2685. populateGeoIPSelect('mangle-modal-dstgeoip');
  2686. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2687. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2688. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2689. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2690. document.getElementById('mangle-modal').classList.remove('hidden');
  2691. }
  2692. function openEditMangleModal(id) {
  2693. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2694. if (!r) return;
  2695. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2696. document.getElementById('mangle-modal-id').value = r.id;
  2697. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2698. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2699. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2700. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2701. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2702. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2703. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2704. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2705. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2706. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2707. const srcInv = (r.src_address_list || '').startsWith('!');
  2708. const dstInv = (r.dst_address_list || '').startsWith('!');
  2709. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2710. if (srcInvEl) srcInvEl.checked = srcInv;
  2711. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2712. if (dstInvEl) dstInvEl.checked = dstInv;
  2713. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2714. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2715. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2716. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2717. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2718. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2719. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2720. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2721. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2722. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2723. document.getElementById('mangle-modal').classList.remove('hidden');
  2724. }
  2725. function closeMangleModal() {
  2726. document.getElementById('mangle-modal').classList.add('hidden');
  2727. }
  2728. function toggleMangleActionFields() {
  2729. // Handled smoothly by single dynamic input
  2730. }
  2731. async function submitSaveMangleRule(e) {
  2732. e.preventDefault();
  2733. const id = document.getElementById('mangle-modal-id').value;
  2734. const chain = document.getElementById('mangle-modal-chain').value;
  2735. const action = document.getElementById('mangle-modal-action').value;
  2736. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2737. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2738. const src = document.getElementById('mangle-modal-src').value.trim();
  2739. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2740. const inIface = document.getElementById('mangle-modal-iniface').value;
  2741. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2742. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2743. srclist = '!' + srclist.replace(/^!/, '');
  2744. }
  2745. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2746. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2747. dstlist = '!' + dstlist.replace(/^!/, '');
  2748. }
  2749. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2750. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2751. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2752. }
  2753. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2754. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2755. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2756. }
  2757. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2758. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2759. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2760. const payload = {
  2761. id,
  2762. chain,
  2763. action,
  2764. passthrough,
  2765. src_address: src,
  2766. dst_address: dst,
  2767. in_interface: inIface,
  2768. src_address_list: srclist,
  2769. dst_address_list: dstlist,
  2770. src_geoip: srcgeoip,
  2771. dst_geoip: dstgeoip,
  2772. connection_mark: connmark,
  2773. comment,
  2774. disabled
  2775. };
  2776. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2777. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2778. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2779. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2780. try {
  2781. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2782. method: 'POST',
  2783. headers: { 'Content-Type': 'application/json' },
  2784. body: JSON.stringify(payload)
  2785. });
  2786. if (res.ok) {
  2787. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2788. closeMangleModal();
  2789. loadFirewall(false);
  2790. }
  2791. } catch (err) {
  2792. showToast('Error', err.message, 'error');
  2793. }
  2794. }
  2795. async function moveMangleRule(id, dir) {
  2796. try {
  2797. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2798. method: 'POST',
  2799. headers: { 'Content-Type': 'application/json' },
  2800. body: JSON.stringify({ direction: dir })
  2801. });
  2802. if (res.ok) loadFirewall(false);
  2803. } catch (err) {
  2804. showToast('Error', err.message, 'error');
  2805. }
  2806. }
  2807. async function toggleMangleRuleState(id, disabled) {
  2808. try {
  2809. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2810. method: 'POST',
  2811. headers: { 'Content-Type': 'application/json' },
  2812. body: JSON.stringify({ disabled })
  2813. });
  2814. if (res.ok) loadFirewall(false);
  2815. } catch (err) {
  2816. showToast('Error', err.message, 'error');
  2817. }
  2818. }
  2819. async function deleteMangleRule(id) {
  2820. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2821. try {
  2822. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2823. if (res.ok) {
  2824. showToast('Deleted', 'Mangle rule removed', 'success');
  2825. loadFirewall(false);
  2826. }
  2827. } catch (err) {
  2828. showToast('Error', err.message, 'error');
  2829. }
  2830. }
  2831. // ----------------- Address Lists -----------------
  2832. function renderAddressLists() {
  2833. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2834. const tbody = document.getElementById('addrlist-table-body');
  2835. const empty = document.getElementById('addrlist-empty');
  2836. if (!tbody) return;
  2837. tbody.innerHTML = '';
  2838. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2839. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2840. // Update filter select
  2841. const sel = document.getElementById('addrlist-filter-name');
  2842. if (sel) {
  2843. const cur = sel.value;
  2844. sel.innerHTML = '<option value="">All Lists</option>';
  2845. const set = new Set((state.addressLists || []).map(a => a.name));
  2846. set.forEach(n => {
  2847. const opt = document.createElement('option');
  2848. opt.value = n;
  2849. opt.innerText = n;
  2850. if (n === cur) opt.selected = true;
  2851. sel.appendChild(opt);
  2852. });
  2853. }
  2854. if (entries.length === 0) {
  2855. empty?.classList.remove('hidden');
  2856. return;
  2857. }
  2858. empty?.classList.add('hidden');
  2859. entries.forEach((e, idx) => {
  2860. const tr = document.createElement('tr');
  2861. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2862. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2863. tr.innerHTML = `
  2864. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2865. <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>
  2866. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2867. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2868. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2869. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2870. <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>
  2871. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2872. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2873. </td>
  2874. `;
  2875. tbody.appendChild(tr);
  2876. });
  2877. }
  2878. function openAddAddrListModal() {
  2879. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2880. document.getElementById('addrlist-modal-id').value = '';
  2881. document.getElementById('addrlist-modal-name').value = '';
  2882. document.getElementById('addrlist-modal-addr').value = '';
  2883. document.getElementById('addrlist-modal-comment').value = '';
  2884. document.getElementById('addrlist-modal-disabled').checked = false;
  2885. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2886. if (submitBtn) submitBtn.innerText = 'Add to List';
  2887. document.getElementById('addrlist-modal').classList.remove('hidden');
  2888. }
  2889. function openEditAddrListModal(id) {
  2890. const e = (state.addressLists || []).find(item => item.id === id);
  2891. if (!e) return;
  2892. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2893. document.getElementById('addrlist-modal-id').value = e.id;
  2894. document.getElementById('addrlist-modal-name').value = e.name;
  2895. document.getElementById('addrlist-modal-addr').value = e.address;
  2896. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2897. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2898. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2899. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2900. document.getElementById('addrlist-modal').classList.remove('hidden');
  2901. }
  2902. function closeAddrListModal() {
  2903. document.getElementById('addrlist-modal').classList.add('hidden');
  2904. }
  2905. async function submitSaveAddrList(e) {
  2906. e.preventDefault();
  2907. const id = document.getElementById('addrlist-modal-id').value;
  2908. const name = document.getElementById('addrlist-modal-name').value.trim();
  2909. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2910. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2911. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2912. try {
  2913. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2914. method: 'POST',
  2915. headers: { 'Content-Type': 'application/json' },
  2916. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2917. });
  2918. if (res.ok) {
  2919. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2920. closeAddrListModal();
  2921. loadFirewall(false);
  2922. } else {
  2923. const err = await res.json();
  2924. showToast('Error', err.message || 'Failed to save address list', 'error');
  2925. }
  2926. } catch (err) {
  2927. showToast('Error', err.message, 'error');
  2928. }
  2929. }
  2930. async function toggleAddrListState(id, disabled) {
  2931. try {
  2932. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2933. method: 'POST',
  2934. headers: { 'Content-Type': 'application/json' },
  2935. body: JSON.stringify({ disabled })
  2936. });
  2937. if (res.ok) {
  2938. loadFirewall(false);
  2939. }
  2940. } catch (err) {
  2941. showToast('Error', err.message, 'error');
  2942. }
  2943. }
  2944. async function deleteAddrList(id) {
  2945. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2946. try {
  2947. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2948. if (res.ok) {
  2949. showToast('Deleted', 'Address list item removed', 'info');
  2950. loadFirewall(false);
  2951. }
  2952. } catch (err) {
  2953. showToast('Error', err.message, 'error');
  2954. }
  2955. }
  2956. // ----------------- Geo-Location IP Management -----------------
  2957. async function loadGeoIP() {
  2958. try {
  2959. const [statusRes, countriesRes] = await Promise.all([
  2960. fetch(`${API_BASE}/firewall/geoip/status`),
  2961. fetch(`${API_BASE}/firewall/geoip/countries`)
  2962. ]);
  2963. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2964. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2965. updateGeoHeader();
  2966. renderGeoCountries();
  2967. } catch (err) {
  2968. console.error('Failed to load GeoIP:', err);
  2969. }
  2970. }
  2971. function getGeoUsageMap() {
  2972. const usage = {};
  2973. const checkRule = (r, type) => {
  2974. ['src_geoip', 'dst_geoip'].forEach(field => {
  2975. let val = (r && r[field]) || '';
  2976. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  2977. if (code) {
  2978. if (!usage[code]) usage[code] = [];
  2979. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  2980. if (!usage[code].includes(label)) usage[code].push(label);
  2981. }
  2982. });
  2983. };
  2984. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  2985. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  2986. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  2987. return usage;
  2988. }
  2989. function updateGeoHeader() {
  2990. const s = state.geoStatus || {};
  2991. const statusBadge = document.getElementById('geo-status-badge');
  2992. if (statusBadge) {
  2993. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2994. statusBadge.className = s.auto_update
  2995. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2996. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2997. }
  2998. const intervalLabel = document.getElementById('geo-interval-label');
  2999. if (intervalLabel) {
  3000. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3001. }
  3002. const usageMap = getGeoUsageMap();
  3003. const inUseCount = Object.keys(usageMap).length;
  3004. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3005. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3006. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3007. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3008. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3009. if (lastSyncEl) {
  3010. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3011. const d = new Date(s.last_updated);
  3012. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3013. } else {
  3014. lastSyncEl.innerText = 'Never (Sync Pending)';
  3015. }
  3016. }
  3017. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3018. if (nextSyncEl) {
  3019. if (s.next_update && !s.next_update.startsWith('0001')) {
  3020. const d = new Date(s.next_update);
  3021. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3022. } else {
  3023. nextSyncEl.innerText = '-';
  3024. }
  3025. }
  3026. const badge = document.getElementById('fw-badge-geo');
  3027. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3028. }
  3029. function renderGeoCountries() {
  3030. const tbody = document.getElementById('geo-table-body');
  3031. const empty = document.getElementById('geo-empty');
  3032. if (!tbody) return;
  3033. tbody.innerHTML = '';
  3034. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3035. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3036. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3037. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3038. const usageMap = getGeoUsageMap();
  3039. const countries = (state.geoCountries || []).filter(c => {
  3040. const isUsed = !!usageMap[c.code];
  3041. if (inUseOnly && !isUsed) return false;
  3042. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3043. if (continent && c.continent !== continent) return false;
  3044. if (q) {
  3045. const matchCode = c.code.toLowerCase().includes(q);
  3046. const matchName = c.name.toLowerCase().includes(q);
  3047. if (!matchCode && !matchName) return false;
  3048. }
  3049. return true;
  3050. });
  3051. if (countries.length === 0) {
  3052. empty?.classList.remove('hidden');
  3053. return;
  3054. }
  3055. empty?.classList.add('hidden');
  3056. countries.forEach(c => {
  3057. const tr = document.createElement('tr');
  3058. const isUsed = !!usageMap[c.code];
  3059. const rulesUsing = usageMap[c.code] || [];
  3060. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3061. let statusHtml = '';
  3062. if (isUsed) {
  3063. 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>`;
  3064. } else if (c.subnet_count > 0) {
  3065. 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>';
  3066. } else {
  3067. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3068. }
  3069. tr.innerHTML = `
  3070. <td class="py-2.5 px-3 text-center">
  3071. <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'}">
  3072. ${c.code}
  3073. </span>
  3074. </td>
  3075. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3076. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3077. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3078. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3079. </td>
  3080. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3081. <td class="py-2.5 px-3">
  3082. ${statusHtml}
  3083. </td>
  3084. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3085. <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>
  3086. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3087. </td>
  3088. `;
  3089. tbody.appendChild(tr);
  3090. });
  3091. }
  3092. function quickFilterGeo(preset) {
  3093. const searchInput = document.getElementById('geo-search-input');
  3094. const continentSel = document.getElementById('geo-continent-filter');
  3095. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3096. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3097. if (searchInput) searchInput.value = '';
  3098. if (continentSel) continentSel.value = '';
  3099. if (inUseCheck) inUseCheck.checked = false;
  3100. if (cachedCheck) cachedCheck.checked = false;
  3101. if (preset === 'GR') {
  3102. if (searchInput) searchInput.value = 'Greece';
  3103. } else if (preset === 'Europe') {
  3104. if (continentSel) continentSel.value = 'Europe';
  3105. } else if (preset === 'HIGHRISK') {
  3106. if (searchInput) searchInput.value = 'China';
  3107. }
  3108. renderGeoCountries();
  3109. }
  3110. async function toggleGeoCountry(code, enabled) {
  3111. try {
  3112. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3113. method: 'POST',
  3114. headers: { 'Content-Type': 'application/json' },
  3115. body: JSON.stringify({ enabled })
  3116. });
  3117. if (res.ok) {
  3118. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3119. loadGeoIP();
  3120. } else {
  3121. const err = await res.json();
  3122. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3123. }
  3124. } catch (err) {
  3125. showToast('Error', err.message, 'error');
  3126. }
  3127. }
  3128. async function updateGeoCountry(code) {
  3129. try {
  3130. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3131. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3132. if (res.ok) {
  3133. const data = await res.json();
  3134. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3135. loadGeoIP();
  3136. } else {
  3137. const err = await res.json();
  3138. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3139. }
  3140. } catch (err) {
  3141. showToast('Error', err.message, 'error');
  3142. }
  3143. }
  3144. async function triggerGeoUpdateNow() {
  3145. const spinner = document.getElementById('geo-update-spinner');
  3146. if (spinner) spinner.classList.remove('hidden');
  3147. try {
  3148. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3149. if (res.ok) {
  3150. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3151. setTimeout(() => {
  3152. loadGeoIP();
  3153. if (spinner) spinner.classList.add('hidden');
  3154. }, 2500);
  3155. } else {
  3156. const err = await res.json();
  3157. showToast('Notice', err.message || 'Update in progress', 'info');
  3158. if (spinner) spinner.classList.add('hidden');
  3159. }
  3160. } catch (err) {
  3161. showToast('Error', err.message, 'error');
  3162. if (spinner) spinner.classList.add('hidden');
  3163. }
  3164. }
  3165. async function applyGeoPreset(preset) {
  3166. try {
  3167. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3168. method: 'POST',
  3169. headers: { 'Content-Type': 'application/json' },
  3170. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3171. });
  3172. if (res.ok) {
  3173. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3174. loadGeoIP();
  3175. }
  3176. } catch (err) {
  3177. showToast('Error', err.message, 'error');
  3178. }
  3179. }
  3180. function openGeoIntervalModal() {
  3181. const s = state.geoStatus || {};
  3182. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3183. const sel = document.getElementById('geo-cfg-interval');
  3184. const customBox = document.getElementById('geo-cfg-custom-box');
  3185. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3186. const curHours = s.interval_hours || 24;
  3187. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3188. if (matchOption) {
  3189. sel.value = String(curHours);
  3190. customBox.classList.add('hidden');
  3191. } else {
  3192. sel.value = 'custom';
  3193. customHoursInput.value = curHours;
  3194. customBox.classList.remove('hidden');
  3195. }
  3196. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3197. }
  3198. function closeGeoIntervalModal() {
  3199. document.getElementById('geo-interval-modal').classList.add('hidden');
  3200. }
  3201. function toggleCustomGeoInterval() {
  3202. const val = document.getElementById('geo-cfg-interval').value;
  3203. const customBox = document.getElementById('geo-cfg-custom-box');
  3204. if (val === 'custom') {
  3205. customBox.classList.remove('hidden');
  3206. } else {
  3207. customBox.classList.add('hidden');
  3208. }
  3209. }
  3210. async function submitGeoIntervalSettings(e) {
  3211. e.preventDefault();
  3212. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3213. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3214. let hours = 24;
  3215. if (intervalVal === 'custom') {
  3216. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3217. } else {
  3218. hours = parseInt(intervalVal, 10) || 24;
  3219. }
  3220. try {
  3221. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3222. method: 'POST',
  3223. headers: { 'Content-Type': 'application/json' },
  3224. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3225. });
  3226. if (res.ok) {
  3227. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3228. closeGeoIntervalModal();
  3229. loadGeoIP();
  3230. } else {
  3231. const err = await res.json();
  3232. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3233. }
  3234. } catch (err) {
  3235. showToast('Error', err.message, 'error');
  3236. }
  3237. }
  3238. async function viewGeoSubnets(code, name) {
  3239. if (!name) {
  3240. const found = (state.geoCountries || []).find(x => x.code === code);
  3241. name = found ? found.name : code;
  3242. }
  3243. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3244. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3245. const listEl = document.getElementById('geo-subnets-list');
  3246. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3247. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3248. try {
  3249. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3250. if (res.ok) {
  3251. const data = await res.json();
  3252. const subnets = data.subnets || [];
  3253. if (subnets.length === 0) {
  3254. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3255. } else {
  3256. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3257. }
  3258. } else {
  3259. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3260. }
  3261. } catch (err) {
  3262. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3263. }
  3264. }
  3265. function closeGeoSubnetsModal() {
  3266. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3267. }
  3268. // ----------------- Active Connections Tracking -----------------
  3269. async function loadConnections() {
  3270. try {
  3271. const res = await fetch(`${API_BASE}/firewall/connections`);
  3272. const data = await res.json();
  3273. state.connections = Array.isArray(data) ? data : [];
  3274. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3275. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3276. renderConnections();
  3277. } catch (err) {
  3278. console.error('Failed to load connections:', err);
  3279. }
  3280. }
  3281. function renderConnections() {
  3282. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3283. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3284. const tbody = document.getElementById('conns-table-body');
  3285. const empty = document.getElementById('conns-empty');
  3286. if (!tbody) return;
  3287. tbody.innerHTML = '';
  3288. const conns = (state.connections || []).filter(c => {
  3289. if (protoFilter && c.protocol !== protoFilter) return false;
  3290. if (search) {
  3291. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3292. if (!line.includes(search)) return false;
  3293. }
  3294. return true;
  3295. });
  3296. if (conns.length === 0) {
  3297. empty?.classList.remove('hidden');
  3298. return;
  3299. }
  3300. empty?.classList.add('hidden');
  3301. conns.slice(0, 150).forEach(c => {
  3302. const tr = document.createElement('tr');
  3303. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3304. let stateColor = 'text-slate-400';
  3305. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3306. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3307. tr.innerHTML = `
  3308. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3309. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3310. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3311. <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>
  3312. <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>
  3313. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3314. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3315. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3316. <td class="py-2.5 px-3 text-right font-sans">
  3317. <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>
  3318. </td>
  3319. `;
  3320. tbody.appendChild(tr);
  3321. });
  3322. }
  3323. async function killConnection(protocol, src, sport, dst, dport) {
  3324. try {
  3325. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3326. method: 'POST',
  3327. headers: { 'Content-Type': 'application/json' },
  3328. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3329. });
  3330. if (res.ok) {
  3331. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3332. loadConnections();
  3333. }
  3334. } catch (err) {
  3335. showToast('Error', err.message, 'error');
  3336. }
  3337. }
  3338. async function resetFirewallCounters() {
  3339. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3340. try {
  3341. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3342. if (res.ok) {
  3343. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3344. loadFirewall(false);
  3345. }
  3346. } catch (err) {
  3347. showToast('Error', err.message, 'error');
  3348. }
  3349. }
  3350. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3351. function switchRoutesSubTab(tab) {
  3352. state.routesSubTab = tab;
  3353. const tabs = ['routes', 'rules', 'tables'];
  3354. tabs.forEach(t => {
  3355. const panel = document.getElementById(`routes-subtab-${t}`);
  3356. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3357. if (panel) {
  3358. if (t === tab) panel.classList.remove('hidden');
  3359. else panel.classList.add('hidden');
  3360. }
  3361. if (btn) {
  3362. if (t === tab) {
  3363. 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';
  3364. } else {
  3365. 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';
  3366. }
  3367. }
  3368. });
  3369. }
  3370. async function loadRoutes() {
  3371. try {
  3372. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3373. fetch(`${API_BASE}/routes`),
  3374. fetch(`${API_BASE}/routing/rules`),
  3375. fetch(`${API_BASE}/routing/tables`)
  3376. ]);
  3377. if (routesRes.ok) state.routes = await routesRes.json();
  3378. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3379. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3380. const bRoutes = document.getElementById('routes-badge-routes');
  3381. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3382. const bRules = document.getElementById('routes-badge-rules');
  3383. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3384. const bTables = document.getElementById('routes-badge-tables');
  3385. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3386. const bRoutesCount = document.getElementById('badge-routes-count');
  3387. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3388. renderRoutesList();
  3389. renderPolicyRules();
  3390. renderRoutingTables();
  3391. } catch (err) {
  3392. console.error('Failed to load routing:', err);
  3393. }
  3394. }
  3395. function renderRoutesList() {
  3396. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3397. const tbody = document.getElementById('routes-table-body');
  3398. const empty = document.getElementById('routes-empty');
  3399. if (!tbody) return;
  3400. tbody.innerHTML = '';
  3401. // Update table filter select
  3402. const sel = document.getElementById('routes-filter-table');
  3403. if (sel) {
  3404. const cur = sel.value;
  3405. sel.innerHTML = '<option value="">All Tables</option>';
  3406. (state.routingTables || []).forEach(t => {
  3407. const opt = document.createElement('option');
  3408. opt.value = t.name;
  3409. opt.innerText = t.name;
  3410. if (t.name === cur) opt.selected = true;
  3411. sel.appendChild(opt);
  3412. });
  3413. }
  3414. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3415. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3416. if (routes.length === 0) {
  3417. empty?.classList.remove('hidden');
  3418. return;
  3419. }
  3420. empty?.classList.add('hidden');
  3421. routes.forEach(r => {
  3422. const tr = document.createElement('tr');
  3423. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3424. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3425. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3426. let flags = '';
  3427. if (r.dynamic) flags += 'D';
  3428. if (r.active) flags += 'A';
  3429. if (r.connect) flags += 'C';
  3430. if (r.static) flags += 'S';
  3431. if (r.disabled) flags += 'X';
  3432. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3433. tr.innerHTML = `
  3434. <td class="py-2.5 px-3 text-center">
  3435. <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'}">
  3436. ${flags || '-'}
  3437. </span>
  3438. </td>
  3439. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3440. <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>
  3441. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3442. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3443. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3444. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3445. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3446. ${r.static ? `
  3447. <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>
  3448. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3449. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3450. ` : `
  3451. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3452. `}
  3453. </td>
  3454. `;
  3455. tbody.appendChild(tr);
  3456. });
  3457. }
  3458. function openAddRouteModal() {
  3459. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3460. document.getElementById('route-modal-id').value = '';
  3461. document.getElementById('route-modal-old-dst').value = '';
  3462. document.getElementById('route-modal-old-gw').value = '';
  3463. document.getElementById('route-modal-old-distance').value = '';
  3464. document.getElementById('route-modal-old-table').value = '';
  3465. document.getElementById('route-modal-old-iface').value = '';
  3466. const dstInput = document.getElementById('route-modal-dst');
  3467. const gwInput = document.getElementById('route-modal-gw');
  3468. const distInput = document.getElementById('route-modal-distance');
  3469. const ifaceSelect = document.getElementById('route-modal-iface');
  3470. const tableSelect = document.getElementById('route-modal-table');
  3471. const commentInput = document.getElementById('route-modal-comment');
  3472. const disCheck = document.getElementById('route-modal-disabled');
  3473. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3474. dstInput.disabled = false;
  3475. dstInput.value = '0.0.0.0/0';
  3476. gwInput.disabled = false;
  3477. gwInput.value = '';
  3478. distInput.disabled = false;
  3479. distInput.value = '1';
  3480. ifaceSelect.disabled = false;
  3481. tableSelect.disabled = false;
  3482. commentInput.disabled = false;
  3483. commentInput.value = '';
  3484. disCheck.disabled = false;
  3485. disCheck.checked = false;
  3486. if (saveBtn) saveBtn.classList.remove('hidden');
  3487. populateInterfaceSelect('route-modal-iface');
  3488. // Populate tables
  3489. tableSelect.innerHTML = '';
  3490. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3491. const opt = document.createElement('option');
  3492. opt.value = t.name;
  3493. opt.innerText = t.name;
  3494. if (t.name === 'main') opt.selected = true;
  3495. tableSelect.appendChild(opt);
  3496. });
  3497. document.getElementById('route-modal').classList.remove('hidden');
  3498. }
  3499. function openEditRouteModal(id) {
  3500. const r = (state.routes || []).find(route => route.id === id);
  3501. if (!r) return;
  3502. const isStatic = !!r.static;
  3503. document.getElementById('route-modal-title').innerText = isStatic
  3504. ? `Edit Route: ${r.dst_address}`
  3505. : `Route Properties (Read Only): ${r.dst_address}`;
  3506. document.getElementById('route-modal-id').value = r.id;
  3507. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3508. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3509. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3510. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3511. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3512. const dstInput = document.getElementById('route-modal-dst');
  3513. const gwInput = document.getElementById('route-modal-gw');
  3514. const distInput = document.getElementById('route-modal-distance');
  3515. const ifaceSelect = document.getElementById('route-modal-iface');
  3516. const tableSelect = document.getElementById('route-modal-table');
  3517. const commentInput = document.getElementById('route-modal-comment');
  3518. const disCheck = document.getElementById('route-modal-disabled');
  3519. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3520. dstInput.value = r.dst_address;
  3521. gwInput.value = r.gateway || '';
  3522. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3523. commentInput.value = r.comment || '';
  3524. disCheck.checked = !!r.disabled;
  3525. dstInput.disabled = !isStatic;
  3526. gwInput.disabled = !isStatic;
  3527. distInput.disabled = !isStatic;
  3528. ifaceSelect.disabled = !isStatic;
  3529. tableSelect.disabled = !isStatic;
  3530. commentInput.disabled = !isStatic;
  3531. disCheck.disabled = !isStatic;
  3532. if (saveBtn) {
  3533. if (isStatic) {
  3534. saveBtn.classList.remove('hidden');
  3535. } else {
  3536. saveBtn.classList.add('hidden');
  3537. }
  3538. }
  3539. populateInterfaceSelect('route-modal-iface', r.interface);
  3540. tableSelect.innerHTML = '';
  3541. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3542. const opt = document.createElement('option');
  3543. opt.value = t.name;
  3544. opt.innerText = t.name;
  3545. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3546. tableSelect.appendChild(opt);
  3547. });
  3548. document.getElementById('route-modal').classList.remove('hidden');
  3549. }
  3550. function closeRouteModal() {
  3551. document.getElementById('route-modal').classList.add('hidden');
  3552. }
  3553. async function submitSaveRoute(e) {
  3554. e.preventDefault();
  3555. const id = document.getElementById('route-modal-id').value;
  3556. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3557. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3558. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3559. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3560. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3561. const dst = document.getElementById('route-modal-dst').value.trim();
  3562. const gw = document.getElementById('route-modal-gw').value.trim();
  3563. const table = document.getElementById('route-modal-table').value;
  3564. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3565. const iface = document.getElementById('route-modal-iface').value;
  3566. const comment = document.getElementById('route-modal-comment').value.trim();
  3567. const disabled = document.getElementById('route-modal-disabled').checked;
  3568. if (!dst) {
  3569. showToast('Error', 'Destination address is required', 'error');
  3570. return;
  3571. }
  3572. if (!gw && !iface) {
  3573. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3574. return;
  3575. }
  3576. const payload = {
  3577. id,
  3578. old_dst_address: oldDst,
  3579. old_gateway: oldGw,
  3580. old_routing_table: oldTable,
  3581. old_interface: oldIface,
  3582. dst_address: dst,
  3583. gateway: gw || iface,
  3584. routing_table: table,
  3585. distance,
  3586. interface: iface,
  3587. comment,
  3588. disabled
  3589. };
  3590. if (oldDistStr !== undefined && oldDistStr !== '') {
  3591. payload.old_distance = parseInt(oldDistStr, 10);
  3592. }
  3593. try {
  3594. const res = await fetch(`${API_BASE}/routes`, {
  3595. method: 'POST',
  3596. headers: { 'Content-Type': 'application/json' },
  3597. body: JSON.stringify(payload)
  3598. });
  3599. if (res.ok) {
  3600. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3601. closeRouteModal();
  3602. loadRoutes();
  3603. } else {
  3604. const err = await res.json();
  3605. showToast('Error', err.message || 'Failed to save route', 'error');
  3606. }
  3607. } catch (err) {
  3608. showToast('Error', err.message, 'error');
  3609. }
  3610. }
  3611. async function toggleRouteState(id, disabled) {
  3612. try {
  3613. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3614. method: 'POST',
  3615. headers: { 'Content-Type': 'application/json' },
  3616. body: JSON.stringify({ disabled })
  3617. });
  3618. if (res.ok) loadRoutes();
  3619. } catch (err) {
  3620. showToast('Error', err.message, 'error');
  3621. }
  3622. }
  3623. async function deleteRoute(id) {
  3624. if (!confirm('Are you sure you want to delete this route?')) return;
  3625. try {
  3626. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3627. if (res.ok) {
  3628. showToast('Deleted', 'Route removed', 'success');
  3629. loadRoutes();
  3630. }
  3631. } catch (err) {
  3632. showToast('Error', err.message, 'error');
  3633. }
  3634. }
  3635. // ----------------- Policy Rules (/ip route rule) -----------------
  3636. function renderPolicyRules() {
  3637. const tbody = document.getElementById('rules-table-body');
  3638. const empty = document.getElementById('rules-empty');
  3639. if (!tbody) return;
  3640. tbody.innerHTML = '';
  3641. const rules = state.policyRules || [];
  3642. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3643. if (rules.length === 0) {
  3644. empty?.classList.remove('hidden');
  3645. return;
  3646. }
  3647. empty?.classList.add('hidden');
  3648. rules.forEach(pr => {
  3649. const tr = document.createElement('tr');
  3650. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3651. tr.innerHTML = `
  3652. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3653. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3654. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3655. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3656. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3657. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3658. <td class="py-2.5 px-3 text-right font-sans">
  3659. ${pr.priority < 32766 && pr.priority > 0 ? `
  3660. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3661. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3662. </td>
  3663. `;
  3664. tbody.appendChild(tr);
  3665. });
  3666. }
  3667. function openAddPolicyRuleModal() {
  3668. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3669. document.getElementById('prule-modal-mark').value = '';
  3670. document.getElementById('prule-modal-src').value = '';
  3671. document.getElementById('prule-modal-dst').value = '';
  3672. const sel = document.getElementById('prule-modal-table');
  3673. sel.innerHTML = '';
  3674. (state.routingTables || []).forEach(t => {
  3675. const opt = document.createElement('option');
  3676. opt.value = t.name;
  3677. opt.innerText = t.name;
  3678. sel.appendChild(opt);
  3679. });
  3680. document.getElementById('prule-modal').classList.remove('hidden');
  3681. }
  3682. function closePolicyRuleModal() {
  3683. document.getElementById('prule-modal').classList.add('hidden');
  3684. }
  3685. async function submitSavePolicyRule(e) {
  3686. e.preventDefault();
  3687. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3688. const mark = document.getElementById('prule-modal-mark').value.trim();
  3689. const src = document.getElementById('prule-modal-src').value.trim();
  3690. const dst = document.getElementById('prule-modal-dst').value.trim();
  3691. const table = document.getElementById('prule-modal-table').value;
  3692. const action = document.getElementById('prule-modal-action').value;
  3693. try {
  3694. const res = await fetch(`${API_BASE}/routing/rules`, {
  3695. method: 'POST',
  3696. headers: { 'Content-Type': 'application/json' },
  3697. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3698. });
  3699. if (res.ok) {
  3700. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3701. closePolicyRuleModal();
  3702. loadRoutes();
  3703. } else {
  3704. const err = await res.json();
  3705. showToast('Error', err.message, 'error');
  3706. }
  3707. } catch (err) {
  3708. showToast('Error', err.message, 'error');
  3709. }
  3710. }
  3711. async function deletePolicyRule(id) {
  3712. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3713. try {
  3714. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3715. if (res.ok) {
  3716. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3717. loadRoutes();
  3718. }
  3719. } catch (err) {
  3720. showToast('Error', err.message, 'error');
  3721. }
  3722. }
  3723. // ----------------- Routing Tables -----------------
  3724. function renderRoutingTables() {
  3725. const tbody = document.getElementById('tables-table-body');
  3726. if (!tbody) return;
  3727. tbody.innerHTML = '';
  3728. (state.routingTables || []).forEach(t => {
  3729. const tr = document.createElement('tr');
  3730. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3731. tr.innerHTML = `
  3732. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3733. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3734. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3735. `;
  3736. tbody.appendChild(tr);
  3737. });
  3738. }
  3739. function openAddTableModal() {
  3740. document.getElementById('table-modal-name').value = '';
  3741. document.getElementById('table-modal-id').value = '';
  3742. document.getElementById('table-modal-comment').value = '';
  3743. document.getElementById('table-modal').classList.remove('hidden');
  3744. }
  3745. function closeTableModal() {
  3746. document.getElementById('table-modal').classList.add('hidden');
  3747. }
  3748. async function submitSaveTable(e) {
  3749. e.preventDefault();
  3750. const name = document.getElementById('table-modal-name').value.trim();
  3751. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3752. const comment = document.getElementById('table-modal-comment').value.trim();
  3753. try {
  3754. const res = await fetch(`${API_BASE}/routing/tables`, {
  3755. method: 'POST',
  3756. headers: { 'Content-Type': 'application/json' },
  3757. body: JSON.stringify({ name, table_id: id, comment })
  3758. });
  3759. if (res.ok) {
  3760. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3761. closeTableModal();
  3762. loadRoutes();
  3763. } else {
  3764. const err = await res.json();
  3765. showToast('Error', err.message, 'error');
  3766. }
  3767. } catch (err) {
  3768. showToast('Error', err.message, 'error');
  3769. }
  3770. }
  3771. async function loadDebianConfig() {
  3772. const view = document.getElementById('debian-config-view');
  3773. view.innerText = 'Generating live configuration...';
  3774. try {
  3775. const res = await fetch(`${API_BASE}/debian/config`);
  3776. const data = await res.json();
  3777. view.innerText = data.content || '# Empty config';
  3778. } catch (err) {
  3779. view.innerText = 'Failed to generate Debian network config.';
  3780. }
  3781. }
  3782. async function saveDebianConfig() {
  3783. try {
  3784. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3785. const data = await res.json();
  3786. if (res.ok) {
  3787. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3788. loadDebianConfig();
  3789. }
  3790. } catch (err) {
  3791. showToast('Error', err.message, 'error');
  3792. }
  3793. }
  3794. function showToast(title, message, type = 'info') {
  3795. const container = document.getElementById('toast-container');
  3796. const toast = document.createElement('div');
  3797. const borderColors = {
  3798. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3799. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3800. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3801. };
  3802. 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}`;
  3803. toast.innerHTML = `
  3804. <div class="flex-1">
  3805. <div class="font-bold text-xs text-white">${title}</div>
  3806. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3807. </div>
  3808. `;
  3809. container.appendChild(toast);
  3810. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3811. setTimeout(() => {
  3812. toast.classList.add('opacity-0', 'translate-y-2');
  3813. setTimeout(() => toast.remove(), 300);
  3814. }, 4000);
  3815. }
  3816. function formatTraffic(bytesPerSec) {
  3817. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3818. const kb = bytesPerSec / 1024;
  3819. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3820. const mb = kb / 1024;
  3821. return `${mb.toFixed(2)} MB/s`;
  3822. }
  3823. function toggleSidebar() {
  3824. const sb = document.getElementById('sidebar');
  3825. sb.classList.toggle('-translate-x-full');
  3826. }
  3827. // ======================== EoIP (Ethernet over IP) ========================
  3828. async function loadEoIP(populate = true) {
  3829. try {
  3830. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3831. const data = await res.json();
  3832. state.eoipTunnels = Array.isArray(data) ? data : [];
  3833. const badge = document.getElementById('eoip-count-badge');
  3834. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3835. const sideBadge = document.getElementById('badge-eoip-count');
  3836. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3837. renderEoIPTunnels();
  3838. } catch (err) {
  3839. console.error('Failed to load EoIP:', err);
  3840. }
  3841. }
  3842. function renderEoIPTunnels() {
  3843. const tbody = document.getElementById('eoip-table-body');
  3844. const empty = document.getElementById('eoip-empty');
  3845. if (!tbody) return;
  3846. tbody.innerHTML = '';
  3847. const tunnels = state.eoipTunnels || [];
  3848. if (tunnels.length === 0) {
  3849. empty?.classList.remove('hidden');
  3850. return;
  3851. }
  3852. empty?.classList.add('hidden');
  3853. tunnels.forEach(t => {
  3854. const tr = document.createElement('tr');
  3855. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3856. tr.innerHTML = `
  3857. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3858. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3859. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3860. <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>
  3861. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3862. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3863. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3864. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3865. <td class="py-2.5 px-3 font-mono text-[11px]">
  3866. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3867. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3868. </td>
  3869. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3870. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3871. <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>
  3872. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3873. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3874. </td>
  3875. `;
  3876. tbody.appendChild(tr);
  3877. });
  3878. }
  3879. function openAddEoIPModal() {
  3880. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3881. document.getElementById('eoip-modal-id').value = '';
  3882. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3883. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3884. document.getElementById('eoip-modal-remote').value = '';
  3885. document.getElementById('eoip-modal-ip').value = '';
  3886. document.getElementById('eoip-modal-local').value = '';
  3887. document.getElementById('eoip-modal-mac').value = '';
  3888. document.getElementById('eoip-modal-mtu').value = '1500';
  3889. document.getElementById('eoip-modal-comment').value = '';
  3890. document.getElementById('eoip-modal-clampmss').checked = true;
  3891. document.getElementById('eoip-modal-disabled').checked = false;
  3892. document.getElementById('eoip-modal').classList.remove('hidden');
  3893. }
  3894. function openEditEoIPModal(id) {
  3895. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3896. if (!t) return;
  3897. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3898. document.getElementById('eoip-modal-id').value = t.id;
  3899. document.getElementById('eoip-modal-name').value = t.name;
  3900. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3901. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3902. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3903. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3904. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3905. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3906. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3907. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3908. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3909. document.getElementById('eoip-modal').classList.remove('hidden');
  3910. }
  3911. function closeEoIPModal() {
  3912. document.getElementById('eoip-modal').classList.add('hidden');
  3913. }
  3914. async function submitSaveEoIP(e) {
  3915. e.preventDefault();
  3916. const id = document.getElementById('eoip-modal-id').value;
  3917. const name = document.getElementById('eoip-modal-name').value.trim();
  3918. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3919. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3920. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3921. const local = document.getElementById('eoip-modal-local').value.trim();
  3922. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3923. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3924. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3925. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3926. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3927. try {
  3928. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3929. method: 'POST',
  3930. headers: { 'Content-Type': 'application/json' },
  3931. body: JSON.stringify({
  3932. id,
  3933. name,
  3934. tunnel_id: tunnelId,
  3935. remote_address: remote,
  3936. ip_address: ipAddress,
  3937. local_address: local,
  3938. mac_address: mac,
  3939. mtu,
  3940. clamp_mss: clampMss,
  3941. comment,
  3942. disabled
  3943. })
  3944. });
  3945. if (res.ok) {
  3946. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3947. closeEoIPModal();
  3948. loadEoIP(false);
  3949. fetchData(false);
  3950. } else {
  3951. const err = await res.json();
  3952. showToast('Error', err.message, 'error');
  3953. }
  3954. } catch (err) {
  3955. showToast('Error', err.message, 'error');
  3956. }
  3957. }
  3958. async function toggleEoIPState(id, disabled) {
  3959. try {
  3960. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3961. method: 'POST',
  3962. headers: { 'Content-Type': 'application/json' },
  3963. body: JSON.stringify({ disabled })
  3964. });
  3965. if (res.ok) {
  3966. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3967. loadEoIP(false);
  3968. fetchData(false);
  3969. }
  3970. } catch (err) {
  3971. showToast('Error', err.message, 'error');
  3972. }
  3973. }
  3974. async function deleteEoIP(id) {
  3975. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3976. try {
  3977. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3978. if (res.ok) {
  3979. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3980. loadEoIP(false);
  3981. fetchData(false);
  3982. }
  3983. } catch (err) {
  3984. showToast('Error', err.message, 'error');
  3985. }
  3986. }
  3987. // ======================== PPP Central Hub & Servers ========================
  3988. function switchPPPSubTab(tab) {
  3989. state.pppSubTab = tab;
  3990. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3991. tabs.forEach(t => {
  3992. const panel = document.getElementById(`ppp-subtab-${t}`);
  3993. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3994. if (panel) {
  3995. if (t === tab) panel.classList.remove('hidden');
  3996. else panel.classList.add('hidden');
  3997. }
  3998. if (btn) {
  3999. if (t === tab) {
  4000. 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';
  4001. } else {
  4002. 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';
  4003. }
  4004. }
  4005. });
  4006. const addBtn = document.getElementById('ppp-primary-add-btn');
  4007. if (addBtn) {
  4008. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4009. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4010. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4011. else addBtn.innerHTML = '<span>Save Config</span>';
  4012. }
  4013. if (tab === 'active') loadPPPSessions();
  4014. }
  4015. function openCurrentPPPModal() {
  4016. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4017. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4018. else if (state.pppSubTab === 'active') loadPPPSessions();
  4019. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4020. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4021. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4022. }
  4023. async function loadPPP(populateDropdowns = true) {
  4024. await Promise.all([
  4025. loadPPPSecrets(),
  4026. loadPPPProfiles(),
  4027. loadPPPServers(),
  4028. loadPPPSessions()
  4029. ]);
  4030. }
  4031. async function loadPPPSecrets() {
  4032. try {
  4033. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4034. const data = await res.json();
  4035. state.pppSecrets = Array.isArray(data) ? data : [];
  4036. const b = document.getElementById('ppp-badge-secrets');
  4037. if (b) b.innerText = state.pppSecrets.length;
  4038. const b2 = document.getElementById('secrets-count-badge');
  4039. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4040. renderPPPSecrets();
  4041. } catch (err) {
  4042. console.error('Failed to load PPP secrets:', err);
  4043. }
  4044. }
  4045. function renderPPPSecrets() {
  4046. const tbody = document.getElementById('secrets-table-body');
  4047. const empty = document.getElementById('secrets-empty');
  4048. if (!tbody) return;
  4049. tbody.innerHTML = '';
  4050. const secrets = state.pppSecrets || [];
  4051. if (secrets.length === 0) {
  4052. empty?.classList.remove('hidden');
  4053. return;
  4054. }
  4055. empty?.classList.add('hidden');
  4056. secrets.forEach(s => {
  4057. const tr = document.createElement('tr');
  4058. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4059. tr.innerHTML = `
  4060. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4061. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4062. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4063. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4064. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4065. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4066. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4067. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4068. <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>
  4069. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4070. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4071. </td>
  4072. `;
  4073. tbody.appendChild(tr);
  4074. });
  4075. }
  4076. async function loadPPPProfiles() {
  4077. try {
  4078. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4079. const data = await res.json();
  4080. state.pppProfiles = Array.isArray(data) ? data : [];
  4081. const b = document.getElementById('ppp-badge-profiles');
  4082. if (b) b.innerText = state.pppProfiles.length;
  4083. const b2 = document.getElementById('profiles-count-badge');
  4084. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4085. // Populate profile selects across modals
  4086. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4087. selects.forEach(sid => {
  4088. const el = document.getElementById(sid);
  4089. if (!el) return;
  4090. const cur = el.value;
  4091. el.innerHTML = '';
  4092. state.pppProfiles.forEach(p => {
  4093. const opt = document.createElement('option');
  4094. opt.value = p.name;
  4095. opt.innerText = `${p.name} (${p.remote_address})`;
  4096. if (p.name === cur) opt.selected = true;
  4097. el.appendChild(opt);
  4098. });
  4099. });
  4100. renderPPPProfiles();
  4101. } catch (err) {
  4102. console.error('Failed to load PPP profiles:', err);
  4103. }
  4104. }
  4105. function renderPPPProfiles() {
  4106. const tbody = document.getElementById('profiles-table-body');
  4107. if (!tbody) return;
  4108. tbody.innerHTML = '';
  4109. (state.pppProfiles || []).forEach(p => {
  4110. const isDefault = p.name.startsWith('default');
  4111. const tr = document.createElement('tr');
  4112. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4113. tr.innerHTML = `
  4114. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4115. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4116. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4117. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4118. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4119. <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>
  4120. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4121. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4122. ${!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>`}
  4123. </td>
  4124. `;
  4125. tbody.appendChild(tr);
  4126. });
  4127. }
  4128. async function loadPPPServers() {
  4129. try {
  4130. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4131. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4132. fetch(`${API_BASE}/vpn/servers/pptp`),
  4133. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4134. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4135. ]);
  4136. if (pppoeRes.ok) {
  4137. state.pppoeServer = await pppoeRes.json();
  4138. const s = state.pppoeServer;
  4139. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4140. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4141. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4142. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4143. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4144. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4145. const pill = document.getElementById('pppoe-server-status-pill');
  4146. if (pill) {
  4147. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4148. 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';
  4149. }
  4150. setDotBadge('ppp-badge-pppoe-state', s.running);
  4151. }
  4152. if (pptpRes.ok) {
  4153. state.pptpServer = await pptpRes.json();
  4154. const s = state.pptpServer;
  4155. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4156. document.getElementById('pptp-server-port').value = s.port || 1723;
  4157. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4158. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4159. const pill = document.getElementById('pptp-server-status-pill');
  4160. if (pill) {
  4161. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4162. 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';
  4163. }
  4164. setDotBadge('ppp-badge-pptp-state', s.running);
  4165. }
  4166. if (l2tpRes.ok) {
  4167. state.l2tpServer = await l2tpRes.json();
  4168. const s = state.l2tpServer;
  4169. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4170. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4171. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4172. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4173. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4174. const pill = document.getElementById('l2tp-server-status-pill');
  4175. if (pill) {
  4176. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4177. 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';
  4178. }
  4179. setDotBadge('ppp-badge-l2tp-state', s.running);
  4180. }
  4181. if (ipsecRes.ok) {
  4182. state.ipsecServer = await ipsecRes.json();
  4183. const s = state.ipsecServer;
  4184. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4185. if (modalEn) modalEn.checked = !!s.enabled;
  4186. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4187. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4188. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4189. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4190. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4191. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4192. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4193. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4194. const pill = document.getElementById('modal-ipsec-server-status');
  4195. if (pill) {
  4196. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4197. 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';
  4198. }
  4199. }
  4200. } catch (err) {
  4201. console.error('Failed to load VPN servers:', err);
  4202. }
  4203. }
  4204. async function loadPPPSessions() {
  4205. try {
  4206. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4207. const data = await res.json();
  4208. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4209. const b = document.getElementById('ppp-badge-active');
  4210. if (b) b.innerText = state.pppActiveSessions.length;
  4211. const sideB = document.getElementById('badge-ppp-sessions');
  4212. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4213. renderPPPSessions();
  4214. } catch (err) {
  4215. console.error('Failed to load active PPP sessions:', err);
  4216. }
  4217. }
  4218. function renderPPPSessions() {
  4219. const tbody = document.getElementById('active-ppp-table-body');
  4220. const empty = document.getElementById('active-ppp-empty');
  4221. if (!tbody) return;
  4222. tbody.innerHTML = '';
  4223. const list = state.pppActiveSessions || [];
  4224. if (list.length === 0) {
  4225. empty?.classList.remove('hidden');
  4226. return;
  4227. }
  4228. empty?.classList.add('hidden');
  4229. list.forEach(s => {
  4230. const tr = document.createElement('tr');
  4231. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4232. tr.innerHTML = `
  4233. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4234. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4235. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4236. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4237. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4238. <td class="py-2.5 px-3 text-[11px]">
  4239. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4240. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4241. </td>
  4242. <td class="py-2.5 px-3 text-right font-sans">
  4243. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4244. </td>
  4245. `;
  4246. tbody.appendChild(tr);
  4247. });
  4248. }
  4249. async function disconnectPPPSession(iface) {
  4250. if (!confirm(`Disconnect session ${iface}?`)) return;
  4251. try {
  4252. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4253. if (res.ok) {
  4254. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4255. loadPPPSessions();
  4256. }
  4257. } catch (err) {
  4258. showToast('Error', err.message, 'error');
  4259. }
  4260. }
  4261. // PPP Secret Modal handlers
  4262. function openAddPPPSecretModal() {
  4263. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4264. document.getElementById('secret-modal-id').value = '';
  4265. document.getElementById('secret-modal-name').value = '';
  4266. document.getElementById('secret-modal-password').value = '';
  4267. document.getElementById('secret-modal-service').value = 'any';
  4268. document.getElementById('secret-modal-profile').value = 'default';
  4269. document.getElementById('secret-modal-local').value = '';
  4270. document.getElementById('secret-modal-remote').value = '';
  4271. document.getElementById('secret-modal-comment').value = '';
  4272. document.getElementById('secret-modal-disabled').checked = false;
  4273. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4274. }
  4275. function openEditPPPSecretModal(id) {
  4276. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4277. if (!s) return;
  4278. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4279. document.getElementById('secret-modal-id').value = s.id;
  4280. document.getElementById('secret-modal-name').value = s.name;
  4281. document.getElementById('secret-modal-password').value = s.password;
  4282. document.getElementById('secret-modal-service').value = s.service || 'any';
  4283. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4284. document.getElementById('secret-modal-local').value = s.local_address || '';
  4285. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4286. document.getElementById('secret-modal-comment').value = s.comment || '';
  4287. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4288. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4289. }
  4290. function closePPPSecretModal() {
  4291. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4292. }
  4293. async function submitSavePPPSecret(e) {
  4294. e.preventDefault();
  4295. const id = document.getElementById('secret-modal-id').value;
  4296. const name = document.getElementById('secret-modal-name').value.trim();
  4297. const password = document.getElementById('secret-modal-password').value.trim();
  4298. const service = document.getElementById('secret-modal-service').value;
  4299. const profile = document.getElementById('secret-modal-profile').value;
  4300. const local = document.getElementById('secret-modal-local').value.trim();
  4301. const remote = document.getElementById('secret-modal-remote').value.trim();
  4302. const comment = document.getElementById('secret-modal-comment').value.trim();
  4303. const disabled = document.getElementById('secret-modal-disabled').checked;
  4304. try {
  4305. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4306. method: 'POST',
  4307. headers: { 'Content-Type': 'application/json' },
  4308. body: JSON.stringify({
  4309. id,
  4310. name,
  4311. password,
  4312. service,
  4313. profile,
  4314. local_address: local,
  4315. remote_address: remote,
  4316. comment,
  4317. disabled
  4318. })
  4319. });
  4320. if (res.ok) {
  4321. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4322. closePPPSecretModal();
  4323. loadPPPSecrets();
  4324. } else {
  4325. const err = await res.json();
  4326. showToast('Error', err.message, 'error');
  4327. }
  4328. } catch (err) {
  4329. showToast('Error', err.message, 'error');
  4330. }
  4331. }
  4332. async function togglePPPSecretState(id, disabled) {
  4333. try {
  4334. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4335. method: 'POST',
  4336. headers: { 'Content-Type': 'application/json' },
  4337. body: JSON.stringify({ disabled })
  4338. });
  4339. if (res.ok) {
  4340. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4341. loadPPPSecrets();
  4342. }
  4343. } catch (err) {
  4344. showToast('Error', err.message, 'error');
  4345. }
  4346. }
  4347. async function deletePPPSecret(id) {
  4348. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4349. try {
  4350. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4351. if (res.ok) {
  4352. showToast('Deleted', 'Secret account removed', 'success');
  4353. loadPPPSecrets();
  4354. }
  4355. } catch (err) {
  4356. showToast('Error', err.message, 'error');
  4357. }
  4358. }
  4359. // PPP Profile Modal handlers
  4360. function openAddPPPProfileModal() {
  4361. document.getElementById('profile-modal-name').value = '';
  4362. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4363. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4364. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4365. document.getElementById('profile-modal-encryption').value = 'required';
  4366. document.getElementById('profile-modal-onlyone').checked = true;
  4367. document.getElementById('profile-modal-comment').value = '';
  4368. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4369. }
  4370. function closePPPProfileModal() {
  4371. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4372. }
  4373. async function submitSavePPPProfile(e) {
  4374. e.preventDefault();
  4375. const name = document.getElementById('profile-modal-name').value.trim();
  4376. const local = document.getElementById('profile-modal-local').value.trim();
  4377. const remote = document.getElementById('profile-modal-remote').value.trim();
  4378. const dns = document.getElementById('profile-modal-dns').value.trim();
  4379. const enc = document.getElementById('profile-modal-encryption').value;
  4380. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4381. const comment = document.getElementById('profile-modal-comment').value.trim();
  4382. try {
  4383. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4384. method: 'POST',
  4385. headers: { 'Content-Type': 'application/json' },
  4386. body: JSON.stringify({
  4387. id: name,
  4388. name,
  4389. local_address: local,
  4390. remote_address: remote,
  4391. dns_servers: dns,
  4392. use_encryption: enc,
  4393. only_one: onlyone,
  4394. comment
  4395. })
  4396. });
  4397. if (res.ok) {
  4398. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4399. closePPPProfileModal();
  4400. loadPPPProfiles();
  4401. } else {
  4402. const err = await res.json();
  4403. showToast('Error', err.message, 'error');
  4404. }
  4405. } catch (err) {
  4406. showToast('Error', err.message, 'error');
  4407. }
  4408. }
  4409. async function deletePPPProfile(name) {
  4410. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4411. try {
  4412. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4413. if (res.ok) {
  4414. showToast('Deleted', 'Profile removed', 'success');
  4415. loadPPPProfiles();
  4416. } else {
  4417. const err = await res.json();
  4418. showToast('Error', err.message, 'error');
  4419. }
  4420. } catch (err) {
  4421. showToast('Error', err.message, 'error');
  4422. }
  4423. }
  4424. // Server Config submissions
  4425. async function savePPPoEServerConfig(e) {
  4426. e.preventDefault();
  4427. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4428. const name = document.getElementById('pppoe-server-name').value.trim();
  4429. const iface = document.getElementById('pppoe-server-iface').value;
  4430. const profile = document.getElementById('pppoe-server-profile').value;
  4431. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4432. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4433. try {
  4434. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4435. method: 'POST',
  4436. headers: { 'Content-Type': 'application/json' },
  4437. body: JSON.stringify({
  4438. enabled,
  4439. service_name: name,
  4440. interface: iface,
  4441. default_profile: profile,
  4442. max_mtu: mtu,
  4443. max_mru: mtu,
  4444. one_session_per_host: onesession
  4445. })
  4446. });
  4447. if (res.ok) {
  4448. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4449. loadPPPServers();
  4450. fetchData(false);
  4451. } else {
  4452. const err = await res.json();
  4453. showToast('Error', err.message, 'error');
  4454. }
  4455. } catch (err) {
  4456. showToast('Error', err.message, 'error');
  4457. }
  4458. }
  4459. async function savePPTPServerConfig(e) {
  4460. e.preventDefault();
  4461. const enabled = document.getElementById('pptp-server-enabled').checked;
  4462. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4463. const profile = document.getElementById('pptp-server-profile').value;
  4464. const mppe = document.getElementById('pptp-server-mppe').checked;
  4465. try {
  4466. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4467. method: 'POST',
  4468. headers: { 'Content-Type': 'application/json' },
  4469. body: JSON.stringify({
  4470. enabled,
  4471. port,
  4472. default_profile: profile,
  4473. require_mppe: mppe
  4474. })
  4475. });
  4476. if (res.ok) {
  4477. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4478. loadPPPServers();
  4479. fetchData(false);
  4480. } else {
  4481. const err = await res.json();
  4482. showToast('Error', err.message, 'error');
  4483. }
  4484. } catch (err) {
  4485. showToast('Error', err.message, 'error');
  4486. }
  4487. }
  4488. async function saveL2TPServerConfig(e) {
  4489. e.preventDefault();
  4490. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4491. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4492. const profile = document.getElementById('l2tp-server-profile').value;
  4493. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4494. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4495. try {
  4496. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4497. method: 'POST',
  4498. headers: { 'Content-Type': 'application/json' },
  4499. body: JSON.stringify({
  4500. enabled,
  4501. port,
  4502. default_profile: profile,
  4503. use_ipsec: useipsec,
  4504. ipsec_secret: psk
  4505. })
  4506. });
  4507. if (res.ok) {
  4508. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4509. loadPPPServers();
  4510. fetchData(false);
  4511. } else {
  4512. const err = await res.json();
  4513. showToast('Error', err.message, 'error');
  4514. }
  4515. } catch (err) {
  4516. showToast('Error', err.message, 'error');
  4517. }
  4518. }
  4519. // IPSec Server Modal
  4520. function openIPSecServerModal() {
  4521. loadPPPServers();
  4522. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4523. }
  4524. function closeIPSecServerModal() {
  4525. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4526. }
  4527. async function submitSaveIPSecServer(e) {
  4528. e.preventDefault();
  4529. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4530. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4531. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4532. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4533. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4534. try {
  4535. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4536. method: 'POST',
  4537. headers: { 'Content-Type': 'application/json' },
  4538. body: JSON.stringify({
  4539. enabled,
  4540. preshared_key: psk,
  4541. pool_address: pool,
  4542. dns_servers: dns,
  4543. local_subnet: subnet
  4544. })
  4545. });
  4546. if (res.ok) {
  4547. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4548. closeIPSecServerModal();
  4549. loadPPPServers();
  4550. fetchData(false);
  4551. } else {
  4552. const err = await res.json();
  4553. showToast('Error', err.message, 'error');
  4554. }
  4555. } catch (err) {
  4556. showToast('Error', err.message, 'error');
  4557. }
  4558. }
  4559. // WireGuard Client Config Viewer
  4560. let currentWGClientConf = '';
  4561. async function openWGClientConfModal(iface, clientIP) {
  4562. try {
  4563. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4564. method: 'POST',
  4565. headers: { 'Content-Type': 'application/json' },
  4566. body: JSON.stringify({
  4567. interface: iface,
  4568. address: clientIP || '10.10.0.2/32',
  4569. dns: '1.1.1.1, 8.8.8.8'
  4570. })
  4571. });
  4572. if (res.ok) {
  4573. const data = await res.json();
  4574. currentWGClientConf = data.config;
  4575. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4576. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4577. } else {
  4578. const err = await res.json();
  4579. showToast('Error', err.message, 'error');
  4580. }
  4581. } catch (err) {
  4582. showToast('Error', err.message, 'error');
  4583. }
  4584. }
  4585. function closeWGClientConfModal() {
  4586. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4587. }
  4588. function copyWGClientConf() {
  4589. if (!currentWGClientConf) return;
  4590. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4591. }
  4592. function downloadWGClientConf() {
  4593. if (!currentWGClientConf) return;
  4594. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4595. const a = document.createElement('a');
  4596. a.href = URL.createObjectURL(blob);
  4597. a.download = 'wireguard-client.conf';
  4598. document.body.appendChild(a);
  4599. a.click();
  4600. document.body.removeChild(a);
  4601. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4602. }
  4603. // =========================================================================
  4604. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4605. // =========================================================================
  4606. state.activeDynSubTab = 'bgp-peers';
  4607. state.activeBgpSubTab = 'bgp-peers';
  4608. state.activeOspfSubTab = 'ospf-ifaces';
  4609. state.bgpInstance = null;
  4610. state.bgpPeers = [];
  4611. state.bgpNets = [];
  4612. state.bgpRoutes = [];
  4613. state.ospfInstance = null;
  4614. state.ospfInterfaces = [];
  4615. state.ospfAreas = [];
  4616. state.ospfNeighbors = [];
  4617. state.ospfRoutes = [];
  4618. function switchBgpSubTab(subTab) {
  4619. state.activeBgpSubTab = subTab;
  4620. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4621. tabs.forEach(t => {
  4622. const el = document.getElementById(`dyn-subtab-${t}`);
  4623. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4624. if (el) el.classList.toggle('hidden', t !== subTab);
  4625. if (btn) {
  4626. if (t === subTab) {
  4627. 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';
  4628. } else {
  4629. 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';
  4630. }
  4631. }
  4632. });
  4633. }
  4634. function switchOspfSubTab(subTab) {
  4635. state.activeOspfSubTab = subTab;
  4636. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4637. tabs.forEach(t => {
  4638. const el = document.getElementById(`dyn-subtab-${t}`);
  4639. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4640. if (el) el.classList.toggle('hidden', t !== subTab);
  4641. if (btn) {
  4642. if (t === subTab) {
  4643. 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';
  4644. } else {
  4645. 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';
  4646. }
  4647. }
  4648. });
  4649. }
  4650. function switchDynSubTab(subTab) {
  4651. if (subTab.startsWith('bgp')) {
  4652. if (state.activeTab !== 'bgp') navigate('bgp');
  4653. switchBgpSubTab(subTab);
  4654. } else if (subTab.startsWith('ospf')) {
  4655. if (state.activeTab !== 'ospf') navigate('ospf');
  4656. switchOspfSubTab(subTab);
  4657. }
  4658. }
  4659. async function loadDynamicRouting(showToastMsg = false) {
  4660. try {
  4661. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes, filtersRes] = await Promise.all([
  4662. fetch(`${API_BASE}/routing/dynamic/summary`),
  4663. fetch(`${API_BASE}/routing/bgp/instance`),
  4664. fetch(`${API_BASE}/routing/bgp/peers`),
  4665. fetch(`${API_BASE}/routing/bgp/networks`),
  4666. fetch(`${API_BASE}/routing/bgp/routes`),
  4667. fetch(`${API_BASE}/routing/ospf/instance`),
  4668. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4669. fetch(`${API_BASE}/routing/ospf/areas`),
  4670. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4671. fetch(`${API_BASE}/routing/ospf/routes`),
  4672. fetch(`${API_BASE}/routing/filters`)
  4673. ]);
  4674. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4675. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4676. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4677. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4678. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4679. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4680. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4681. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4682. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4683. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4684. if (filtersRes && filtersRes.ok) state.routingFilters = await filtersRes.json();
  4685. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4686. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4687. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4688. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4689. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4690. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4691. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4692. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  4693. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  4694. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  4695. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  4696. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  4697. } catch (err) {
  4698. console.error('Failed to load dynamic routing:', err);
  4699. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4700. }
  4701. }
  4702. function renderBgpStatusPill() {
  4703. const pill = document.getElementById('bgp-live-status-pill');
  4704. if (!pill) return;
  4705. const inst = state.bgpInstance;
  4706. if (!inst || !inst.enabled) {
  4707. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4708. pill.innerText = 'BGP DISABLED';
  4709. } else if (inst.running) {
  4710. 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';
  4711. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4712. } else {
  4713. 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';
  4714. pill.innerText = 'BGP STARTING...';
  4715. }
  4716. }
  4717. function renderBgpPeers() {
  4718. const tbody = document.getElementById('bgp-peers-table-body');
  4719. if (!tbody) return;
  4720. const empty = document.getElementById('bgp-peers-empty');
  4721. const countBadge = document.getElementById('bgp-peers-count-badge');
  4722. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4723. const peers = state.bgpPeers || [];
  4724. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4725. if (navBadge) navBadge.innerText = peers.length;
  4726. if (peers.length === 0) {
  4727. tbody.innerHTML = '';
  4728. if (empty) empty.classList.remove('hidden');
  4729. return;
  4730. }
  4731. if (empty) empty.classList.add('hidden');
  4732. tbody.innerHTML = peers.map(p => {
  4733. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4734. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4735. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4736. let stateBadge = '';
  4737. if (p.disabled) {
  4738. 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>';
  4739. } else if (p.state === 'Established') {
  4740. 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>';
  4741. } else if (p.state === 'Connect' || p.state === 'Active') {
  4742. 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>`;
  4743. } else {
  4744. 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>`;
  4745. }
  4746. return `
  4747. <tr class="hover:bg-slate-800/40 transition">
  4748. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4749. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4750. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4751. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4752. <td class="py-2.5 px-3">${stateBadge}</td>
  4753. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4754. <td class="py-2.5 px-3 text-slate-300">
  4755. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4756. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4757. </td>
  4758. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  4759. ${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> ` : ''}
  4760. ${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>` : ''}
  4761. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  4762. </td>
  4763. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4764. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4765. <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'}">
  4766. ${p.disabled ? 'Enable' : 'Disable'}
  4767. </button>
  4768. <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">
  4769. Edit
  4770. </button>
  4771. <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">
  4772. Delete
  4773. </button>
  4774. </td>
  4775. </tr>
  4776. `;
  4777. }).join('');
  4778. }
  4779. function renderBgpNetworks() {
  4780. const tbody = document.getElementById('bgp-nets-table-body');
  4781. if (!tbody) return;
  4782. const empty = document.getElementById('bgp-nets-empty');
  4783. const countBadge = document.getElementById('bgp-nets-count-badge');
  4784. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4785. const nets = state.bgpNets || [];
  4786. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4787. if (navBadge) navBadge.innerText = nets.length;
  4788. if (nets.length === 0) {
  4789. tbody.innerHTML = '';
  4790. if (empty) empty.classList.remove('hidden');
  4791. return;
  4792. }
  4793. if (empty) empty.classList.add('hidden');
  4794. tbody.innerHTML = nets.map(n => `
  4795. <tr class="hover:bg-slate-800/40 transition">
  4796. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4797. <td class="py-2.5 px-3">
  4798. ${n.disabled
  4799. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4800. : '<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>'}
  4801. </td>
  4802. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4803. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4804. <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">
  4805. Delete
  4806. </button>
  4807. </td>
  4808. </tr>
  4809. `).join('');
  4810. }
  4811. function renderBgpRoutes() {
  4812. const tbody = document.getElementById('bgp-routes-table-body');
  4813. if (!tbody) return;
  4814. const empty = document.getElementById('bgp-routes-empty');
  4815. const countBadge = document.getElementById('bgp-routes-count-badge');
  4816. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4817. const routes = state.bgpRoutes || [];
  4818. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4819. if (navBadge) navBadge.innerText = routes.length;
  4820. if (routes.length === 0) {
  4821. tbody.innerHTML = '';
  4822. if (empty) empty.classList.remove('hidden');
  4823. return;
  4824. }
  4825. if (empty) empty.classList.add('hidden');
  4826. tbody.innerHTML = routes.map(r => `
  4827. <tr class="hover:bg-slate-800/40 transition">
  4828. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4829. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4830. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4831. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4832. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4833. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4834. </tr>
  4835. `).join('');
  4836. }
  4837. function renderOspfStatusPill() {
  4838. const pill = document.getElementById('ospf-live-status-pill');
  4839. if (!pill) return;
  4840. const inst = state.ospfInstance;
  4841. if (!inst || !inst.enabled) {
  4842. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4843. pill.innerText = 'OSPF DISABLED';
  4844. } else if (inst.running) {
  4845. 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';
  4846. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4847. } else {
  4848. 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';
  4849. pill.innerText = 'OSPF STARTING...';
  4850. }
  4851. }
  4852. function renderOspfInterfaces() {
  4853. const tbody = document.getElementById('ospf-ifaces-table-body');
  4854. if (!tbody) return;
  4855. const empty = document.getElementById('ospf-ifaces-empty');
  4856. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4857. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4858. const ifaces = state.ospfInterfaces || [];
  4859. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4860. if (navBadge) navBadge.innerText = ifaces.length;
  4861. if (ifaces.length === 0) {
  4862. tbody.innerHTML = '';
  4863. if (empty) empty.classList.remove('hidden');
  4864. return;
  4865. }
  4866. if (empty) empty.classList.add('hidden');
  4867. tbody.innerHTML = ifaces.map(i => {
  4868. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4869. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4870. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4871. return `
  4872. <tr class="hover:bg-slate-800/40 transition">
  4873. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4874. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4875. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4876. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4877. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4878. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4879. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4880. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4881. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4882. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4883. <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'}">
  4884. ${i.disabled ? 'Enable' : 'Disable'}
  4885. </button>
  4886. <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">
  4887. Edit
  4888. </button>
  4889. <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">
  4890. Delete
  4891. </button>
  4892. </td>
  4893. </tr>
  4894. `;
  4895. }).join('');
  4896. }
  4897. function renderOspfAreas() {
  4898. const tbody = document.getElementById('ospf-areas-table-body');
  4899. if (!tbody) return;
  4900. const countBadge = document.getElementById('ospf-areas-count-badge');
  4901. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4902. const areas = state.ospfAreas || [];
  4903. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4904. if (navBadge) navBadge.innerText = areas.length;
  4905. tbody.innerHTML = areas.map(a => `
  4906. <tr class="hover:bg-slate-800/40 transition">
  4907. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4908. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4909. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4910. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4911. <td class="py-2.5 px-3 text-right font-sans">
  4912. <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">
  4913. Delete
  4914. </button>
  4915. </td>
  4916. </tr>
  4917. `).join('');
  4918. }
  4919. function renderOspfNeighbors() {
  4920. const tbody = document.getElementById('ospf-nbrs-table-body');
  4921. if (!tbody) return;
  4922. const empty = document.getElementById('ospf-nbrs-empty');
  4923. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4924. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4925. const nbrs = state.ospfNeighbors || [];
  4926. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4927. if (navBadge) navBadge.innerText = nbrs.length;
  4928. if (nbrs.length === 0) {
  4929. tbody.innerHTML = '';
  4930. if (empty) empty.classList.remove('hidden');
  4931. return;
  4932. }
  4933. if (empty) empty.classList.add('hidden');
  4934. tbody.innerHTML = nbrs.map(n => {
  4935. let stateBadge = '';
  4936. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4937. 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>`;
  4938. } else {
  4939. 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>`;
  4940. }
  4941. return `
  4942. <tr class="hover:bg-slate-800/40 transition">
  4943. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4944. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4945. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4946. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4947. <td class="py-2.5 px-3">${stateBadge}</td>
  4948. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4949. </tr>
  4950. `;
  4951. }).join('');
  4952. }
  4953. function renderOspfRoutes() {
  4954. const tbody = document.getElementById('ospf-routes-table-body');
  4955. if (!tbody) return;
  4956. const empty = document.getElementById('ospf-routes-empty');
  4957. const countBadge = document.getElementById('ospf-routes-count-badge');
  4958. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4959. const routes = state.ospfRoutes || [];
  4960. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4961. if (navBadge) navBadge.innerText = routes.length;
  4962. if (routes.length === 0) {
  4963. tbody.innerHTML = '';
  4964. if (empty) empty.classList.remove('hidden');
  4965. return;
  4966. }
  4967. if (empty) empty.classList.add('hidden');
  4968. tbody.innerHTML = routes.map(r => `
  4969. <tr class="hover:bg-slate-800/40 transition">
  4970. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4971. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4972. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4973. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4974. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4975. </tr>
  4976. `).join('');
  4977. }
  4978. // BGP Modals & Actions
  4979. function openBgpInstanceModal() {
  4980. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4981. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4982. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4983. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4984. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4985. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4986. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4987. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4988. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4989. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4990. }
  4991. function closeBgpInstanceModal() {
  4992. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4993. }
  4994. async function submitBgpInstance(e) {
  4995. e.preventDefault();
  4996. const payload = {
  4997. enabled: document.getElementById('modal-bgp-enabled').checked,
  4998. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4999. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5000. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5001. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5002. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5003. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5004. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5005. };
  5006. try {
  5007. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5008. method: 'POST',
  5009. headers: { 'Content-Type': 'application/json' },
  5010. body: JSON.stringify(payload)
  5011. });
  5012. if (res.ok) {
  5013. closeBgpInstanceModal();
  5014. showToast('Success', 'BGP instance configuration updated', 'success');
  5015. loadDynamicRouting();
  5016. } else {
  5017. const err = await res.json();
  5018. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5019. }
  5020. } catch (err) {
  5021. showToast('Error', err.message, 'error');
  5022. }
  5023. }
  5024. function openAddBgpPeerModal() {
  5025. document.getElementById('bgp-peer-form').reset();
  5026. document.getElementById('modal-bgp-peer-id').value = '';
  5027. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5028. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5029. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5030. if (inFilterEl) inFilterEl.value = '';
  5031. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5032. if (outFilterEl) outFilterEl.value = '';
  5033. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5034. }
  5035. function openEditBgpPeerModal(id) {
  5036. const p = (state.bgpPeers || []).find(item => item.id === id);
  5037. if (!p) return;
  5038. document.getElementById('modal-bgp-peer-id').value = p.id;
  5039. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5040. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5041. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5042. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5043. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5044. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5045. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5046. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5047. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5048. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5049. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5050. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5051. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5052. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5053. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5054. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5055. }
  5056. function closeBgpPeerModal() {
  5057. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5058. }
  5059. async function submitBgpPeer(e) {
  5060. e.preventDefault();
  5061. const payload = {
  5062. id: document.getElementById('modal-bgp-peer-id').value,
  5063. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5064. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5065. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5066. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5067. password: document.getElementById('modal-bgp-peer-password').value,
  5068. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5069. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5070. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5071. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5072. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5073. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5074. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5075. };
  5076. try {
  5077. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5078. method: 'POST',
  5079. headers: { 'Content-Type': 'application/json' },
  5080. body: JSON.stringify(payload)
  5081. });
  5082. if (res.ok) {
  5083. closeBgpPeerModal();
  5084. showToast('Success', 'BGP Peer saved', 'success');
  5085. loadDynamicRouting();
  5086. } else {
  5087. const err = await res.json();
  5088. showToast('Error', err.error || 'Failed to save peer', 'error');
  5089. }
  5090. } catch (err) {
  5091. showToast('Error', err.message, 'error');
  5092. }
  5093. }
  5094. async function deleteBgpPeer(id) {
  5095. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5096. try {
  5097. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5098. if (res.ok) {
  5099. showToast('Deleted', 'BGP peer removed', 'success');
  5100. loadDynamicRouting();
  5101. }
  5102. } catch (err) {
  5103. showToast('Error', err.message, 'error');
  5104. }
  5105. }
  5106. async function toggleBgpPeerState(id, disabled) {
  5107. try {
  5108. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5109. method: 'POST',
  5110. headers: { 'Content-Type': 'application/json' },
  5111. body: JSON.stringify({ disabled })
  5112. });
  5113. if (res.ok) {
  5114. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5115. loadDynamicRouting();
  5116. }
  5117. } catch (err) {
  5118. showToast('Error', err.message, 'error');
  5119. }
  5120. }
  5121. function openAddBgpNetworkModal() {
  5122. document.getElementById('bgp-network-form').reset();
  5123. document.getElementById('modal-bgp-net-id').value = '';
  5124. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5125. }
  5126. function closeBgpNetworkModal() {
  5127. document.getElementById('bgp-network-modal').classList.add('hidden');
  5128. }
  5129. async function submitBgpNetwork(e) {
  5130. e.preventDefault();
  5131. const payload = {
  5132. id: document.getElementById('modal-bgp-net-id').value,
  5133. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5134. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5135. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5136. };
  5137. try {
  5138. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5139. method: 'POST',
  5140. headers: { 'Content-Type': 'application/json' },
  5141. body: JSON.stringify(payload)
  5142. });
  5143. if (res.ok) {
  5144. closeBgpNetworkModal();
  5145. showToast('Success', 'BGP network advertisement saved', 'success');
  5146. loadDynamicRouting();
  5147. } else {
  5148. const err = await res.json();
  5149. showToast('Error', err.error || 'Failed to save network', 'error');
  5150. }
  5151. } catch (err) {
  5152. showToast('Error', err.message, 'error');
  5153. }
  5154. }
  5155. async function deleteBgpNetwork(id) {
  5156. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5157. try {
  5158. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5159. if (res.ok) {
  5160. showToast('Deleted', 'Network advertisement removed', 'success');
  5161. loadDynamicRouting();
  5162. }
  5163. } catch (err) {
  5164. showToast('Error', err.message, 'error');
  5165. }
  5166. }
  5167. // OSPF Modals & Actions
  5168. function openOspfInstanceModal() {
  5169. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5170. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5171. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5172. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5173. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5174. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5175. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5176. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5177. }
  5178. function closeOspfInstanceModal() {
  5179. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5180. }
  5181. async function submitOspfInstance(e) {
  5182. e.preventDefault();
  5183. const payload = {
  5184. enabled: document.getElementById('modal-ospf-enabled').checked,
  5185. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5186. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5187. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5188. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5189. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5190. };
  5191. try {
  5192. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5193. method: 'POST',
  5194. headers: { 'Content-Type': 'application/json' },
  5195. body: JSON.stringify(payload)
  5196. });
  5197. if (res.ok) {
  5198. closeOspfInstanceModal();
  5199. showToast('Success', 'OSPF instance configuration updated', 'success');
  5200. loadDynamicRouting();
  5201. } else {
  5202. const err = await res.json();
  5203. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. function openAddOspfAreaModal() {
  5210. document.getElementById('ospf-area-form').reset();
  5211. document.getElementById('modal-ospf-area-id').value = '';
  5212. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5213. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5214. }
  5215. function closeOspfAreaModal() {
  5216. document.getElementById('ospf-area-modal').classList.add('hidden');
  5217. }
  5218. async function submitOspfArea(e) {
  5219. e.preventDefault();
  5220. const payload = {
  5221. id: document.getElementById('modal-ospf-area-id').value,
  5222. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5223. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5224. area_type: document.getElementById('modal-ospf-area-type').value,
  5225. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5226. };
  5227. try {
  5228. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5229. method: 'POST',
  5230. headers: { 'Content-Type': 'application/json' },
  5231. body: JSON.stringify(payload)
  5232. });
  5233. if (res.ok) {
  5234. closeOspfAreaModal();
  5235. showToast('Success', 'OSPF area saved', 'success');
  5236. loadDynamicRouting();
  5237. } else {
  5238. const err = await res.json();
  5239. showToast('Error', err.error || 'Failed to save area', 'error');
  5240. }
  5241. } catch (err) {
  5242. showToast('Error', err.message, 'error');
  5243. }
  5244. }
  5245. async function deleteOspfArea(id) {
  5246. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5247. try {
  5248. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5249. if (res.ok) {
  5250. showToast('Deleted', 'OSPF area removed', 'success');
  5251. loadDynamicRouting();
  5252. }
  5253. } catch (err) {
  5254. showToast('Error', err.message, 'error');
  5255. }
  5256. }
  5257. function populateOspfInterfaceDevices() {
  5258. const select = document.getElementById('modal-ospf-iface-device');
  5259. if (!select) return;
  5260. const current = select.value;
  5261. select.innerHTML = '<option value="">Any matching interface</option>';
  5262. (state.interfaces || []).forEach(iface => {
  5263. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5264. });
  5265. if (current) select.value = current;
  5266. }
  5267. function openAddOspfInterfaceModal() {
  5268. document.getElementById('ospf-interface-form').reset();
  5269. document.getElementById('modal-ospf-iface-id').value = '';
  5270. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5271. document.getElementById('modal-ospf-iface-cost').value = '10';
  5272. document.getElementById('modal-ospf-iface-priority').value = '1';
  5273. document.getElementById('modal-ospf-iface-hello').value = '10';
  5274. document.getElementById('modal-ospf-iface-dead').value = '40';
  5275. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5276. populateOspfInterfaceDevices();
  5277. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5278. }
  5279. function openEditOspfInterfaceModal(id) {
  5280. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5281. if (!item) return;
  5282. populateOspfInterfaceDevices();
  5283. document.getElementById('modal-ospf-iface-id').value = item.id;
  5284. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5285. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5286. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5287. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5288. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5289. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5290. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5291. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5292. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5293. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5294. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5295. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5296. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5297. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5298. }
  5299. function closeOspfInterfaceModal() {
  5300. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5301. }
  5302. async function submitOspfInterface(e) {
  5303. e.preventDefault();
  5304. const payload = {
  5305. id: document.getElementById('modal-ospf-iface-id').value,
  5306. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5307. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5308. interface: document.getElementById('modal-ospf-iface-device').value,
  5309. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5310. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5311. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5312. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5313. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5314. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5315. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5316. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5317. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5318. };
  5319. try {
  5320. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5321. method: 'POST',
  5322. headers: { 'Content-Type': 'application/json' },
  5323. body: JSON.stringify(payload)
  5324. });
  5325. if (res.ok) {
  5326. closeOspfInterfaceModal();
  5327. showToast('Success', 'OSPF interface template saved', 'success');
  5328. loadDynamicRouting();
  5329. } else {
  5330. const err = await res.json();
  5331. showToast('Error', err.error || 'Failed to save interface', 'error');
  5332. }
  5333. } catch (err) {
  5334. showToast('Error', err.message, 'error');
  5335. }
  5336. }
  5337. async function deleteOspfInterface(id) {
  5338. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5339. try {
  5340. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5341. if (res.ok) {
  5342. showToast('Deleted', 'OSPF interface removed', 'success');
  5343. loadDynamicRouting();
  5344. }
  5345. } catch (err) {
  5346. showToast('Error', err.message, 'error');
  5347. }
  5348. }
  5349. async function toggleOspfInterfaceState(id, disabled) {
  5350. try {
  5351. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5352. method: 'POST',
  5353. headers: { 'Content-Type': 'application/json' },
  5354. body: JSON.stringify({ disabled })
  5355. });
  5356. if (res.ok) {
  5357. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5358. loadDynamicRouting();
  5359. }
  5360. } catch (err) {
  5361. showToast('Error', err.message, 'error');
  5362. }
  5363. }
  5364. // ============================================================================
  5365. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5366. // ============================================================================
  5367. function switchBridgeSubTab(tab) {
  5368. state.bridgeSubTab = tab;
  5369. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5370. tabs.forEach(t => {
  5371. const panel = document.getElementById(`bridge-subtab-${t}`);
  5372. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5373. if (panel) {
  5374. if (t === tab) panel.classList.remove('hidden');
  5375. else panel.classList.add('hidden');
  5376. }
  5377. if (btn) {
  5378. if (t === tab) {
  5379. 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';
  5380. } else {
  5381. 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';
  5382. }
  5383. }
  5384. });
  5385. const addBtn = document.getElementById('bridge-top-action-btn');
  5386. if (addBtn) {
  5387. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5388. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5389. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5390. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5391. }
  5392. if (tab === 'hosts') loadBridgeHosts();
  5393. }
  5394. function openCurrentBridgeModal() {
  5395. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5396. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5397. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5398. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5399. }
  5400. async function loadBridge() {
  5401. try {
  5402. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5403. fetch(`${API_BASE}/bridge/bridges`),
  5404. fetch(`${API_BASE}/bridge/ports`),
  5405. fetch(`${API_BASE}/bridge/vlans`),
  5406. fetch(`${API_BASE}/bridge/summary`),
  5407. fetch(`${API_BASE}/vpn/eoip`),
  5408. fetch(`${API_BASE}/vlans`)
  5409. ]);
  5410. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5411. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5412. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5413. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5414. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5415. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5416. // Badges & Stats
  5417. const bBridges = document.getElementById('bridge-badge-bridges');
  5418. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5419. const bPorts = document.getElementById('bridge-badge-ports');
  5420. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5421. const bVlans = document.getElementById('bridge-badge-vlans');
  5422. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5423. const bHosts = document.getElementById('bridge-badge-hosts');
  5424. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5425. const sBr = document.getElementById('bridge-stat-bridges');
  5426. if (sBr) sBr.innerText = (state.bridges || []).length;
  5427. const sPorts = document.getElementById('bridge-stat-ports');
  5428. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5429. const sHosts = document.getElementById('bridge-stat-hosts');
  5430. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5431. renderBridges();
  5432. renderBridgePorts();
  5433. renderBridgeVLANs();
  5434. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5435. } catch (err) {
  5436. console.error('Failed to load bridge subsystem:', err);
  5437. }
  5438. }
  5439. // ----------------- Bridges -----------------
  5440. function renderBridges() {
  5441. const tbody = document.getElementById('bridge-table-body');
  5442. const empty = document.getElementById('bridge-empty-bridges');
  5443. const countBadge = document.getElementById('bridge-count-badge');
  5444. if (!tbody) return;
  5445. tbody.innerHTML = '';
  5446. const bridges = state.bridges || [];
  5447. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5448. if (bridges.length === 0) {
  5449. empty?.classList.remove('hidden');
  5450. return;
  5451. }
  5452. empty?.classList.add('hidden');
  5453. bridges.forEach((b, idx) => {
  5454. const tr = document.createElement('tr');
  5455. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5456. // Format IP addresses pill list
  5457. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5458. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5459. ipsHtml = b.ip_addresses.map(ip => `
  5460. <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">
  5461. <span>${ip}</span>
  5462. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5463. </span>
  5464. `).join(' ');
  5465. }
  5466. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5467. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5468. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5469. tr.innerHTML = `
  5470. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5471. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5472. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5473. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5474. </td>
  5475. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5476. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5477. <td class="py-2.5 px-3">
  5478. <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>
  5479. </td>
  5480. <td class="py-2.5 px-3 text-center">
  5481. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5482. </td>
  5483. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5484. <td class="py-2.5 px-3">
  5485. <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>
  5486. </td>
  5487. <td class="py-2.5 px-3">
  5488. <div class="flex items-center gap-1.5 flex-wrap">
  5489. ${ipsHtml}
  5490. <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>
  5491. </div>
  5492. </td>
  5493. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5494. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5495. </td>
  5496. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5497. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5498. <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>
  5499. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5500. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5501. </td>
  5502. `;
  5503. tbody.appendChild(tr);
  5504. });
  5505. }
  5506. function openAddBridgeModal() {
  5507. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5508. document.getElementById('bridge-modal-id').value = '';
  5509. document.getElementById('bridge-modal-name').value = 'bridge1';
  5510. document.getElementById('bridge-modal-name').disabled = false;
  5511. document.getElementById('bridge-modal-mtu').value = '1500';
  5512. document.getElementById('bridge-modal-mac').value = '';
  5513. document.getElementById('bridge-modal-stp').value = 'rstp';
  5514. document.getElementById('bridge-modal-priority').value = '32768';
  5515. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5516. document.getElementById('bridge-modal-pvid').value = '1';
  5517. document.getElementById('bridge-modal-fastforward').checked = true;
  5518. document.getElementById('bridge-modal-comment').value = '';
  5519. document.getElementById('bridge-modal-disabled').checked = false;
  5520. toggleBridgeModalVlanFiltering();
  5521. document.getElementById('bridge-modal').classList.remove('hidden');
  5522. }
  5523. function openEditBridgeModal(id) {
  5524. const b = (state.bridges || []).find(x => x.id === id);
  5525. if (!b) return;
  5526. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5527. document.getElementById('bridge-modal-id').value = b.id;
  5528. document.getElementById('bridge-modal-name').value = b.name;
  5529. document.getElementById('bridge-modal-name').disabled = true;
  5530. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5531. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5532. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5533. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5534. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5535. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5536. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5537. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5538. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5539. toggleBridgeModalVlanFiltering();
  5540. document.getElementById('bridge-modal').classList.remove('hidden');
  5541. }
  5542. function closeBridgeModal() {
  5543. document.getElementById('bridge-modal').classList.add('hidden');
  5544. }
  5545. function toggleBridgeModalVlanFiltering() {
  5546. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5547. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5548. if (pvidBox) {
  5549. if (chk) pvidBox.classList.remove('opacity-40');
  5550. else pvidBox.classList.add('opacity-40');
  5551. }
  5552. }
  5553. async function submitSaveBridge(e) {
  5554. e.preventDefault();
  5555. const id = document.getElementById('bridge-modal-id').value;
  5556. const name = document.getElementById('bridge-modal-name').value.trim();
  5557. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5558. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5559. const stp = document.getElementById('bridge-modal-stp').value;
  5560. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5561. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5562. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5563. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5564. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5565. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5566. try {
  5567. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5568. method: 'POST',
  5569. headers: { 'Content-Type': 'application/json' },
  5570. body: JSON.stringify({
  5571. id,
  5572. name,
  5573. mtu,
  5574. mac_address: mac,
  5575. stp,
  5576. priority,
  5577. vlan_filtering: vlanFiltering,
  5578. pvid,
  5579. fast_forward: fastForward,
  5580. comment,
  5581. disabled
  5582. })
  5583. });
  5584. if (res.ok) {
  5585. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5586. closeBridgeModal();
  5587. loadBridge();
  5588. fetchData(false);
  5589. } else {
  5590. const err = await res.json();
  5591. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5592. }
  5593. } catch (err) {
  5594. showToast('Error', err.message, 'error');
  5595. }
  5596. }
  5597. async function toggleBridgeState(id, disabled) {
  5598. try {
  5599. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5600. method: 'POST',
  5601. headers: { 'Content-Type': 'application/json' },
  5602. body: JSON.stringify({ disabled })
  5603. });
  5604. if (res.ok) {
  5605. loadBridge();
  5606. fetchData(false);
  5607. }
  5608. } catch (err) {
  5609. showToast('Error', err.message, 'error');
  5610. }
  5611. }
  5612. async function deleteBridge(id) {
  5613. const b = (state.bridges || []).find(x => x.id === id);
  5614. const name = b ? b.name : id;
  5615. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5616. try {
  5617. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5618. if (res.ok) {
  5619. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5620. loadBridge();
  5621. fetchData(false);
  5622. } else {
  5623. const err = await res.json();
  5624. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5625. }
  5626. } catch (err) {
  5627. showToast('Error', err.message, 'error');
  5628. }
  5629. }
  5630. // ----------------- Bridge IP Assignments -----------------
  5631. function openAddBridgeIPModal(id, name) {
  5632. document.getElementById('bridge-ip-modal-id').value = id;
  5633. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5634. document.getElementById('bridge-ip-modal-cidr').value = '';
  5635. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5636. }
  5637. function closeBridgeIPModal() {
  5638. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5639. }
  5640. async function submitAddBridgeIP(e) {
  5641. e.preventDefault();
  5642. const id = document.getElementById('bridge-ip-modal-id').value;
  5643. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5644. try {
  5645. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5646. method: 'POST',
  5647. headers: { 'Content-Type': 'application/json' },
  5648. body: JSON.stringify({ ip })
  5649. });
  5650. if (res.ok) {
  5651. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5652. closeBridgeIPModal();
  5653. loadBridge();
  5654. fetchData(false);
  5655. } else {
  5656. const err = await res.json();
  5657. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5658. }
  5659. } catch (err) {
  5660. showToast('Error', err.message, 'error');
  5661. }
  5662. }
  5663. async function deleteBridgeIP(id, ip) {
  5664. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5665. try {
  5666. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5667. method: 'DELETE',
  5668. headers: { 'Content-Type': 'application/json' },
  5669. body: JSON.stringify({ ip })
  5670. });
  5671. if (res.ok) {
  5672. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5673. loadBridge();
  5674. fetchData(false);
  5675. }
  5676. } catch (err) {
  5677. showToast('Error', err.message, 'error');
  5678. }
  5679. }
  5680. // ----------------- Bridge Ports -----------------
  5681. function renderBridgePorts() {
  5682. const tbody = document.getElementById('bridge-ports-table-body');
  5683. const empty = document.getElementById('bridge-empty-ports');
  5684. const countBadge = document.getElementById('bridge-ports-count-badge');
  5685. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5686. if (!tbody) return;
  5687. tbody.innerHTML = '';
  5688. // Update filter select
  5689. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5690. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5691. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5692. if (ports.length === 0) {
  5693. empty?.classList.remove('hidden');
  5694. return;
  5695. }
  5696. empty?.classList.add('hidden');
  5697. ports.forEach((p, idx) => {
  5698. const tr = document.createElement('tr');
  5699. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5700. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5701. tr.innerHTML = `
  5702. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5703. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5704. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5705. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5706. </td>
  5707. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5708. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5709. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5710. <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>
  5711. <td class="py-2.5 px-3">
  5712. ${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>'}
  5713. </td>
  5714. <td class="py-2.5 px-3">
  5715. <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>
  5716. </td>
  5717. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5718. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5719. <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>
  5720. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5721. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5722. </td>
  5723. `;
  5724. tbody.appendChild(tr);
  5725. });
  5726. }
  5727. function openAddBridgePortModal() {
  5728. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5729. document.getElementById('bridge-port-modal-id').value = '';
  5730. populateBridgeSelect('bridge-port-modal-bridge');
  5731. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5732. document.getElementById('bridge-port-modal-pvid').value = '1';
  5733. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5734. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5735. document.getElementById('bridge-port-modal-horizon').value = '0';
  5736. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5737. document.getElementById('bridge-port-modal-priority').value = '128';
  5738. document.getElementById('bridge-port-modal-learn').checked = true;
  5739. document.getElementById('bridge-port-modal-comment').value = '';
  5740. document.getElementById('bridge-port-modal-disabled').checked = false;
  5741. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5742. }
  5743. function openEditBridgePortModal(id) {
  5744. const p = (state.bridgePorts || []).find(x => x.id === id);
  5745. if (!p) return;
  5746. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5747. document.getElementById('bridge-port-modal-id').value = p.id;
  5748. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5749. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5750. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5751. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5752. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5753. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5754. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5755. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5756. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5757. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5758. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5759. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5760. }
  5761. function closeBridgePortModal() {
  5762. document.getElementById('bridge-port-modal').classList.add('hidden');
  5763. }
  5764. async function submitSaveBridgePort(e) {
  5765. e.preventDefault();
  5766. const id = document.getElementById('bridge-port-modal-id').value;
  5767. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5768. const iface = document.getElementById('bridge-port-modal-interface').value;
  5769. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5770. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5771. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5772. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5773. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5774. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5775. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5776. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5777. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5778. try {
  5779. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5780. method: 'POST',
  5781. headers: { 'Content-Type': 'application/json' },
  5782. body: JSON.stringify({
  5783. id,
  5784. bridge,
  5785. interface: iface,
  5786. pvid,
  5787. frame_types: frameTypes,
  5788. ingress_filtering: ingressFiltering,
  5789. horizon,
  5790. path_cost: pathCost,
  5791. priority,
  5792. learn,
  5793. comment,
  5794. disabled
  5795. })
  5796. });
  5797. if (res.ok) {
  5798. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5799. closeBridgePortModal();
  5800. loadBridge();
  5801. fetchData(false);
  5802. } else {
  5803. const err = await res.json();
  5804. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5805. }
  5806. } catch (err) {
  5807. showToast('Error', err.message, 'error');
  5808. }
  5809. }
  5810. async function toggleBridgePortState(id, disabled) {
  5811. try {
  5812. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5813. method: 'POST',
  5814. headers: { 'Content-Type': 'application/json' },
  5815. body: JSON.stringify({ disabled })
  5816. });
  5817. if (res.ok) {
  5818. loadBridge();
  5819. fetchData(false);
  5820. }
  5821. } catch (err) {
  5822. showToast('Error', err.message, 'error');
  5823. }
  5824. }
  5825. async function deleteBridgePort(id) {
  5826. const p = (state.bridgePorts || []).find(x => x.id === id);
  5827. const iface = p ? p.interface : id;
  5828. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5829. try {
  5830. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5831. if (res.ok) {
  5832. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5833. loadBridge();
  5834. fetchData(false);
  5835. }
  5836. } catch (err) {
  5837. showToast('Error', err.message, 'error');
  5838. }
  5839. }
  5840. // ----------------- Bridge VLANs -----------------
  5841. function renderBridgeVLANs() {
  5842. const tbody = document.getElementById('bridge-vlans-table-body');
  5843. const empty = document.getElementById('bridge-empty-vlans');
  5844. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5845. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5846. if (!tbody) return;
  5847. tbody.innerHTML = '';
  5848. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5849. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5850. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5851. if (vlans.length === 0) {
  5852. empty?.classList.remove('hidden');
  5853. return;
  5854. }
  5855. empty?.classList.add('hidden');
  5856. vlans.forEach((v, idx) => {
  5857. const tr = document.createElement('tr');
  5858. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5859. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5860. ? 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(' ')
  5861. : '<span class="text-slate-600">none</span>';
  5862. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5863. ? 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(' ')
  5864. : '<span class="text-slate-600">none</span>';
  5865. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5866. tr.innerHTML = `
  5867. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5868. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5869. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5870. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5871. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5872. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5873. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5874. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5875. <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>
  5876. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5877. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5878. </td>
  5879. `;
  5880. tbody.appendChild(tr);
  5881. });
  5882. }
  5883. function openAddBridgeVLANModal() {
  5884. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5885. document.getElementById('bridge-vlan-modal-id').value = '';
  5886. populateBridgeSelect('bridge-vlan-modal-bridge');
  5887. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5888. document.getElementById('bridge-vlan-modal-comment').value = '';
  5889. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5890. updateBridgeVlanPortCheckboxes();
  5891. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5892. }
  5893. function openEditBridgeVLANModal(id) {
  5894. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5895. if (!v) return;
  5896. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5897. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5898. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5899. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5900. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5901. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5902. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5903. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5904. }
  5905. function closeBridgeVlanModal() {
  5906. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5907. }
  5908. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5909. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5910. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5911. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5912. if (!taggedBox || !untaggedBox) return;
  5913. // Ports belonging to the selected bridge
  5914. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5915. if (memberPorts.length === 0) {
  5916. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5917. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5918. return;
  5919. }
  5920. taggedBox.innerHTML = memberPorts.map(p => `
  5921. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5922. <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">
  5923. <span>${p.interface}</span>
  5924. </label>
  5925. `).join('');
  5926. untaggedBox.innerHTML = memberPorts.map(p => `
  5927. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5928. <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">
  5929. <span>${p.interface}</span>
  5930. </label>
  5931. `).join('');
  5932. }
  5933. async function submitSaveBridgeVLAN(e) {
  5934. e.preventDefault();
  5935. const id = document.getElementById('bridge-vlan-modal-id').value;
  5936. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5937. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5938. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5939. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5940. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5941. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5942. try {
  5943. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5944. method: 'POST',
  5945. headers: { 'Content-Type': 'application/json' },
  5946. body: JSON.stringify({
  5947. id,
  5948. bridge,
  5949. vlan_ids: vlanIDs,
  5950. tagged,
  5951. untagged,
  5952. comment,
  5953. disabled
  5954. })
  5955. });
  5956. if (res.ok) {
  5957. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5958. closeBridgeVlanModal();
  5959. loadBridge();
  5960. } else {
  5961. const err = await res.json();
  5962. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5963. }
  5964. } catch (err) {
  5965. showToast('Error', err.message, 'error');
  5966. }
  5967. }
  5968. async function toggleBridgeVLANState(id, disabled) {
  5969. try {
  5970. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5971. method: 'POST',
  5972. headers: { 'Content-Type': 'application/json' },
  5973. body: JSON.stringify({ disabled })
  5974. });
  5975. if (res.ok) loadBridge();
  5976. } catch (err) {
  5977. showToast('Error', err.message, 'error');
  5978. }
  5979. }
  5980. async function deleteBridgeVLAN(id) {
  5981. if (!confirm('Delete this bridge VLAN entry?')) return;
  5982. try {
  5983. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5984. if (res.ok) {
  5985. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5986. loadBridge();
  5987. }
  5988. } catch (err) {
  5989. showToast('Error', err.message, 'error');
  5990. }
  5991. }
  5992. // ----------------- Hosts / MAC Table -----------------
  5993. async function loadBridgeHosts() {
  5994. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5995. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5996. try {
  5997. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5998. const res = await fetch(url);
  5999. if (res.ok) {
  6000. state.bridgeHosts = await res.json();
  6001. renderBridgeHosts();
  6002. }
  6003. } catch (err) {
  6004. console.error('Failed to load bridge hosts:', err);
  6005. }
  6006. }
  6007. function renderBridgeHosts() {
  6008. const tbody = document.getElementById('bridge-hosts-table-body');
  6009. const empty = document.getElementById('bridge-empty-hosts');
  6010. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6011. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6012. if (!tbody) return;
  6013. tbody.innerHTML = '';
  6014. const hosts = (state.bridgeHosts || []).filter(h => {
  6015. if (!search) return true;
  6016. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6017. });
  6018. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6019. if (hosts.length === 0) {
  6020. empty?.classList.remove('hidden');
  6021. return;
  6022. }
  6023. empty?.classList.add('hidden');
  6024. hosts.forEach(h => {
  6025. const tr = document.createElement('tr');
  6026. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6027. let flagBadges = '';
  6028. 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>';
  6029. 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>';
  6030. 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>';
  6031. tr.innerHTML = `
  6032. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6033. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6034. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6035. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6036. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6037. <td class="py-2.5 px-3">${flagBadges}</td>
  6038. `;
  6039. tbody.appendChild(tr);
  6040. });
  6041. }
  6042. async function flushBridgeHosts() {
  6043. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6044. if (!selBridge) {
  6045. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6046. return;
  6047. }
  6048. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6049. try {
  6050. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6051. method: 'POST',
  6052. headers: { 'Content-Type': 'application/json' },
  6053. body: JSON.stringify({ bridge: selBridge })
  6054. });
  6055. if (res.ok) {
  6056. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6057. loadBridgeHosts();
  6058. }
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. // ----------------- Helpers -----------------
  6064. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6065. const sel = document.getElementById(selectId);
  6066. if (!sel) return;
  6067. const prevVal = currentVal || sel.value;
  6068. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6069. (state.bridges || []).forEach(b => {
  6070. const opt = document.createElement('option');
  6071. opt.value = b.name;
  6072. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6073. if (b.name === prevVal) opt.selected = true;
  6074. sel.appendChild(opt);
  6075. });
  6076. }
  6077. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6078. const sel = document.getElementById(selectId);
  6079. if (!sel) return;
  6080. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6081. // 1. Physical Interfaces
  6082. const grpPhys = document.createElement('optgroup');
  6083. grpPhys.label = 'Physical Interfaces';
  6084. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6085. const opt = document.createElement('option');
  6086. opt.value = i.name;
  6087. opt.innerText = `${i.name} (${i.role || i.type})`;
  6088. if (i.name === currentVal) opt.selected = true;
  6089. grpPhys.appendChild(opt);
  6090. });
  6091. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6092. // 2. VLAN Sub-interfaces
  6093. const grpVlans = document.createElement('optgroup');
  6094. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6095. (state.vlans || []).forEach(v => {
  6096. const opt = document.createElement('option');
  6097. opt.value = v.name;
  6098. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6099. if (v.name === currentVal) opt.selected = true;
  6100. grpVlans.appendChild(opt);
  6101. });
  6102. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6103. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6104. const grpEoip = document.createElement('optgroup');
  6105. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6106. (state.eoipTunnels || []).forEach(t => {
  6107. const opt = document.createElement('option');
  6108. opt.value = t.name;
  6109. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6110. if (t.name === currentVal) opt.selected = true;
  6111. grpEoip.appendChild(opt);
  6112. });
  6113. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6114. }
  6115. // -------------------------------------------------------------
  6116. // Routing Filters Management (/routing filter)
  6117. // -------------------------------------------------------------
  6118. function renderRoutingFilters() {
  6119. const tbody = document.getElementById('routing-filters-table-body');
  6120. if (!tbody) return;
  6121. const empty = document.getElementById('routing-filters-empty');
  6122. const countBadge = document.getElementById('routing-filters-count-badge');
  6123. const navBadge = document.getElementById('badge-filters-count');
  6124. const chainSelect = document.getElementById('routing-filter-chain-select');
  6125. const allRules = state.routingFilters || [];
  6126. if (navBadge) navBadge.innerText = allRules.length;
  6127. // Populate chain filter select options dynamically
  6128. if (chainSelect) {
  6129. const currentVal = state.filterChainSelected || 'all';
  6130. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6131. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6132. uniqueChains.map(ch => {
  6133. const count = allRules.filter(r => r.chain === ch).length;
  6134. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6135. }).join('');
  6136. chainSelect.value = currentVal;
  6137. }
  6138. // Filter rules by selected chain
  6139. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6140. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6141. : allRules.slice();
  6142. // Sort by chain then rule_order
  6143. filteredRules.sort((a, b) => {
  6144. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6145. return (a.rule_order || 0) - (b.rule_order || 0);
  6146. });
  6147. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6148. if (filteredRules.length === 0) {
  6149. tbody.innerHTML = '';
  6150. if (empty) empty.classList.remove('hidden');
  6151. return;
  6152. }
  6153. if (empty) empty.classList.add('hidden');
  6154. tbody.innerHTML = filteredRules.map(r => {
  6155. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6156. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6157. let actionBadge = '';
  6158. if (r.action === 'accept') {
  6159. 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>';
  6160. } else if (r.action === 'discard') {
  6161. 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>';
  6162. } else if (r.action === 'reject') {
  6163. 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>';
  6164. } else {
  6165. 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>`;
  6166. }
  6167. // Prefix match
  6168. let matchPfx = '';
  6169. if (r.prefix) {
  6170. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6171. if (r.prefix_len) {
  6172. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6173. }
  6174. } else {
  6175. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6176. }
  6177. // Other matches
  6178. const matchExtra = [];
  6179. if (r.match_protocol && r.match_protocol !== 'any') {
  6180. 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>`);
  6181. }
  6182. if (r.match_as_path) {
  6183. 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>`);
  6184. }
  6185. if (r.match_community) {
  6186. 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>`);
  6187. }
  6188. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6189. // Set modifications
  6190. const setBadges = [];
  6191. if (r.set_local_pref > 0) {
  6192. 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>`);
  6193. }
  6194. if (r.set_metric > 0) {
  6195. 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>`);
  6196. }
  6197. if (r.set_as_prepend > 0) {
  6198. 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>`);
  6199. }
  6200. if (r.set_community) {
  6201. 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>`);
  6202. }
  6203. if (r.set_next_hop) {
  6204. 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>`);
  6205. }
  6206. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6207. return `
  6208. <tr class="hover:bg-slate-800/40 transition">
  6209. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6210. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6211. <td class="py-2.5 px-3">
  6212. <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>
  6213. </td>
  6214. <td class="py-2.5 px-3">${actionBadge}</td>
  6215. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6216. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6217. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6218. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6219. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6220. <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'}">
  6221. ${r.disabled ? 'Enable' : 'Disable'}
  6222. </button>
  6223. <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">
  6224. Edit
  6225. </button>
  6226. <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">
  6227. Delete
  6228. </button>
  6229. </td>
  6230. </tr>
  6231. `;
  6232. }).join('');
  6233. }
  6234. function filterRoutingFiltersByChain(chain) {
  6235. state.filterChainSelected = chain;
  6236. renderRoutingFilters();
  6237. }
  6238. function openAddRoutingFilterModal(defaultChain = '') {
  6239. const form = document.getElementById('routing-filter-form');
  6240. if (form) form.reset();
  6241. const idEl = document.getElementById('modal-rf-id');
  6242. if (idEl) idEl.value = '';
  6243. const titleEl = document.getElementById('modal-rf-title');
  6244. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6245. const chainEl = document.getElementById('modal-rf-chain');
  6246. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6247. const orderEl = document.getElementById('modal-rf-order');
  6248. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6249. const actEl = document.getElementById('modal-rf-action');
  6250. if (actEl) actEl.value = 'accept';
  6251. const protoEl = document.getElementById('modal-rf-protocol');
  6252. if (protoEl) protoEl.value = 'any';
  6253. const disEl = document.getElementById('modal-rf-disabled');
  6254. if (disEl) disEl.checked = false;
  6255. const modal = document.getElementById('modal-routing-filter');
  6256. if (modal) modal.classList.remove('hidden');
  6257. }
  6258. function openEditRoutingFilterModal(id) {
  6259. const r = (state.routingFilters || []).find(item => item.id === id);
  6260. if (!r) return;
  6261. const idEl = document.getElementById('modal-rf-id');
  6262. if (idEl) idEl.value = r.id;
  6263. const titleEl = document.getElementById('modal-rf-title');
  6264. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6265. const chainEl = document.getElementById('modal-rf-chain');
  6266. if (chainEl) chainEl.value = r.chain || '';
  6267. const orderEl = document.getElementById('modal-rf-order');
  6268. if (orderEl) orderEl.value = r.rule_order || 10;
  6269. const actEl = document.getElementById('modal-rf-action');
  6270. if (actEl) actEl.value = r.action || 'accept';
  6271. const pfxEl = document.getElementById('modal-rf-prefix');
  6272. if (pfxEl) pfxEl.value = r.prefix || '';
  6273. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6274. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6275. const protoEl = document.getElementById('modal-rf-protocol');
  6276. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6277. const aspEl = document.getElementById('modal-rf-as-path');
  6278. if (aspEl) aspEl.value = r.match_as_path || '';
  6279. const commEl = document.getElementById('modal-rf-community');
  6280. if (commEl) commEl.value = r.match_community || '';
  6281. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6282. if (lpEl) lpEl.value = r.set_local_pref || '';
  6283. const metEl = document.getElementById('modal-rf-set-metric');
  6284. if (metEl) metEl.value = r.set_metric || '';
  6285. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6286. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6287. const setCommEl = document.getElementById('modal-rf-set-community');
  6288. if (setCommEl) setCommEl.value = r.set_community || '';
  6289. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6290. if (nhEl) nhEl.value = r.set_next_hop || '';
  6291. const comEl = document.getElementById('modal-rf-comment');
  6292. if (comEl) comEl.value = r.comment || '';
  6293. const disEl = document.getElementById('modal-rf-disabled');
  6294. if (disEl) disEl.checked = !!r.disabled;
  6295. const modal = document.getElementById('modal-routing-filter');
  6296. if (modal) modal.classList.remove('hidden');
  6297. }
  6298. function closeRoutingFilterModal() {
  6299. const modal = document.getElementById('modal-routing-filter');
  6300. if (modal) modal.classList.add('hidden');
  6301. }
  6302. async function submitRoutingFilter(e) {
  6303. e.preventDefault();
  6304. const payload = {
  6305. id: document.getElementById('modal-rf-id').value,
  6306. chain: document.getElementById('modal-rf-chain').value.trim(),
  6307. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6308. action: document.getElementById('modal-rf-action').value,
  6309. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6310. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6311. match_protocol: document.getElementById('modal-rf-protocol').value,
  6312. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6313. match_community: document.getElementById('modal-rf-community').value.trim(),
  6314. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6315. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6316. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6317. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6318. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6319. comment: document.getElementById('modal-rf-comment').value.trim(),
  6320. disabled: document.getElementById('modal-rf-disabled').checked
  6321. };
  6322. try {
  6323. const res = await fetch(`${API_BASE}/routing/filters`, {
  6324. method: 'POST',
  6325. headers: { 'Content-Type': 'application/json' },
  6326. body: JSON.stringify(payload)
  6327. });
  6328. if (res.ok) {
  6329. closeRoutingFilterModal();
  6330. showToast('Success', 'Routing filter rule saved', 'success');
  6331. loadDynamicRouting();
  6332. } else {
  6333. const err = await res.json();
  6334. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6335. }
  6336. } catch (err) {
  6337. showToast('Error', err.message, 'error');
  6338. }
  6339. }
  6340. async function deleteRoutingFilter(id) {
  6341. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6342. try {
  6343. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6344. if (res.ok) {
  6345. showToast('Deleted', 'Routing filter rule removed', 'info');
  6346. loadDynamicRouting();
  6347. } else {
  6348. const err = await res.json();
  6349. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6350. }
  6351. } catch (err) {
  6352. showToast('Error', err.message, 'error');
  6353. }
  6354. }
  6355. async function toggleRoutingFilterState(id, disabled) {
  6356. try {
  6357. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6358. method: 'POST',
  6359. headers: { 'Content-Type': 'application/json' },
  6360. body: JSON.stringify({ disabled })
  6361. });
  6362. if (res.ok) {
  6363. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6364. loadDynamicRouting();
  6365. } else {
  6366. const err = await res.json();
  6367. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6368. }
  6369. } catch (err) {
  6370. showToast('Error', err.message, 'error');
  6371. }
  6372. }
  6373. // ==========================================
  6374. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6375. // ==========================================
  6376. function loadToolsView() {
  6377. populateToolsInterfaces();
  6378. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6379. }
  6380. function populateToolsInterfaces() {
  6381. const pingSel = document.getElementById('tools-ping-iface');
  6382. const traceSel = document.getElementById('tools-trace-iface');
  6383. if (!pingSel || !traceSel) return;
  6384. const currentPing = pingSel.value;
  6385. const currentTrace = traceSel.value;
  6386. let opts = '<option value="">Default (System Routing)</option>';
  6387. if (Array.isArray(state.interfaces)) {
  6388. state.interfaces.forEach(iface => {
  6389. if (iface.name) {
  6390. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6391. }
  6392. });
  6393. }
  6394. pingSel.innerHTML = opts;
  6395. traceSel.innerHTML = opts;
  6396. if (currentPing) pingSel.value = currentPing;
  6397. if (currentTrace) traceSel.value = currentTrace;
  6398. }
  6399. function switchToolsSubTab(subTab) {
  6400. state.activeToolsSubTab = subTab;
  6401. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6402. tabs.forEach(t => {
  6403. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6404. const view = document.getElementById(`tools-view-${t}`);
  6405. if (btn) {
  6406. if (t === subTab) {
  6407. 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';
  6408. } else {
  6409. 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';
  6410. }
  6411. }
  6412. if (view) {
  6413. if (t === subTab) {
  6414. view.classList.remove('hidden');
  6415. } else {
  6416. view.classList.add('hidden');
  6417. }
  6418. }
  6419. });
  6420. }
  6421. function setPortPreset(port) {
  6422. const input = document.getElementById('tools-port-num');
  6423. if (input) input.value = port;
  6424. }
  6425. async function executePing(e) {
  6426. if (e) e.preventDefault();
  6427. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6428. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6429. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6430. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '5', 10);
  6431. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6432. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6433. if (!target) {
  6434. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6435. return;
  6436. }
  6437. const btn = document.getElementById('tools-ping-btn');
  6438. const spinner = document.getElementById('tools-ping-spinner');
  6439. if (btn) btn.disabled = true;
  6440. if (spinner) spinner.classList.remove('hidden');
  6441. try {
  6442. const res = await fetch(`${API_BASE}/tools/ping`, {
  6443. method: 'POST',
  6444. headers: { 'Content-Type': 'application/json' },
  6445. body: JSON.stringify({
  6446. target,
  6447. count,
  6448. size,
  6449. timeout,
  6450. interface: iface,
  6451. dont_frag: dontFrag
  6452. })
  6453. });
  6454. const data = await res.json();
  6455. if (!res.ok) {
  6456. showToast('Ping Error', data.error || 'Failed to execute ping', 'error');
  6457. return;
  6458. }
  6459. const resCard = document.getElementById('tools-ping-results');
  6460. if (resCard) resCard.classList.remove('hidden');
  6461. document.getElementById('tools-ping-stat-sent').innerText = data.packets_sent ?? 0;
  6462. document.getElementById('tools-ping-stat-rcv').innerText = data.packets_recv ?? 0;
  6463. const lossEl = document.getElementById('tools-ping-stat-loss');
  6464. if (lossEl) {
  6465. const loss = data.packet_loss_pct ?? 0;
  6466. lossEl.innerText = `${loss}%`;
  6467. lossEl.className = loss === 0 ? 'text-lg font-bold font-mono text-emerald-400' : (loss < 50 ? 'text-lg font-bold font-mono text-amber-400' : 'text-lg font-bold font-mono text-rose-400');
  6468. }
  6469. document.getElementById('tools-ping-stat-min').innerText = data.min_rtt_ms ? `${data.min_rtt_ms.toFixed(1)} ms` : '--';
  6470. document.getElementById('tools-ping-stat-avg').innerText = data.avg_rtt_ms ? `${data.avg_rtt_ms.toFixed(1)} ms` : '--';
  6471. document.getElementById('tools-ping-stat-max').innerText = data.max_rtt_ms ? `${data.max_rtt_ms.toFixed(1)} ms` : '--';
  6472. document.getElementById('tools-ping-stat-jitter').innerText = data.mdev_rtt_ms ? `${data.mdev_rtt_ms.toFixed(2)} ms` : '--';
  6473. const tbody = document.getElementById('tools-ping-table-body');
  6474. if (tbody) {
  6475. if (Array.isArray(data.replies) && data.replies.length > 0) {
  6476. tbody.innerHTML = data.replies.map(r => `
  6477. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6478. <td class="p-3 text-slate-300">#${r.seq}</td>
  6479. <td class="p-3 font-semibold text-white">${escapeHtml(r.from)}</td>
  6480. <td class="p-3 text-slate-400">${r.bytes} bytes</td>
  6481. <td class="p-3 text-slate-300">${r.ttl}</td>
  6482. <td class="p-3 font-bold text-amber-300">${r.time_ms.toFixed(2)} ms</td>
  6483. <td class="p-3"><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>
  6484. </tr>
  6485. `).join('');
  6486. } else {
  6487. tbody.innerHTML = `<tr><td colspan="6" class="p-4 text-center text-xs text-rose-400 font-mono">No replies received (100% packet loss or timed out)</td></tr>`;
  6488. }
  6489. }
  6490. const rawEl = document.getElementById('tools-ping-raw');
  6491. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6492. showToast('Ping Finished', `Sent ${data.packets_sent}, received ${data.packets_recv} (${data.packet_loss_pct}% loss)`, data.packet_loss_pct === 0 ? 'success' : 'info');
  6493. } catch (err) {
  6494. showToast('Ping Error', err.message, 'error');
  6495. } finally {
  6496. if (btn) btn.disabled = false;
  6497. if (spinner) spinner.classList.add('hidden');
  6498. }
  6499. }
  6500. async function executeTraceroute(e) {
  6501. if (e) e.preventDefault();
  6502. const target = document.getElementById('tools-trace-target')?.value?.trim();
  6503. const maxHops = parseInt(document.getElementById('tools-trace-maxhops')?.value || '15', 10);
  6504. const timeout = parseInt(document.getElementById('tools-trace-timeout')?.value || '1', 10);
  6505. const protocol = document.getElementById('tools-trace-protocol')?.value || 'icmp';
  6506. const iface = document.getElementById('tools-trace-iface')?.value || '';
  6507. const resolve = document.getElementById('tools-trace-resolve')?.checked || false;
  6508. if (!target) {
  6509. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6510. return;
  6511. }
  6512. const btn = document.getElementById('tools-trace-btn');
  6513. const spinner = document.getElementById('tools-trace-spinner');
  6514. if (btn) btn.disabled = true;
  6515. if (spinner) spinner.classList.remove('hidden');
  6516. try {
  6517. const res = await fetch(`${API_BASE}/tools/traceroute`, {
  6518. method: 'POST',
  6519. headers: { 'Content-Type': 'application/json' },
  6520. body: JSON.stringify({
  6521. target,
  6522. max_hops: maxHops,
  6523. timeout,
  6524. protocol,
  6525. interface: iface,
  6526. resolve
  6527. })
  6528. });
  6529. const data = await res.json();
  6530. if (!res.ok) {
  6531. showToast('Traceroute Error', data.error || 'Failed to execute traceroute', 'error');
  6532. return;
  6533. }
  6534. const resCard = document.getElementById('tools-trace-results');
  6535. if (resCard) resCard.classList.remove('hidden');
  6536. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  6537. const statHops = document.getElementById('tools-trace-stat-hops');
  6538. if (statHops) statHops.innerText = hopsCount;
  6539. const statStatus = document.getElementById('tools-trace-stat-status');
  6540. if (statStatus) {
  6541. statStatus.innerText = hopsCount > 0 ? 'Trace Complete' : 'No Hops Discovered';
  6542. statStatus.className = hopsCount > 0 ? 'text-xs font-bold font-mono text-emerald-400' : 'text-xs font-bold font-mono text-rose-400';
  6543. }
  6544. const tbody = document.getElementById('tools-trace-table-body');
  6545. if (tbody) {
  6546. if (hopsCount > 0) {
  6547. tbody.innerHTML = data.hops.map(h => {
  6548. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  6549. const rttDisplay = Array.isArray(h.times_ms) && h.times_ms.length > 0 ? h.times_ms.join(', ') : (isTimeout ? '* * *' : '--');
  6550. return `
  6551. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}">
  6552. <td class="p-3 text-slate-300 font-bold">${h.hop}</td>
  6553. <td class="p-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${escapeHtml(h.ip || (isTimeout ? 'Request timed out' : ''))}</td>
  6554. <td class="p-3 text-slate-400">${escapeHtml(h.host || '--')}</td>
  6555. <td class="p-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rttDisplay)}</td>
  6556. <td class="p-3">
  6557. ${isTimeout
  6558. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  6559. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REACHABLE</span>'}
  6560. </td>
  6561. </tr>
  6562. `;
  6563. }).join('');
  6564. } else {
  6565. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-rose-400 font-mono">No route or hops discovered</td></tr>`;
  6566. }
  6567. }
  6568. const rawEl = document.getElementById('tools-trace-raw');
  6569. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6570. showToast('Traceroute Finished', `Traced ${hopsCount} hops to ${target}`, 'info');
  6571. } catch (err) {
  6572. showToast('Traceroute Error', err.message, 'error');
  6573. } finally {
  6574. if (btn) btn.disabled = false;
  6575. if (spinner) spinner.classList.add('hidden');
  6576. }
  6577. }
  6578. async function executeMTR(e) {
  6579. if (e) e.preventDefault();
  6580. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  6581. const cycles = parseInt(document.getElementById('tools-mtr-cycles')?.value || '3', 10);
  6582. if (!target) {
  6583. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6584. return;
  6585. }
  6586. const btn = document.getElementById('tools-mtr-btn');
  6587. const spinner = document.getElementById('tools-mtr-spinner');
  6588. if (btn) btn.disabled = true;
  6589. if (spinner) spinner.classList.remove('hidden');
  6590. try {
  6591. const res = await fetch(`${API_BASE}/tools/mtr`, {
  6592. method: 'POST',
  6593. headers: { 'Content-Type': 'application/json' },
  6594. body: JSON.stringify({ target, count: cycles })
  6595. });
  6596. const data = await res.json();
  6597. if (!res.ok) {
  6598. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  6599. return;
  6600. }
  6601. const resCard = document.getElementById('tools-mtr-results');
  6602. if (resCard) resCard.classList.remove('hidden');
  6603. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  6604. const statHops = document.getElementById('tools-mtr-stat-hops');
  6605. if (statHops) statHops.innerText = hopsCount;
  6606. const statDest = document.getElementById('tools-mtr-stat-dest');
  6607. if (statDest) statDest.innerText = data.target || target;
  6608. const tbody = document.getElementById('tools-mtr-table-body');
  6609. if (tbody) {
  6610. if (hopsCount > 0) {
  6611. tbody.innerHTML = data.hops.map(h => {
  6612. 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');
  6613. return `
  6614. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6615. <td class="p-3 text-slate-300 font-bold">${h.hop}</td>
  6616. <td class="p-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  6617. <td class="p-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  6618. <td class="p-3 text-slate-300">${h.sent}</td>
  6619. <td class="p-3 text-slate-300">${h.last_ms.toFixed(1)} ms</td>
  6620. <td class="p-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)} ms</td>
  6621. <td class="p-3 text-emerald-400">${h.best_ms.toFixed(1)} ms</td>
  6622. <td class="p-3 text-rose-400">${h.wrst_ms.toFixed(1)} ms</td>
  6623. <td class="p-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  6624. </tr>
  6625. `;
  6626. }).join('');
  6627. } else {
  6628. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  6629. }
  6630. }
  6631. const rawEl = document.getElementById('tools-mtr-raw');
  6632. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6633. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  6634. } catch (err) {
  6635. showToast('MTR Error', err.message, 'error');
  6636. } finally {
  6637. if (btn) btn.disabled = false;
  6638. if (spinner) spinner.classList.add('hidden');
  6639. }
  6640. }
  6641. async function executeDNS(e) {
  6642. if (e) e.preventDefault();
  6643. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  6644. const type = document.getElementById('tools-dns-type')?.value || 'A';
  6645. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  6646. if (!domain) {
  6647. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  6648. return;
  6649. }
  6650. const btn = document.getElementById('tools-dns-btn');
  6651. const spinner = document.getElementById('tools-dns-spinner');
  6652. if (btn) btn.disabled = true;
  6653. if (spinner) spinner.classList.remove('hidden');
  6654. try {
  6655. const res = await fetch(`${API_BASE}/tools/dns`, {
  6656. method: 'POST',
  6657. headers: { 'Content-Type': 'application/json' },
  6658. body: JSON.stringify({ domain, type, server })
  6659. });
  6660. const data = await res.json();
  6661. if (!res.ok) {
  6662. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  6663. return;
  6664. }
  6665. const resCard = document.getElementById('tools-dns-results');
  6666. if (resCard) resCard.classList.remove('hidden');
  6667. const statTime = document.getElementById('tools-dns-stat-time');
  6668. if (statTime) statTime.innerText = `${data.query_time_ms ?? 0} ms`;
  6669. const statServer = document.getElementById('tools-dns-stat-server');
  6670. if (statServer) statServer.innerText = data.server || (server || 'System Resolver');
  6671. const tbody = document.getElementById('tools-dns-table-body');
  6672. if (tbody) {
  6673. if (Array.isArray(data.records) && data.records.length > 0) {
  6674. tbody.innerHTML = data.records.map(r => `
  6675. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6676. <td class="p-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  6677. <td class="p-3 text-slate-400">${r.ttl}s</td>
  6678. <td class="p-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>
  6679. <td class="p-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  6680. </tr>
  6681. `).join('');
  6682. } else {
  6683. tbody.innerHTML = `<tr><td colspan="4" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  6684. }
  6685. }
  6686. const rawEl = document.getElementById('tools-dns-raw');
  6687. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6688. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  6689. } catch (err) {
  6690. showToast('DNS Error', err.message, 'error');
  6691. } finally {
  6692. if (btn) btn.disabled = false;
  6693. if (spinner) spinner.classList.add('hidden');
  6694. }
  6695. }
  6696. async function executePortProbe(e) {
  6697. if (e) e.preventDefault();
  6698. const target = document.getElementById('tools-port-target')?.value?.trim();
  6699. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  6700. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  6701. if (!target || !port) {
  6702. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  6703. return;
  6704. }
  6705. const btn = document.getElementById('tools-port-btn');
  6706. const spinner = document.getElementById('tools-port-spinner');
  6707. if (btn) btn.disabled = true;
  6708. if (spinner) spinner.classList.remove('hidden');
  6709. try {
  6710. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  6711. method: 'POST',
  6712. headers: { 'Content-Type': 'application/json' },
  6713. body: JSON.stringify({ target, port, timeout })
  6714. });
  6715. const data = await res.json();
  6716. if (!res.ok) {
  6717. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  6718. return;
  6719. }
  6720. const resCard = document.getElementById('tools-port-results');
  6721. if (resCard) resCard.classList.remove('hidden');
  6722. const banner = document.getElementById('tools-port-banner');
  6723. const icon = document.getElementById('tools-port-icon');
  6724. const title = document.getElementById('tools-port-title');
  6725. const sub = document.getElementById('tools-port-sub');
  6726. const latency = document.getElementById('tools-port-latency');
  6727. if (data.open) {
  6728. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  6729. if (icon) {
  6730. 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';
  6731. icon.innerText = '✓';
  6732. }
  6733. if (title) {
  6734. title.className = 'text-sm font-bold text-emerald-300';
  6735. title.innerText = `PORT ${port} OPEN / LISTENING`;
  6736. }
  6737. if (sub) {
  6738. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  6739. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  6740. }
  6741. if (latency) {
  6742. latency.className = 'text-base font-bold font-mono text-emerald-300';
  6743. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  6744. }
  6745. } else {
  6746. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  6747. if (icon) {
  6748. 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';
  6749. icon.innerText = '✕';
  6750. }
  6751. if (title) {
  6752. title.className = 'text-sm font-bold text-rose-300';
  6753. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  6754. }
  6755. if (sub) {
  6756. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  6757. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  6758. }
  6759. if (latency) {
  6760. latency.className = 'text-base font-bold font-mono text-slate-500';
  6761. latency.innerText = '--';
  6762. }
  6763. }
  6764. const rawEl = document.getElementById('tools-port-raw');
  6765. 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'}`);
  6766. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  6767. } catch (err) {
  6768. showToast('Probe Error', err.message, 'error');
  6769. } finally {
  6770. if (btn) btn.disabled = false;
  6771. if (spinner) spinner.classList.add('hidden');
  6772. }
  6773. }