app.js 318 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528
  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. try { populateToolsInterfaces(); } catch (e) {}
  182. }
  183. if (vlansRes.ok) {
  184. const vlansData = await vlansRes.json();
  185. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  186. }
  187. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  188. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  189. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  190. updateSystemMetrics();
  191. updateBadges();
  192. if (state.activeTab === 'dashboard') renderDashboard();
  193. if (state.activeTab === 'interfaces') renderInterfacesList();
  194. if (state.activeTab === 'vlans') renderVlansList();
  195. if (state.activeTab === 'firewall') loadFirewall(false);
  196. if (state.activeTab === 'routes') loadRoutes(false);
  197. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  198. if (state.activeTab === 'ppp') loadPPP(false);
  199. if (state.activeTab === 'eoip') loadEoIP(false);
  200. if (state.activeTab === 'pppoe') loadPPPoE(false);
  201. if (state.activeTab === 'wireguard') loadWireGuard(false);
  202. if (state.activeTab === 'ipsec') loadIPSec(false);
  203. if (state.activeTab === 'l2tp') loadL2TP(false);
  204. if (state.activeTab === 'pptp') loadPPTP(false);
  205. } catch (err) {
  206. console.error('Failed to fetch router state:', err);
  207. } finally {
  208. if (isManual && spinner) {
  209. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  210. }
  211. }
  212. }
  213. // Update Top KPI and Sidebar Telemetry
  214. function updateSystemMetrics() {
  215. const s = state.systemStatus;
  216. const v = state.vpnStatus;
  217. if (!s) return;
  218. // Sidebar
  219. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  220. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  221. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  222. if (s.cpu_pct !== undefined) {
  223. const pct = s.cpu_pct;
  224. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  225. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  226. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  227. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  228. } else if (s.cpu_load && s.cpu_load.length > 0) {
  229. const cores = s.cpu_cores || 4;
  230. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  231. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  232. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  233. }
  234. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  235. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  236. // Dashboard Stats
  237. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  238. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  239. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  240. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  241. // VPN Status Indicators
  242. if (v) {
  243. const totalActive = v.total_active_tunnels || 0;
  244. const statVpnActive = document.getElementById('stat-vpn-active');
  245. if (statVpnActive) statVpnActive.innerText = totalActive;
  246. const tunnelsDot = document.getElementById('tunnels-dot');
  247. const tunnelsLabel = document.getElementById('tunnels-label');
  248. if (tunnelsDot && tunnelsLabel) {
  249. if (totalActive > 0) {
  250. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  251. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  252. } else {
  253. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  254. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  255. }
  256. }
  257. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  258. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  259. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  260. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  261. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  262. }
  263. // Total Live Bandwidth Rate
  264. let totalRx = 0;
  265. let totalTx = 0;
  266. (state.interfaces || []).forEach(i => {
  267. if (i.rate) {
  268. totalRx += i.rate.rx_bytes_sec || 0;
  269. totalTx += i.rate.tx_bytes_sec || 0;
  270. }
  271. });
  272. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  273. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  274. }
  275. function setDotBadge(id, active) {
  276. const el = document.getElementById(id);
  277. if (!el) return;
  278. if (active) {
  279. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  280. } else {
  281. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  282. }
  283. }
  284. function updateBadges() {
  285. const bIfaces = document.getElementById('badge-ifaces-count');
  286. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  287. const bVlans = document.getElementById('badge-vlans-count');
  288. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  289. if (state.fwSummary) {
  290. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  291. const badgeFw = document.getElementById('badge-firewall-count');
  292. if (badgeFw) badgeFw.innerText = totalFwRules;
  293. }
  294. if (state.vpnStatus) {
  295. const v = state.vpnStatus;
  296. const bEoIP = document.getElementById('badge-eoip-count');
  297. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  298. const bPPPSess = document.getElementById('badge-ppp-sessions');
  299. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  300. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  301. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  302. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  303. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  304. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  305. }
  306. if (state.dynSummary) {
  307. const d = state.dynSummary;
  308. setDotBadge('badge-bgp-dot', d.bgp_running);
  309. setDotBadge('badge-ospf-dot', d.ospf_running);
  310. const bBgp = document.getElementById('badge-bgp-count');
  311. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  312. const bOspf = document.getElementById('badge-ospf-count');
  313. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  314. const bFilters = document.getElementById('badge-filters-count');
  315. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  316. }
  317. }
  318. // Render Dashboard View
  319. function renderDashboard() {
  320. const matrix = document.getElementById('port-matrix');
  321. matrix.innerHTML = '';
  322. (state.interfaces || []).forEach(iface => {
  323. const isUp = iface.state === 'UP';
  324. const isVlan = iface.is_vlan;
  325. const portCard = document.createElement('div');
  326. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  327. isUp
  328. ? (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')
  329. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  330. }`;
  331. portCard.onclick = () => openIfaceModal(iface.name);
  332. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  333. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  334. portCard.innerHTML = `
  335. <div class="flex items-center justify-between mb-2">
  336. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  337. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  338. </div>
  339. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  340. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  341. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  342. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  343. </div>
  344. `;
  345. matrix.appendChild(portCard);
  346. });
  347. const ifaceTbody = document.getElementById('quick-interfaces-table');
  348. ifaceTbody.innerHTML = '';
  349. (state.interfaces || []).slice(0, 6).forEach(i => {
  350. const isUp = i.state === 'UP';
  351. const tr = document.createElement('tr');
  352. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  353. tr.onclick = () => openIfaceModal(i.name);
  354. tr.innerHTML = `
  355. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  356. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  357. <span>${i.name}</span>
  358. </td>
  359. <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>
  360. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  361. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  362. `;
  363. ifaceTbody.appendChild(tr);
  364. });
  365. const vlanTbody = document.getElementById('quick-vlans-table');
  366. vlanTbody.innerHTML = '';
  367. const vlans = state.vlans || [];
  368. if (vlans.length === 0) {
  369. 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>`;
  370. } else {
  371. vlans.slice(0, 6).forEach(v => {
  372. const tr = document.createElement('tr');
  373. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  374. tr.onclick = () => openIfaceModal(v.name);
  375. tr.innerHTML = `
  376. <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>
  377. <td class="py-2.5 text-white font-bold">${v.name}</td>
  378. <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>
  379. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  380. `;
  381. vlanTbody.appendChild(tr);
  382. });
  383. }
  384. }
  385. // Expand / Collapse Handlers
  386. function toggleExpand(parentName) {
  387. if (state.expandedParents.has(parentName)) {
  388. state.expandedParents.delete(parentName);
  389. } else {
  390. state.expandedParents.add(parentName);
  391. }
  392. renderInterfacesList();
  393. }
  394. function expandAllIfaces(expand) {
  395. if (expand) {
  396. (state.interfaces || []).forEach(i => {
  397. if (!i.is_vlan) state.expandedParents.add(i.name);
  398. });
  399. } else {
  400. state.expandedParents.clear();
  401. }
  402. renderInterfacesList();
  403. }
  404. // Filter and Render Hierarchical Interfaces List
  405. function filterIfaces(filter) {
  406. state.ifaceFilter = filter;
  407. document.querySelectorAll('.filter-btn').forEach(btn => {
  408. 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';
  409. });
  410. const activeBtn = document.getElementById(`filter-${filter}`);
  411. if (activeBtn) {
  412. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  413. }
  414. renderInterfacesList();
  415. }
  416. function renderInterfacesList() {
  417. const tbody = document.getElementById('interfaces-tree-tbody');
  418. const emptyState = document.getElementById('interfaces-empty-state');
  419. const summary = document.getElementById('ifaces-list-summary');
  420. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  421. tbody.innerHTML = '';
  422. const allIfaces = state.interfaces || [];
  423. const allVlans = state.vlans || [];
  424. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  425. const filteredParents = parentIfaces.filter(parent => {
  426. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  427. if (query) {
  428. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  429. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  430. if (!matchParent && !matchVlan) return false;
  431. }
  432. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  433. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  434. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  435. return true;
  436. });
  437. if (summary) {
  438. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  439. }
  440. if (filteredParents.length === 0) {
  441. emptyState?.classList.remove('hidden');
  442. return;
  443. }
  444. emptyState?.classList.add('hidden');
  445. filteredParents.forEach(parent => {
  446. const isUp = parent.state === 'UP';
  447. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  448. const isExpanded = state.expandedParents.has(parent.name);
  449. const parentRow = document.createElement('tr');
  450. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  451. parentRow.innerHTML = `
  452. <td class="py-3 px-3 text-center">
  453. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  454. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  455. <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">
  456. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  457. </svg>
  458. </button>
  459. </td>
  460. <td class="py-3 px-4">
  461. <div class="flex items-center space-x-2.5">
  462. <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">
  463. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  464. </div>
  465. <div>
  466. <div class="flex items-center gap-2">
  467. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  468. ${childVlans.length > 0
  469. ? `<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>`
  470. : `<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>`
  471. }
  472. </div>
  473. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  474. </div>
  475. </div>
  476. </td>
  477. <td class="py-3 px-4 font-sans">
  478. <div class="flex items-center gap-1.5">
  479. <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>
  480. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  481. </div>
  482. </td>
  483. <td class="py-3 px-4">
  484. ${parent.ipv4 && parent.ipv4.length > 0
  485. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  486. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  487. }
  488. </td>
  489. <td class="py-3 px-4 text-slate-400 text-[11px]">
  490. <div>${parent.mac || 'N/A'}</div>
  491. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  492. </td>
  493. <td class="py-3 px-4 text-[11px]">
  494. <div class="flex items-center space-x-2">
  495. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  496. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  497. </div>
  498. </td>
  499. <td class="py-3 px-4 font-sans">
  500. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  501. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  502. 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'
  503. }" title="Click to toggle link status">
  504. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  505. <span>${parent.state}</span>
  506. </button>
  507. </td>
  508. <td class="py-3 px-4 text-right space-x-2 font-sans">
  509. <button onclick="openVlanModal('${parent.name}')"
  510. 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">
  511. + Add VLAN
  512. </button>
  513. <button onclick="openIfaceModal('${parent.name}')"
  514. 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">
  515. Configure
  516. </button>
  517. </td>
  518. `;
  519. tbody.appendChild(parentRow);
  520. if (isExpanded) {
  521. const drawerRow = document.createElement('tr');
  522. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  523. const drawerCell = document.createElement('td');
  524. drawerCell.colSpan = 8;
  525. drawerCell.className = 'p-0';
  526. drawerCell.innerHTML = `
  527. <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">
  528. <div class="flex items-center justify-between mb-3">
  529. <div class="flex items-center space-x-3">
  530. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  531. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  532. </span>
  533. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  534. ${childVlans.length} Attached
  535. </span>
  536. </div>
  537. <button onclick="openVlanModal('${parent.name}')"
  538. 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">
  539. <span>+ Create VLAN on ${parent.name}</span>
  540. </button>
  541. </div>
  542. ${childVlans.length === 0 ? `
  543. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  544. <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>
  545. <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">
  546. <span>+ Create Your First VLAN on ${parent.name}</span>
  547. </button>
  548. </div>
  549. ` : `
  550. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  551. <table class="w-full text-left text-xs font-mono">
  552. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  553. <tr>
  554. <th class="py-2.5 px-4">VLAN ID</th>
  555. <th class="py-2.5 px-4">Interface Device</th>
  556. <th class="py-2.5 px-4">Subnet Gateway</th>
  557. <th class="py-2.5 px-4">Role / Alias</th>
  558. <th class="py-2.5 px-4">MTU</th>
  559. <th class="py-2.5 px-4">Throughput</th>
  560. <th class="py-2.5 px-4">Status</th>
  561. <th class="py-2.5 px-4 text-right">Actions</th>
  562. </tr>
  563. </thead>
  564. <tbody class="divide-y divide-slate-800/70">
  565. ${childVlans.map(v => {
  566. const isVlanUp = v.state === 'UP';
  567. return `
  568. <tr class="hover:bg-slate-800/40 transition">
  569. <td class="py-2.5 px-4">
  570. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  571. VLAN ${v.vlan_id}
  572. </span>
  573. </td>
  574. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  575. <span class="text-cyan-500">└─</span>
  576. <span>${v.name}</span>
  577. </td>
  578. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  579. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  580. </td>
  581. <td class="py-2.5 px-4 font-sans text-slate-300">
  582. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  583. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  584. </td>
  585. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  586. <td class="py-2.5 px-4 text-[11px]">
  587. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  588. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  589. </td>
  590. <td class="py-2.5 px-4 font-sans">
  591. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  592. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  593. 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'
  594. }">
  595. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  596. <span>${v.state}</span>
  597. </button>
  598. </td>
  599. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  600. <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>
  601. <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>
  602. </td>
  603. </tr>
  604. `;
  605. }).join('')}
  606. </tbody>
  607. </table>
  608. </div>
  609. `}
  610. </div>
  611. `;
  612. drawerRow.appendChild(drawerCell);
  613. tbody.appendChild(drawerRow);
  614. }
  615. });
  616. }
  617. // Render VLANs Dedicated View
  618. function renderVlansList() {
  619. const tbody = document.getElementById('vlans-table-body');
  620. if (!tbody) return;
  621. const emptyState = document.getElementById('vlans-empty-state');
  622. const countBadge = document.getElementById('vlans-table-count');
  623. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  624. tbody.innerHTML = '';
  625. const allVlans = state.vlans || [];
  626. if (countBadge) countBadge.innerText = allVlans.length;
  627. const filtered = allVlans.filter(v => {
  628. if (!query) return true;
  629. return v.name.toLowerCase().includes(query) ||
  630. String(v.vlan_id).includes(query) ||
  631. (v.description || '').toLowerCase().includes(query) ||
  632. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  633. });
  634. if (allVlans.length === 0) {
  635. emptyState.classList.remove('hidden');
  636. return;
  637. }
  638. emptyState.classList.add('hidden');
  639. filtered.forEach(v => {
  640. const isUp = v.state === 'UP';
  641. const tr = document.createElement('tr');
  642. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  643. tr.innerHTML = `
  644. <td class="py-3 px-4">
  645. <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">
  646. VLAN ${v.vlan_id}
  647. </span>
  648. </td>
  649. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  650. <td class="py-3 px-4 text-slate-300">
  651. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  652. </td>
  653. <td class="py-3 px-4 text-emerald-400 font-medium">
  654. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  655. </td>
  656. <td class="py-3 px-4 text-slate-300 font-sans">
  657. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  658. </td>
  659. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  660. <td class="py-3 px-4 font-sans">
  661. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  662. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  663. 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'
  664. }">
  665. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  666. <span>${v.state}</span>
  667. </button>
  668. </td>
  669. <td class="py-3 px-4 text-right space-x-2 font-sans">
  670. <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>
  671. <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>
  672. </td>
  673. `;
  674. tbody.appendChild(tr);
  675. });
  676. }
  677. // Toggle interface UP / DOWN
  678. async function toggleInterfaceState(name, newState) {
  679. try {
  680. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  681. method: 'POST',
  682. headers: { 'Content-Type': 'application/json' },
  683. body: JSON.stringify({ state: newState })
  684. });
  685. const data = await res.json();
  686. if (res.ok) {
  687. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  688. fetchData(false);
  689. } else {
  690. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  691. }
  692. } catch (err) {
  693. showToast('Error', err.message, 'error');
  694. }
  695. }
  696. // ---------------- MikroTik Flag & Utilities ----------------
  697. function renderMikroTikFlag(running, disabled) {
  698. if (running) {
  699. 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>`;
  700. }
  701. if (disabled) {
  702. 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>`;
  703. }
  704. 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>`;
  705. }
  706. function copyToClipboard(text, label = 'Text') {
  707. navigator.clipboard.writeText(text).then(() => {
  708. showToast('Copied', `${label} copied to clipboard`, 'success');
  709. }).catch(() => {
  710. prompt('Copy value:', text);
  711. });
  712. }
  713. // ======================== PPPoE Multi-Instance ========================
  714. async function loadPPPoE(populateInputs = true) {
  715. try {
  716. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  717. const list = await res.json();
  718. state.pppoeList = Array.isArray(list) ? list : [];
  719. const badge = document.getElementById('pppoe-count-badge');
  720. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  721. const tbody = document.getElementById('pppoe-table-body');
  722. const empty = document.getElementById('pppoe-empty');
  723. if (!tbody) return;
  724. tbody.innerHTML = '';
  725. if (state.pppoeList.length === 0) {
  726. if (empty) empty.classList.remove('hidden');
  727. } else {
  728. if (empty) empty.classList.add('hidden');
  729. state.pppoeList.forEach(inst => {
  730. const tr = document.createElement('tr');
  731. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  732. tr.innerHTML = `
  733. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  734. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  735. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  736. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  737. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  738. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  739. <td class="py-2.5 px-3 text-center">
  740. <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'}">
  741. ${inst.default_route ? 'Yes' : 'No'}
  742. </span>
  743. </td>
  744. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  745. ${inst.running ? `
  746. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  747. ` : `
  748. <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>
  749. `}
  750. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  751. ${inst.disabled ? 'Enable' : 'Disable'}
  752. </button>
  753. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  754. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  755. </td>
  756. `;
  757. tbody.appendChild(tr);
  758. });
  759. }
  760. } catch (err) {
  761. console.error('Failed to load PPPoE:', err);
  762. }
  763. }
  764. function openAddPPPoEModal() {
  765. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  766. document.getElementById('pppoe-modal-edit-orig').value = '';
  767. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  768. document.getElementById('pppoe-modal-name').readOnly = false;
  769. document.getElementById('pppoe-modal-user').value = '';
  770. document.getElementById('pppoe-modal-pass').value = '';
  771. document.getElementById('pppoe-modal-service').value = '';
  772. document.getElementById('pppoe-modal-mtu').value = '1492';
  773. document.getElementById('pppoe-modal-defroute').checked = true;
  774. document.getElementById('pppoe-modal-reconnect').checked = true;
  775. document.getElementById('pppoe-modal-disabled').checked = false;
  776. // Populate interfaces
  777. const sel = document.getElementById('pppoe-modal-iface');
  778. sel.innerHTML = '';
  779. (state.interfaces || []).forEach(i => {
  780. if (i.name === 'lo') return;
  781. const opt = document.createElement('option');
  782. opt.value = i.name;
  783. opt.innerText = `${i.name} (${i.role || i.type})`;
  784. sel.appendChild(opt);
  785. });
  786. document.getElementById('pppoe-modal').classList.remove('hidden');
  787. }
  788. function openEditPPPoEModal(name) {
  789. const inst = (state.pppoeList || []).find(i => i.name === name);
  790. if (!inst) return;
  791. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  792. document.getElementById('pppoe-modal-edit-orig').value = name;
  793. document.getElementById('pppoe-modal-name').value = inst.name;
  794. document.getElementById('pppoe-modal-name').readOnly = true;
  795. document.getElementById('pppoe-modal-user').value = inst.username || '';
  796. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  797. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  798. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  799. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  800. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  801. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  802. const sel = document.getElementById('pppoe-modal-iface');
  803. sel.innerHTML = '';
  804. (state.interfaces || []).forEach(i => {
  805. if (i.name === 'lo') return;
  806. const opt = document.createElement('option');
  807. opt.value = i.name;
  808. opt.innerText = `${i.name} (${i.role || i.type})`;
  809. if (i.name === inst.interface) opt.selected = true;
  810. sel.appendChild(opt);
  811. });
  812. document.getElementById('pppoe-modal').classList.remove('hidden');
  813. }
  814. function closePPPoEModal() {
  815. document.getElementById('pppoe-modal').classList.add('hidden');
  816. }
  817. async function submitSavePPPoE(e) {
  818. e.preventDefault();
  819. const name = document.getElementById('pppoe-modal-name').value.trim();
  820. const iface = document.getElementById('pppoe-modal-iface').value;
  821. const user = document.getElementById('pppoe-modal-user').value.trim();
  822. const pass = document.getElementById('pppoe-modal-pass').value;
  823. const service = document.getElementById('pppoe-modal-service').value.trim();
  824. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  825. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  826. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  827. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  828. try {
  829. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  830. method: 'POST',
  831. headers: { 'Content-Type': 'application/json' },
  832. body: JSON.stringify({
  833. name,
  834. interface: iface,
  835. username: user,
  836. password: pass,
  837. service_name: service,
  838. mtu,
  839. default_route: defRoute,
  840. auto_reconnect: reconnect,
  841. disabled
  842. })
  843. });
  844. if (res.ok) {
  845. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  846. closePPPoEModal();
  847. loadPPPoE(false);
  848. fetchData(false);
  849. } else {
  850. const err = await res.json();
  851. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  852. }
  853. } catch (err) {
  854. showToast('Error', err.message, 'error');
  855. }
  856. }
  857. async function connectPPPoEInstance(name) {
  858. try {
  859. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  860. if (res.ok) {
  861. showToast('Connecting', `Dialing ${name}...`, 'info');
  862. setTimeout(() => loadPPPoE(false), 2000);
  863. }
  864. } catch (err) {
  865. showToast('Error', err.message, 'error');
  866. }
  867. }
  868. async function disconnectPPPoEInstance(name) {
  869. try {
  870. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  871. if (res.ok) {
  872. showToast('Disconnected', `${name} session terminated`, 'info');
  873. setTimeout(() => loadPPPoE(false), 1000);
  874. }
  875. } catch (err) {
  876. showToast('Error', err.message, 'error');
  877. }
  878. }
  879. async function togglePPPoEState(name, enable) {
  880. try {
  881. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  882. method: 'POST',
  883. headers: { 'Content-Type': 'application/json' },
  884. body: JSON.stringify({ enabled: enable })
  885. });
  886. if (res.ok) {
  887. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  888. loadPPPoE(false);
  889. }
  890. } catch (err) {
  891. showToast('Error', err.message, 'error');
  892. }
  893. }
  894. async function deletePPPoEInstance(name) {
  895. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  896. try {
  897. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  898. if (res.ok) {
  899. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  900. loadPPPoE(false);
  901. fetchData(false);
  902. }
  903. } catch (err) {
  904. showToast('Error', err.message, 'error');
  905. }
  906. }
  907. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  908. state.wgSubTab = 'ifaces';
  909. function switchWGSubTab(tab) {
  910. state.wgSubTab = tab;
  911. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  912. const peersPanel = document.getElementById('wg-subtab-peers');
  913. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  914. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  915. if (tab === 'ifaces') {
  916. ifacesPanel?.classList.remove('hidden');
  917. peersPanel?.classList.add('hidden');
  918. 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';
  919. 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';
  920. } else {
  921. ifacesPanel?.classList.add('hidden');
  922. peersPanel?.classList.remove('hidden');
  923. 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';
  924. 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';
  925. renderWGPeers();
  926. }
  927. }
  928. async function loadWireGuard(populateInputs = true) {
  929. try {
  930. const [ifacesRes, peersRes] = await Promise.all([
  931. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  932. fetch(`${API_BASE}/vpn/wireguard/peers`)
  933. ]);
  934. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  935. const peers = peersRes.ok ? await peersRes.json() : [];
  936. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  937. state.wgPeers = Array.isArray(peers) ? peers : [];
  938. // Badges
  939. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  940. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  941. const peersCountBadge = document.getElementById('wg-peers-count');
  942. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  943. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  944. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  945. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  946. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  947. // Render Interfaces
  948. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  949. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  950. if (ifacesTbody) {
  951. ifacesTbody.innerHTML = '';
  952. if (state.wgInterfaces.length === 0) {
  953. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  954. } else {
  955. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  956. state.wgInterfaces.forEach(iface => {
  957. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  958. const tr = document.createElement('tr');
  959. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  960. tr.innerHTML = `
  961. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  962. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  963. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  964. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  965. <td class="py-2.5 px-3 text-slate-300 font-mono">
  966. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  967. ${(iface.public_key || '').substring(0, 10)}... 📋
  968. </span>
  969. </td>
  970. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  971. <td class="py-2.5 px-3 text-center">
  972. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  973. </td>
  974. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  975. ${iface.running ? `
  976. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  977. ` : `
  978. <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>
  979. `}
  980. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  981. ${iface.disabled ? 'Enable' : 'Disable'}
  982. </button>
  983. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  984. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  985. </td>
  986. `;
  987. ifacesTbody.appendChild(tr);
  988. });
  989. }
  990. }
  991. // Populate filter dropdown in peers tab
  992. const filterSel = document.getElementById('wg-peers-filter-iface');
  993. if (filterSel) {
  994. const currentVal = filterSel.value;
  995. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  996. state.wgInterfaces.forEach(i => {
  997. const opt = document.createElement('option');
  998. opt.value = i.name;
  999. opt.innerText = i.name;
  1000. if (i.name === currentVal) opt.selected = true;
  1001. filterSel.appendChild(opt);
  1002. });
  1003. }
  1004. renderWGPeers();
  1005. } catch (err) {
  1006. console.error('Failed to load WireGuard:', err);
  1007. }
  1008. }
  1009. function renderWGPeers() {
  1010. const filterSel = document.getElementById('wg-peers-filter-iface');
  1011. const selectedIface = filterSel ? filterSel.value : '';
  1012. const tbody = document.getElementById('wg-peers-table-body');
  1013. const empty = document.getElementById('wg-peers-empty');
  1014. if (!tbody) return;
  1015. tbody.innerHTML = '';
  1016. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1017. if (filtered.length === 0) {
  1018. if (empty) empty.classList.remove('hidden');
  1019. } else {
  1020. if (empty) empty.classList.add('hidden');
  1021. filtered.forEach(p => {
  1022. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1023. const tr = document.createElement('tr');
  1024. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1025. tr.innerHTML = `
  1026. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1027. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  1028. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  1029. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1030. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1031. ${p.public_key.substring(0, 10)}... 📋
  1032. </span>
  1033. </td>
  1034. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1035. <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>
  1036. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1037. <td class="py-2.5 px-3 font-mono text-[11px]">
  1038. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1039. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1040. </td>
  1041. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1042. <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>
  1043. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1044. </td>
  1045. `;
  1046. tbody.appendChild(tr);
  1047. });
  1048. }
  1049. }
  1050. function openAddWGInterfaceModal() {
  1051. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1052. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1053. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1054. document.getElementById('wg-iface-modal-name').readOnly = false;
  1055. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1056. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1057. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1058. document.getElementById('wg-iface-modal-pubkey').value = '';
  1059. document.getElementById('wg-iface-modal-privkey').value = '';
  1060. document.getElementById('wg-iface-modal-disabled').checked = false;
  1061. generateWGInterfaceKeys();
  1062. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1063. }
  1064. function openEditWGInterfaceModal(name) {
  1065. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1066. if (!iface) return;
  1067. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1068. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1069. document.getElementById('wg-iface-modal-name').value = iface.name;
  1070. document.getElementById('wg-iface-modal-name').readOnly = true;
  1071. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1072. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1073. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1074. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1075. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1076. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1077. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1078. }
  1079. function closeAddWGInterfaceModal() {
  1080. document.getElementById('wg-iface-modal').classList.add('hidden');
  1081. }
  1082. async function generateWGInterfaceKeys() {
  1083. try {
  1084. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1085. const keys = await res.json();
  1086. if (res.ok) {
  1087. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1088. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1089. }
  1090. } catch (err) {
  1091. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1092. }
  1093. }
  1094. async function submitSaveWGInterface(e) {
  1095. e.preventDefault();
  1096. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1097. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1098. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1099. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1100. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1101. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1102. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1103. try {
  1104. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1105. method: 'POST',
  1106. headers: { 'Content-Type': 'application/json' },
  1107. body: JSON.stringify({
  1108. name,
  1109. listen_port: port,
  1110. address: addr,
  1111. mtu,
  1112. public_key: pub,
  1113. private_key: priv,
  1114. disabled
  1115. })
  1116. });
  1117. if (res.ok) {
  1118. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1119. closeAddWGInterfaceModal();
  1120. loadWireGuard(false);
  1121. fetchData(false);
  1122. }
  1123. } catch (err) {
  1124. showToast('Error', err.message, 'error');
  1125. }
  1126. }
  1127. async function startWGInterface(name) {
  1128. try {
  1129. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1130. if (res.ok) {
  1131. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1132. loadWireGuard(false);
  1133. fetchData(false);
  1134. }
  1135. } catch (err) {
  1136. showToast('Error', err.message, 'error');
  1137. }
  1138. }
  1139. async function stopWGInterface(name) {
  1140. try {
  1141. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1142. if (res.ok) {
  1143. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1144. loadWireGuard(false);
  1145. fetchData(false);
  1146. }
  1147. } catch (err) {
  1148. showToast('Error', err.message, 'error');
  1149. }
  1150. }
  1151. async function toggleWGInterfaceState(name, enable) {
  1152. try {
  1153. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1154. method: 'POST',
  1155. headers: { 'Content-Type': 'application/json' },
  1156. body: JSON.stringify({ enabled: enable })
  1157. });
  1158. if (res.ok) {
  1159. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1160. loadWireGuard(false);
  1161. }
  1162. } catch (err) {
  1163. showToast('Error', err.message, 'error');
  1164. }
  1165. }
  1166. async function deleteWGInterface(name) {
  1167. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1168. try {
  1169. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1170. if (res.ok) {
  1171. showToast('Deleted', `Interface ${name} removed`, 'success');
  1172. loadWireGuard(false);
  1173. fetchData(false);
  1174. }
  1175. } catch (err) {
  1176. showToast('Error', err.message, 'error');
  1177. }
  1178. }
  1179. function openAddWGPeerModal() {
  1180. const sel = document.getElementById('wg-peer-modal-iface');
  1181. sel.innerHTML = '';
  1182. (state.wgInterfaces || []).forEach(i => {
  1183. const opt = document.createElement('option');
  1184. opt.value = i.name;
  1185. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1186. sel.appendChild(opt);
  1187. });
  1188. if ((state.wgInterfaces || []).length === 0) {
  1189. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1190. openAddWGInterfaceModal();
  1191. return;
  1192. }
  1193. document.getElementById('wg-peer-modal-name').value = '';
  1194. document.getElementById('wg-peer-modal-pubkey').value = '';
  1195. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1196. document.getElementById('wg-peer-modal-endpoint').value = '';
  1197. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1198. document.getElementById('wg-peer-modal-preshared').value = '';
  1199. document.getElementById('wg-peer-modal-disabled').checked = false;
  1200. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1201. }
  1202. function closeAddWGPeerModal() {
  1203. document.getElementById('wg-peer-modal').classList.add('hidden');
  1204. }
  1205. async function submitSaveWGPeer(e) {
  1206. e.preventDefault();
  1207. const iface = document.getElementById('wg-peer-modal-iface').value;
  1208. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1209. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1210. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1211. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1212. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1213. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1214. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1215. let epAddr = ep;
  1216. let epPort = 0;
  1217. if (ep.includes(':')) {
  1218. const parts = ep.split(':');
  1219. epAddr = parts[0];
  1220. epPort = parseInt(parts[1], 10) || 0;
  1221. }
  1222. try {
  1223. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1224. method: 'POST',
  1225. headers: { 'Content-Type': 'application/json' },
  1226. body: JSON.stringify({
  1227. interface: iface,
  1228. name,
  1229. public_key: pub,
  1230. allowed_ips: allowed,
  1231. endpoint_address: epAddr,
  1232. endpoint_port: epPort,
  1233. persistent_keepalive: keepalive,
  1234. preshared_key: psk,
  1235. disabled
  1236. })
  1237. });
  1238. if (res.ok) {
  1239. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1240. closeAddWGPeerModal();
  1241. loadWireGuard(false);
  1242. }
  1243. } catch (err) {
  1244. showToast('Error', err.message, 'error');
  1245. }
  1246. }
  1247. async function deleteWGPeer(iface, pubkey) {
  1248. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1249. try {
  1250. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1251. method: 'DELETE'
  1252. });
  1253. if (res.ok) {
  1254. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1255. loadWireGuard(false);
  1256. }
  1257. } catch (err) {
  1258. showToast('Error', err.message, 'error');
  1259. }
  1260. }
  1261. // ======================== IPSec Multi-Tunnel ========================
  1262. async function loadIPSec(populateInputs = true) {
  1263. try {
  1264. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1265. const list = await res.json();
  1266. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1267. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1268. const badge = document.getElementById('ipsec-sas-badge');
  1269. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1270. const tbody = document.getElementById('ipsec-table-body');
  1271. const empty = document.getElementById('ipsec-empty');
  1272. if (!tbody) return;
  1273. tbody.innerHTML = '';
  1274. if (state.ipsecTunnels.length === 0) {
  1275. if (empty) empty.classList.remove('hidden');
  1276. } else {
  1277. if (empty) empty.classList.add('hidden');
  1278. state.ipsecTunnels.forEach(c => {
  1279. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1280. const tr = document.createElement('tr');
  1281. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1282. tr.innerHTML = `
  1283. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1284. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1285. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1286. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1287. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1288. <td class="py-2.5 px-4 font-sans">
  1289. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1290. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1291. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1292. </td>
  1293. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1294. ${isEstablished ? `
  1295. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1296. ` : `
  1297. <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>
  1298. `}
  1299. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1300. ${c.disabled ? 'Enable' : 'Disable'}
  1301. </button>
  1302. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1303. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1304. </td>
  1305. `;
  1306. tbody.appendChild(tr);
  1307. });
  1308. }
  1309. } catch (err) {
  1310. console.error('Failed to load IPSec:', err);
  1311. }
  1312. }
  1313. function openAddIPSecModal() {
  1314. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1315. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1316. document.getElementById('ipsec-modal-name').readOnly = false;
  1317. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1318. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1319. document.getElementById('ipsec-modal-remotegw').value = '';
  1320. document.getElementById('ipsec-modal-psk').value = '';
  1321. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1322. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1323. document.getElementById('ipsec-modal-autostart').checked = true;
  1324. document.getElementById('ipsec-modal-disabled').checked = false;
  1325. document.getElementById('ipsec-modal').classList.remove('hidden');
  1326. }
  1327. function openEditIPSecModal(name) {
  1328. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1329. if (!conn) return;
  1330. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1331. document.getElementById('ipsec-modal-name').value = conn.name;
  1332. document.getElementById('ipsec-modal-name').readOnly = true;
  1333. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1334. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1335. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1336. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1337. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1338. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1339. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1340. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1341. document.getElementById('ipsec-modal').classList.remove('hidden');
  1342. }
  1343. function closeAddIPSecModal() {
  1344. document.getElementById('ipsec-modal').classList.add('hidden');
  1345. }
  1346. async function submitSaveIPSec(e) {
  1347. e.preventDefault();
  1348. const name = document.getElementById('ipsec-modal-name').value.trim();
  1349. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1350. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1351. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1352. const psk = document.getElementById('ipsec-modal-psk').value;
  1353. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1354. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1355. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1356. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1357. try {
  1358. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1359. method: 'POST',
  1360. headers: { 'Content-Type': 'application/json' },
  1361. body: JSON.stringify({
  1362. name,
  1363. local_addrs: '%any',
  1364. remote_addrs: remotegw,
  1365. local_subnet: localts,
  1366. remote_subnet: remotets,
  1367. preshared_key: psk,
  1368. ike_proposals: ike,
  1369. esp_proposals: esp,
  1370. auto_start: autostart,
  1371. disabled
  1372. })
  1373. });
  1374. if (res.ok) {
  1375. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1376. closeAddIPSecModal();
  1377. loadIPSec(false);
  1378. fetchData(false);
  1379. }
  1380. } catch (err) {
  1381. showToast('Error', err.message, 'error');
  1382. }
  1383. }
  1384. async function startIPSecTunnel(name) {
  1385. try {
  1386. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1387. if (res.ok) {
  1388. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1389. setTimeout(() => loadIPSec(false), 2000);
  1390. }
  1391. } catch (err) {
  1392. showToast('Error', err.message, 'error');
  1393. }
  1394. }
  1395. async function stopIPSecTunnel(name) {
  1396. try {
  1397. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1398. if (res.ok) {
  1399. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1400. loadIPSec(false);
  1401. }
  1402. } catch (err) {
  1403. showToast('Error', err.message, 'error');
  1404. }
  1405. }
  1406. async function toggleIPSecState(name, enable) {
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1409. method: 'POST',
  1410. headers: { 'Content-Type': 'application/json' },
  1411. body: JSON.stringify({ enabled: enable })
  1412. });
  1413. if (res.ok) {
  1414. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1415. loadIPSec(false);
  1416. }
  1417. } catch (err) {
  1418. showToast('Error', err.message, 'error');
  1419. }
  1420. }
  1421. async function deleteIPSecConn(name) {
  1422. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1423. try {
  1424. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1425. if (res.ok) {
  1426. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1427. loadIPSec(false);
  1428. fetchData(false);
  1429. }
  1430. } catch (err) {
  1431. showToast('Error', err.message, 'error');
  1432. }
  1433. }
  1434. // ======================== L2TP Multi-Instance ========================
  1435. async function loadL2TP(populateInputs = true) {
  1436. try {
  1437. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1438. const list = await res.json();
  1439. state.l2tpList = Array.isArray(list) ? list : [];
  1440. const badge = document.getElementById('l2tp-count-badge');
  1441. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1442. const tbody = document.getElementById('l2tp-table-body');
  1443. const empty = document.getElementById('l2tp-empty');
  1444. if (!tbody) return;
  1445. tbody.innerHTML = '';
  1446. if (state.l2tpList.length === 0) {
  1447. if (empty) empty.classList.remove('hidden');
  1448. } else {
  1449. if (empty) empty.classList.add('hidden');
  1450. state.l2tpList.forEach(inst => {
  1451. const tr = document.createElement('tr');
  1452. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1453. tr.innerHTML = `
  1454. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1455. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1456. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1457. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1458. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1459. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1460. <td class="py-2.5 px-3 text-center">
  1461. <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'}">
  1462. ${inst.default_route ? 'Yes' : 'No'}
  1463. </span>
  1464. </td>
  1465. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1466. ${inst.running ? `
  1467. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1468. ` : `
  1469. <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>
  1470. `}
  1471. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1472. ${inst.disabled ? 'Enable' : 'Disable'}
  1473. </button>
  1474. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1475. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1476. </td>
  1477. `;
  1478. tbody.appendChild(tr);
  1479. });
  1480. }
  1481. } catch (err) {
  1482. console.error('Failed to load L2TP:', err);
  1483. }
  1484. }
  1485. function openAddL2TPModal() {
  1486. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1487. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1488. document.getElementById('l2tp-modal-name').readOnly = false;
  1489. document.getElementById('l2tp-modal-server').value = '';
  1490. document.getElementById('l2tp-modal-user').value = '';
  1491. document.getElementById('l2tp-modal-pass').value = '';
  1492. document.getElementById('l2tp-modal-ipsec').value = '';
  1493. document.getElementById('l2tp-modal-defroute').checked = true;
  1494. document.getElementById('l2tp-modal-disabled').checked = false;
  1495. document.getElementById('l2tp-modal').classList.remove('hidden');
  1496. }
  1497. function openEditL2TPModal(name) {
  1498. const inst = (state.l2tpList || []).find(i => i.name === name);
  1499. if (!inst) return;
  1500. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1501. document.getElementById('l2tp-modal-name').value = inst.name;
  1502. document.getElementById('l2tp-modal-name').readOnly = true;
  1503. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1504. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1505. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1506. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1507. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1508. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1509. document.getElementById('l2tp-modal').classList.remove('hidden');
  1510. }
  1511. function closeL2TPModal() {
  1512. document.getElementById('l2tp-modal').classList.add('hidden');
  1513. }
  1514. async function submitSaveL2TP(e) {
  1515. e.preventDefault();
  1516. const name = document.getElementById('l2tp-modal-name').value.trim();
  1517. const server = document.getElementById('l2tp-modal-server').value.trim();
  1518. const user = document.getElementById('l2tp-modal-user').value.trim();
  1519. const pass = document.getElementById('l2tp-modal-pass').value;
  1520. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1521. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1522. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1523. try {
  1524. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1525. method: 'POST',
  1526. headers: { 'Content-Type': 'application/json' },
  1527. body: JSON.stringify({
  1528. name,
  1529. connect_to: server,
  1530. username: user,
  1531. password: pass,
  1532. ipsec_secret: ipsec,
  1533. default_route: defRoute,
  1534. disabled
  1535. })
  1536. });
  1537. if (res.ok) {
  1538. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1539. closeL2TPModal();
  1540. loadL2TP(false);
  1541. fetchData(false);
  1542. }
  1543. } catch (err) {
  1544. showToast('Error', err.message, 'error');
  1545. }
  1546. }
  1547. async function connectL2TPInstance(name) {
  1548. try {
  1549. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1550. if (res.ok) {
  1551. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1552. setTimeout(() => loadL2TP(false), 2000);
  1553. }
  1554. } catch (err) {
  1555. showToast('Error', err.message, 'error');
  1556. }
  1557. }
  1558. async function disconnectL2TPInstance(name) {
  1559. try {
  1560. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1561. if (res.ok) {
  1562. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1563. loadL2TP(false);
  1564. }
  1565. } catch (err) {
  1566. showToast('Error', err.message, 'error');
  1567. }
  1568. }
  1569. async function toggleL2TPState(name, enable) {
  1570. try {
  1571. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1572. method: 'POST',
  1573. headers: { 'Content-Type': 'application/json' },
  1574. body: JSON.stringify({ enabled: enable })
  1575. });
  1576. if (res.ok) {
  1577. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1578. loadL2TP(false);
  1579. }
  1580. } catch (err) {
  1581. showToast('Error', err.message, 'error');
  1582. }
  1583. }
  1584. async function deleteL2TPInstance(name) {
  1585. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1586. try {
  1587. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1588. if (res.ok) {
  1589. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1590. loadL2TP(false);
  1591. fetchData(false);
  1592. }
  1593. } catch (err) {
  1594. showToast('Error', err.message, 'error');
  1595. }
  1596. }
  1597. // ======================== PPTP Multi-Instance ========================
  1598. async function loadPPTP(populateInputs = true) {
  1599. try {
  1600. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1601. const list = await res.json();
  1602. state.pptpList = Array.isArray(list) ? list : [];
  1603. const badge = document.getElementById('pptp-count-badge');
  1604. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1605. const tbody = document.getElementById('pptp-table-body');
  1606. const empty = document.getElementById('pptp-empty');
  1607. if (!tbody) return;
  1608. tbody.innerHTML = '';
  1609. if (state.pptpList.length === 0) {
  1610. if (empty) empty.classList.remove('hidden');
  1611. } else {
  1612. if (empty) empty.classList.add('hidden');
  1613. state.pptpList.forEach(inst => {
  1614. const tr = document.createElement('tr');
  1615. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1616. tr.innerHTML = `
  1617. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1618. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1619. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1620. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1621. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1622. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1623. <td class="py-2.5 px-3 text-center">
  1624. <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'}">
  1625. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1626. </span>
  1627. </td>
  1628. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1629. ${inst.running ? `
  1630. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1631. ` : `
  1632. <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>
  1633. `}
  1634. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1635. ${inst.disabled ? 'Enable' : 'Disable'}
  1636. </button>
  1637. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1638. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1639. </td>
  1640. `;
  1641. tbody.appendChild(tr);
  1642. });
  1643. }
  1644. } catch (err) {
  1645. console.error('Failed to load PPTP:', err);
  1646. }
  1647. }
  1648. function openAddPPTPModal() {
  1649. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1650. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1651. document.getElementById('pptp-modal-name').readOnly = false;
  1652. document.getElementById('pptp-modal-server').value = '';
  1653. document.getElementById('pptp-modal-user').value = '';
  1654. document.getElementById('pptp-modal-pass').value = '';
  1655. document.getElementById('pptp-modal-mppe').checked = true;
  1656. document.getElementById('pptp-modal-defroute').checked = true;
  1657. document.getElementById('pptp-modal-disabled').checked = false;
  1658. document.getElementById('pptp-modal').classList.remove('hidden');
  1659. }
  1660. function openEditPPTPModal(name) {
  1661. const inst = (state.pptpList || []).find(i => i.name === name);
  1662. if (!inst) return;
  1663. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1664. document.getElementById('pptp-modal-name').value = inst.name;
  1665. document.getElementById('pptp-modal-name').readOnly = true;
  1666. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1667. document.getElementById('pptp-modal-user').value = inst.username || '';
  1668. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1669. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1670. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1671. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1672. document.getElementById('pptp-modal').classList.remove('hidden');
  1673. }
  1674. function closePPTPModal() {
  1675. document.getElementById('pptp-modal').classList.add('hidden');
  1676. }
  1677. async function submitSavePPTP(e) {
  1678. e.preventDefault();
  1679. const name = document.getElementById('pptp-modal-name').value.trim();
  1680. const server = document.getElementById('pptp-modal-server').value.trim();
  1681. const user = document.getElementById('pptp-modal-user').value.trim();
  1682. const pass = document.getElementById('pptp-modal-pass').value;
  1683. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1684. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1685. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1686. try {
  1687. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1688. method: 'POST',
  1689. headers: { 'Content-Type': 'application/json' },
  1690. body: JSON.stringify({
  1691. name,
  1692. connect_to: server,
  1693. username: user,
  1694. password: pass,
  1695. require_mppe: mppe,
  1696. default_route: defRoute,
  1697. auto_reconnect: true,
  1698. disabled
  1699. })
  1700. });
  1701. if (res.ok) {
  1702. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1703. closePPTPModal();
  1704. loadPPTP(false);
  1705. fetchData(false);
  1706. }
  1707. } catch (err) {
  1708. showToast('Error', err.message, 'error');
  1709. }
  1710. }
  1711. async function connectPPTPInstance(name) {
  1712. try {
  1713. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1714. if (res.ok) {
  1715. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1716. setTimeout(() => loadPPTP(false), 2000);
  1717. }
  1718. } catch (err) {
  1719. showToast('Error', err.message, 'error');
  1720. }
  1721. }
  1722. async function disconnectPPTPInstance(name) {
  1723. try {
  1724. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1725. if (res.ok) {
  1726. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1727. loadPPTP(false);
  1728. }
  1729. } catch (err) {
  1730. showToast('Error', err.message, 'error');
  1731. }
  1732. }
  1733. async function togglePPTPState(name, enable) {
  1734. try {
  1735. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1736. method: 'POST',
  1737. headers: { 'Content-Type': 'application/json' },
  1738. body: JSON.stringify({ enabled: enable })
  1739. });
  1740. if (res.ok) {
  1741. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1742. loadPPTP(false);
  1743. }
  1744. } catch (err) {
  1745. showToast('Error', err.message, 'error');
  1746. }
  1747. }
  1748. async function deletePPTPInstance(name) {
  1749. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1750. try {
  1751. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1752. if (res.ok) {
  1753. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1754. loadPPTP(false);
  1755. fetchData(false);
  1756. }
  1757. } catch (err) {
  1758. showToast('Error', err.message, 'error');
  1759. }
  1760. }
  1761. // ---------------- Modal & Helper Functions ----------------
  1762. function openVlanModal(defaultParent = '') {
  1763. const select = document.getElementById('vlan-parent');
  1764. select.innerHTML = '';
  1765. const allIfaces = state.interfaces || [];
  1766. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1767. if (eligible.length === 0) {
  1768. allIfaces.forEach(i => eligible.push(i));
  1769. }
  1770. eligible.forEach(i => {
  1771. const opt = document.createElement('option');
  1772. opt.value = i.name;
  1773. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1774. if (i.name === defaultParent) opt.selected = true;
  1775. select.appendChild(opt);
  1776. });
  1777. document.getElementById('vlan-id').value = '';
  1778. document.getElementById('vlan-name').value = '';
  1779. document.getElementById('vlan-ip').value = '';
  1780. document.getElementById('vlan-desc').value = '';
  1781. autoSuggestVlanName();
  1782. document.getElementById('vlan-modal').classList.remove('hidden');
  1783. }
  1784. function closeVlanModal() {
  1785. document.getElementById('vlan-modal').classList.add('hidden');
  1786. }
  1787. function autoSuggestVlanName() {
  1788. const parent = document.getElementById('vlan-parent').value;
  1789. const id = document.getElementById('vlan-id').value;
  1790. const nameInput = document.getElementById('vlan-name');
  1791. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1792. }
  1793. function setSubnetPreset(cidr) {
  1794. const ipInput = document.getElementById('vlan-ip');
  1795. const id = document.getElementById('vlan-id').value || '10';
  1796. ipInput.value = `192.168.${id}.1${cidr}`;
  1797. }
  1798. async function submitCreateVlan(e) {
  1799. e.preventDefault();
  1800. const btn = document.getElementById('vlan-submit-btn');
  1801. btn.disabled = true;
  1802. btn.innerText = 'Creating...';
  1803. const parent = document.getElementById('vlan-parent').value;
  1804. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1805. const name = document.getElementById('vlan-name').value.trim();
  1806. const ip = document.getElementById('vlan-ip').value.trim();
  1807. const role = document.getElementById('vlan-role').value;
  1808. const desc = document.getElementById('vlan-desc').value.trim();
  1809. try {
  1810. const res = await fetch(`${API_BASE}/vlans`, {
  1811. method: 'POST',
  1812. headers: { 'Content-Type': 'application/json' },
  1813. body: JSON.stringify({
  1814. parent_name: parent,
  1815. vlan_id: id,
  1816. name: name,
  1817. ip_address: ip,
  1818. role: role,
  1819. description: desc,
  1820. mtu: 1500,
  1821. auto_up: true
  1822. })
  1823. });
  1824. const data = await res.json();
  1825. if (res.ok) {
  1826. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1827. state.expandedParents.add(parent);
  1828. closeVlanModal();
  1829. await fetchData(true);
  1830. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1831. } else {
  1832. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1833. }
  1834. } catch (err) {
  1835. showToast('Error', err.message, 'error');
  1836. } finally {
  1837. btn.disabled = false;
  1838. btn.innerText = 'Create VLAN';
  1839. }
  1840. }
  1841. async function confirmDeleteVlan(name) {
  1842. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1843. try {
  1844. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1845. if (res.ok) {
  1846. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1847. closeIfaceModal();
  1848. fetchData(true);
  1849. }
  1850. } catch (err) {
  1851. showToast('Error', err.message, 'error');
  1852. }
  1853. }
  1854. function openIfaceModal(name) {
  1855. const iface = (state.interfaces || []).find(i => i.name === name);
  1856. if (!iface) return;
  1857. state.currentModalIface = iface.name;
  1858. document.getElementById('modal-iface-name').innerText = iface.name;
  1859. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1860. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1861. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1862. document.getElementById('modal-iface-desc').value = iface.description || '';
  1863. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1864. if (iface.is_vlan) {
  1865. delBtn.classList.remove('hidden');
  1866. } else {
  1867. delBtn.classList.add('hidden');
  1868. }
  1869. renderModalIPs(iface);
  1870. document.getElementById('iface-modal').classList.remove('hidden');
  1871. }
  1872. function renderModalIPs(iface) {
  1873. const container = document.getElementById('modal-ip-list');
  1874. container.innerHTML = '';
  1875. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1876. if (addrs.length === 0) {
  1877. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1878. return;
  1879. }
  1880. addrs.forEach(addr => {
  1881. const row = document.createElement('div');
  1882. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1883. row.innerHTML = `
  1884. <span class="text-white">${addr}</span>
  1885. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1886. `;
  1887. container.appendChild(row);
  1888. });
  1889. }
  1890. function closeIfaceModal() {
  1891. document.getElementById('iface-modal').classList.add('hidden');
  1892. state.currentModalIface = null;
  1893. }
  1894. async function setIfaceState(name, newState) {
  1895. await toggleInterfaceState(name, newState);
  1896. const updated = (state.interfaces || []).find(i => i.name === name);
  1897. if (updated) openIfaceModal(name);
  1898. }
  1899. async function applyMTU() {
  1900. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1901. try {
  1902. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1903. method: 'POST',
  1904. headers: { 'Content-Type': 'application/json' },
  1905. body: JSON.stringify({ mtu })
  1906. });
  1907. if (res.ok) {
  1908. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1909. fetchData(false);
  1910. }
  1911. } catch (err) {
  1912. showToast('Error', err.message, 'error');
  1913. }
  1914. }
  1915. async function addInterfaceIP() {
  1916. const ip = document.getElementById('modal-new-ip').value.trim();
  1917. if (!ip) return;
  1918. try {
  1919. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ ip })
  1923. });
  1924. if (res.ok) {
  1925. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1926. document.getElementById('modal-new-ip').value = '';
  1927. await fetchData(false);
  1928. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1929. if (iface) renderModalIPs(iface);
  1930. } else {
  1931. const err = await res.json();
  1932. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1933. }
  1934. } catch (err) {
  1935. showToast('Error', err.message, 'error');
  1936. }
  1937. }
  1938. async function removeInterfaceIP(ip) {
  1939. if (!confirm(`Remove IP ${ip}?`)) return;
  1940. try {
  1941. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1942. method: 'DELETE',
  1943. headers: { 'Content-Type': 'application/json' },
  1944. body: JSON.stringify({ ip })
  1945. });
  1946. if (res.ok) {
  1947. showToast('IP Removed', `Removed ${ip}`, 'success');
  1948. await fetchData(false);
  1949. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1950. if (iface) renderModalIPs(iface);
  1951. }
  1952. } catch (err) {
  1953. showToast('Error', err.message, 'error');
  1954. }
  1955. }
  1956. async function saveInterfaceMetadata() {
  1957. const role = document.getElementById('modal-iface-role').value;
  1958. const desc = document.getElementById('modal-iface-desc').value.trim();
  1959. try {
  1960. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1961. method: 'POST',
  1962. headers: { 'Content-Type': 'application/json' },
  1963. body: JSON.stringify({ role, description: desc })
  1964. });
  1965. if (res.ok) {
  1966. showToast('Saved', 'Metadata updated', 'success');
  1967. closeIfaceModal();
  1968. fetchData(false);
  1969. }
  1970. } catch (err) {
  1971. showToast('Error', err.message, 'error');
  1972. }
  1973. }
  1974. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1975. state.fwSubTab = 'filter';
  1976. state.routesSubTab = 'routes';
  1977. function renderRuleFlag(disabled, hasComment) {
  1978. let flags = '';
  1979. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1980. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1981. return flags || '<span class="text-slate-600">-</span>';
  1982. }
  1983. function renderActionBadge(action) {
  1984. const act = (action || '').toLowerCase();
  1985. let color = 'bg-slate-800 text-slate-300';
  1986. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1987. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1988. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1989. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1990. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1991. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1992. }
  1993. function switchFWSubTab(tab) {
  1994. state.fwSubTab = tab;
  1995. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1996. tabs.forEach(t => {
  1997. const panel = document.getElementById(`fw-subtab-${t}`);
  1998. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1999. if (panel) {
  2000. if (t === tab) panel.classList.remove('hidden');
  2001. else panel.classList.add('hidden');
  2002. }
  2003. if (btn) {
  2004. if (t === tab) {
  2005. 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';
  2006. } else {
  2007. 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';
  2008. }
  2009. }
  2010. });
  2011. const addBtn = document.getElementById('fw-primary-add-btn');
  2012. if (addBtn) {
  2013. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2014. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2015. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2016. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2017. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2018. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2019. }
  2020. if (tab === 'geo') loadGeoIP();
  2021. if (tab === 'connections') loadConnections();
  2022. }
  2023. function openCurrentFWModal() {
  2024. if (state.fwSubTab === 'filter') openAddFilterModal();
  2025. else if (state.fwSubTab === 'nat') openAddNATModal();
  2026. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2027. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2028. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2029. else if (state.fwSubTab === 'connections') loadConnections();
  2030. }
  2031. async function loadFirewall(populateDropdowns = true) {
  2032. try {
  2033. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2034. fetch(`${API_BASE}/firewall/summary`),
  2035. fetch(`${API_BASE}/firewall/filter`),
  2036. fetch(`${API_BASE}/firewall/nat`),
  2037. fetch(`${API_BASE}/firewall/mangle`),
  2038. fetch(`${API_BASE}/firewall/address-lists`),
  2039. fetch(`${API_BASE}/firewall/geoip/status`),
  2040. fetch(`${API_BASE}/firewall/geoip/countries`)
  2041. ]);
  2042. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2043. if (filterRes.ok) state.filterRules = await filterRes.json();
  2044. if (natRes.ok) state.natRules = await natRes.json();
  2045. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2046. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2047. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2048. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2049. // Badges
  2050. const bFilter = document.getElementById('fw-badge-filter');
  2051. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2052. const bNat = document.getElementById('fw-badge-nat');
  2053. if (bNat) bNat.innerText = (state.natRules || []).length;
  2054. const bMangle = document.getElementById('fw-badge-mangle');
  2055. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2056. const bAddr = document.getElementById('fw-badge-addrlist');
  2057. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2058. const bGeo = document.getElementById('fw-badge-geo');
  2059. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2060. renderFilterRules();
  2061. renderNATRules();
  2062. renderMangleRules();
  2063. renderAddressLists();
  2064. renderGeoCountries();
  2065. if (state.fwSubTab === 'connections') {
  2066. loadConnections();
  2067. }
  2068. } catch (err) {
  2069. console.error('Failed to load firewall:', err);
  2070. }
  2071. }
  2072. // ----------------- Filter Rules -----------------
  2073. function renderFilterRules() {
  2074. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2075. const tbody = document.getElementById('filter-table-body');
  2076. const empty = document.getElementById('filter-empty');
  2077. if (!tbody) return;
  2078. tbody.innerHTML = '';
  2079. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2080. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2081. if (rules.length === 0) {
  2082. empty?.classList.remove('hidden');
  2083. return;
  2084. }
  2085. empty?.classList.add('hidden');
  2086. rules.forEach((r, idx) => {
  2087. const tr = document.createElement('tr');
  2088. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2089. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2090. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2091. tr.innerHTML = `
  2092. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2093. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2094. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2095. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2096. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2097. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2098. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2099. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2100. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2101. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2102. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2103. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2104. </td>
  2105. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2106. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2107. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2108. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2109. <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>
  2110. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2111. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2112. </td>
  2113. `;
  2114. tbody.appendChild(tr);
  2115. });
  2116. }
  2117. function formatTarget(addr, list, geo) {
  2118. const parts = [];
  2119. if (addr) parts.push(`<span>${addr}</span>`);
  2120. if (list) {
  2121. const inv = list.startsWith('!') ? '!' : '';
  2122. const clean = list.replace(/^!/, '');
  2123. 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>`);
  2124. }
  2125. if (geo) {
  2126. const inv = geo.startsWith('!') ? '!' : '';
  2127. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2128. 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>`);
  2129. }
  2130. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2131. return parts.join(' ');
  2132. }
  2133. function populateInterfaceSelect(selectId, currentVal = '') {
  2134. const sel = document.getElementById(selectId);
  2135. if (!sel) return;
  2136. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2137. (state.interfaces || []).forEach(i => {
  2138. const opt = document.createElement('option');
  2139. opt.value = i.name;
  2140. opt.innerText = `${i.name} (${i.role || i.type})`;
  2141. if (i.name === currentVal) opt.selected = true;
  2142. sel.appendChild(opt);
  2143. });
  2144. }
  2145. function populateAddressListSelect(selectId, currentVal = '') {
  2146. const sel = document.getElementById(selectId);
  2147. if (!sel) return;
  2148. sel.innerHTML = '<option value="">(None)</option>';
  2149. const cleanVal = (currentVal || '').replace(/^!/, '');
  2150. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2151. customNames.forEach(name => {
  2152. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2153. const opt = document.createElement('option');
  2154. opt.value = name;
  2155. opt.innerText = `${name} (${count} entries)`;
  2156. if (name === cleanVal) opt.selected = true;
  2157. sel.appendChild(opt);
  2158. });
  2159. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2160. const opt = document.createElement('option');
  2161. opt.value = cleanVal;
  2162. opt.innerText = cleanVal;
  2163. opt.selected = true;
  2164. sel.appendChild(opt);
  2165. }
  2166. }
  2167. function populateGeoIPSelect(selectId, currentVal = '') {
  2168. const sel = document.getElementById(selectId);
  2169. if (!sel) return;
  2170. sel.innerHTML = '<option value="">(None)</option>';
  2171. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2172. // Presets optgroup
  2173. const grpPresets = document.createElement('optgroup');
  2174. grpPresets.label = '⚡ Regional Presets';
  2175. const presets = [
  2176. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2177. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2178. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2179. ];
  2180. presets.forEach(p => {
  2181. const opt = document.createElement('option');
  2182. opt.value = p.code;
  2183. opt.innerText = p.label;
  2184. if (p.code === cleanVal) opt.selected = true;
  2185. grpPresets.appendChild(opt);
  2186. });
  2187. sel.appendChild(grpPresets);
  2188. // All Countries optgroup
  2189. const grpCountries = document.createElement('optgroup');
  2190. grpCountries.label = '🌍 All Countries';
  2191. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2192. countries.forEach(c => {
  2193. const opt = document.createElement('option');
  2194. opt.value = c.code;
  2195. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2196. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2197. if (c.code === cleanVal) opt.selected = true;
  2198. grpCountries.appendChild(opt);
  2199. });
  2200. sel.appendChild(grpCountries);
  2201. }
  2202. function openAddFilterModal() {
  2203. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2204. document.getElementById('filter-modal-id').value = '';
  2205. document.getElementById('filter-modal-chain').value = 'forward';
  2206. document.getElementById('filter-modal-action').value = 'accept';
  2207. document.getElementById('filter-modal-proto').value = 'all';
  2208. document.getElementById('filter-modal-src').value = '';
  2209. document.getElementById('filter-modal-dst').value = '';
  2210. document.getElementById('filter-modal-sport').value = '';
  2211. document.getElementById('filter-modal-dport').value = '';
  2212. document.getElementById('filter-modal-connmark').value = '';
  2213. document.getElementById('filter-modal-comment').value = '';
  2214. document.getElementById('filter-modal-disabled').checked = false;
  2215. document.getElementById('filter-modal-cs-established').checked = false;
  2216. document.getElementById('filter-modal-cs-related').checked = false;
  2217. document.getElementById('filter-modal-cs-new').checked = false;
  2218. document.getElementById('filter-modal-cs-invalid').checked = false;
  2219. populateInterfaceSelect('filter-modal-iniface');
  2220. populateInterfaceSelect('filter-modal-outiface');
  2221. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2222. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2223. populateAddressListSelect('filter-modal-srclist');
  2224. populateAddressListSelect('filter-modal-dstlist');
  2225. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2226. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2227. populateGeoIPSelect('filter-modal-srcgeoip');
  2228. populateGeoIPSelect('filter-modal-dstgeoip');
  2229. toggleFilterActionFields();
  2230. document.getElementById('filter-modal').classList.remove('hidden');
  2231. }
  2232. function openEditFilterModal(id) {
  2233. const r = (state.filterRules || []).find(rule => rule.id === id);
  2234. if (!r) return;
  2235. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2236. document.getElementById('filter-modal-id').value = r.id;
  2237. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2238. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2239. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2240. document.getElementById('filter-modal-src').value = r.src_address || '';
  2241. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2242. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2243. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2244. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2245. document.getElementById('filter-modal-comment').value = r.comment || '';
  2246. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2247. const states = r.connection_state || [];
  2248. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2249. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2250. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2251. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2252. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2253. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2254. const srcInv = (r.src_address_list || '').startsWith('!');
  2255. const dstInv = (r.dst_address_list || '').startsWith('!');
  2256. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2257. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2258. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2259. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2260. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2261. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2262. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2263. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2264. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2265. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2266. toggleFilterActionFields();
  2267. document.getElementById('filter-modal').classList.remove('hidden');
  2268. }
  2269. function closeFilterModal() {
  2270. document.getElementById('filter-modal').classList.add('hidden');
  2271. }
  2272. function toggleFilterActionFields() {
  2273. const act = document.getElementById('filter-modal-action').value;
  2274. const rejectBox = document.getElementById('filter-action-reject-box');
  2275. if (rejectBox) {
  2276. if (act === 'reject') rejectBox.classList.remove('hidden');
  2277. else rejectBox.classList.add('hidden');
  2278. }
  2279. }
  2280. async function submitSaveFilterRule(e) {
  2281. e.preventDefault();
  2282. const id = document.getElementById('filter-modal-id').value;
  2283. const chain = document.getElementById('filter-modal-chain').value;
  2284. const action = document.getElementById('filter-modal-action').value;
  2285. const proto = document.getElementById('filter-modal-proto').value;
  2286. const src = document.getElementById('filter-modal-src').value.trim();
  2287. const dst = document.getElementById('filter-modal-dst').value.trim();
  2288. const sport = document.getElementById('filter-modal-sport').value.trim();
  2289. const dport = document.getElementById('filter-modal-dport').value.trim();
  2290. const inIface = document.getElementById('filter-modal-iniface').value;
  2291. const outIface = document.getElementById('filter-modal-outiface').value;
  2292. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2293. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2294. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2295. srclist = '!' + srclist.replace(/^!/, '');
  2296. }
  2297. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2298. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2299. dstlist = '!' + dstlist.replace(/^!/, '');
  2300. }
  2301. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2302. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2303. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2304. }
  2305. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2306. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2307. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2308. }
  2309. const comment = document.getElementById('filter-modal-comment').value.trim();
  2310. const disabled = document.getElementById('filter-modal-disabled').checked;
  2311. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2312. const states = [];
  2313. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2314. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2315. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2316. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2317. try {
  2318. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2319. method: 'POST',
  2320. headers: { 'Content-Type': 'application/json' },
  2321. body: JSON.stringify({
  2322. id,
  2323. chain,
  2324. action,
  2325. reject_with: rejectWith,
  2326. protocol: proto,
  2327. src_address: src,
  2328. dst_address: dst,
  2329. src_port: sport,
  2330. dst_port: dport,
  2331. in_interface: inIface,
  2332. out_interface: outIface,
  2333. connection_state: states,
  2334. connection_mark: connmark,
  2335. src_address_list: srclist,
  2336. dst_address_list: dstlist,
  2337. src_geoip: srcgeoip,
  2338. dst_geoip: dstgeoip,
  2339. comment,
  2340. disabled
  2341. })
  2342. });
  2343. if (res.ok) {
  2344. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2345. closeFilterModal();
  2346. loadFirewall(false);
  2347. } else {
  2348. const err = await res.json();
  2349. showToast('Error', err.message, 'error');
  2350. }
  2351. } catch (err) {
  2352. showToast('Error', err.message, 'error');
  2353. }
  2354. }
  2355. async function moveFilterRule(id, dir) {
  2356. try {
  2357. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2358. method: 'POST',
  2359. headers: { 'Content-Type': 'application/json' },
  2360. body: JSON.stringify({ direction: dir })
  2361. });
  2362. if (res.ok) loadFirewall(false);
  2363. } catch (err) {
  2364. showToast('Error', err.message, 'error');
  2365. }
  2366. }
  2367. async function toggleFilterRuleState(id, disabled) {
  2368. try {
  2369. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2370. method: 'POST',
  2371. headers: { 'Content-Type': 'application/json' },
  2372. body: JSON.stringify({ disabled })
  2373. });
  2374. if (res.ok) loadFirewall(false);
  2375. } catch (err) {
  2376. showToast('Error', err.message, 'error');
  2377. }
  2378. }
  2379. async function deleteFilterRule(id) {
  2380. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2381. try {
  2382. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2383. if (res.ok) {
  2384. showToast('Deleted', 'Filter rule removed', 'success');
  2385. loadFirewall(false);
  2386. }
  2387. } catch (err) {
  2388. showToast('Error', err.message, 'error');
  2389. }
  2390. }
  2391. // ----------------- NAT Rules -----------------
  2392. function renderNATRules() {
  2393. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2394. const tbody = document.getElementById('nat-table-body');
  2395. const empty = document.getElementById('nat-empty');
  2396. if (!tbody) return;
  2397. tbody.innerHTML = '';
  2398. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2399. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2400. if (rules.length === 0) {
  2401. empty?.classList.remove('hidden');
  2402. return;
  2403. }
  2404. empty?.classList.add('hidden');
  2405. rules.forEach((r, idx) => {
  2406. const tr = document.createElement('tr');
  2407. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2408. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2409. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2410. tr.innerHTML = `
  2411. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2412. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2413. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2414. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2415. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2416. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2417. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2418. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2419. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2420. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2421. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2422. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2423. </td>
  2424. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2425. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2426. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2427. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2428. <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>
  2429. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2430. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2431. </td>
  2432. `;
  2433. tbody.appendChild(tr);
  2434. });
  2435. }
  2436. function openAddNATModal() {
  2437. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2438. document.getElementById('nat-modal-id').value = '';
  2439. document.getElementById('nat-modal-chain').value = 'srcnat';
  2440. document.getElementById('nat-modal-action').value = 'masquerade';
  2441. document.getElementById('nat-modal-toaddr').value = '';
  2442. document.getElementById('nat-modal-toport').value = '';
  2443. document.getElementById('nat-modal-proto').value = 'all';
  2444. document.getElementById('nat-modal-src').value = '';
  2445. document.getElementById('nat-modal-dst').value = '';
  2446. document.getElementById('nat-modal-dport').value = '';
  2447. document.getElementById('nat-modal-comment').value = '';
  2448. document.getElementById('nat-modal-disabled').checked = false;
  2449. populateInterfaceSelect('nat-modal-iniface');
  2450. populateInterfaceSelect('nat-modal-outiface');
  2451. populateAddressListSelect('nat-modal-srclist');
  2452. populateAddressListSelect('nat-modal-dstlist');
  2453. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2454. if (srcInvEl) srcInvEl.checked = false;
  2455. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2456. if (dstInvEl) dstInvEl.checked = false;
  2457. populateGeoIPSelect('nat-modal-srcgeoip');
  2458. populateGeoIPSelect('nat-modal-dstgeoip');
  2459. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2460. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2461. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2462. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2463. toggleNATActionFields();
  2464. document.getElementById('nat-modal').classList.remove('hidden');
  2465. }
  2466. function openEditNATModal(id) {
  2467. const r = (state.natRules || []).find(rule => rule.id === id);
  2468. if (!r) return;
  2469. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2470. document.getElementById('nat-modal-id').value = r.id;
  2471. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2472. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2473. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2474. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2475. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2476. document.getElementById('nat-modal-src').value = r.src_address || '';
  2477. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2478. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2479. document.getElementById('nat-modal-comment').value = r.comment || '';
  2480. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2481. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2482. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2483. const srcInv = (r.src_address_list || '').startsWith('!');
  2484. const dstInv = (r.dst_address_list || '').startsWith('!');
  2485. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2486. if (srcInvEl) srcInvEl.checked = srcInv;
  2487. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2488. if (dstInvEl) dstInvEl.checked = dstInv;
  2489. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2490. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2491. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2492. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2493. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2494. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2495. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2496. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2497. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2498. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2499. toggleNATActionFields();
  2500. document.getElementById('nat-modal').classList.remove('hidden');
  2501. }
  2502. function closeNATModal() {
  2503. document.getElementById('nat-modal').classList.add('hidden');
  2504. }
  2505. function toggleNATChainFields() {
  2506. const ch = document.getElementById('nat-modal-chain').value;
  2507. const actSel = document.getElementById('nat-modal-action');
  2508. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2509. actSel.value = 'masquerade';
  2510. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2511. actSel.value = 'dst-nat';
  2512. }
  2513. toggleNATActionFields();
  2514. }
  2515. function toggleNATActionFields() {
  2516. const act = document.getElementById('nat-modal-action').value;
  2517. const toBox = document.getElementById('nat-action-to-box');
  2518. if (toBox) {
  2519. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2520. else toBox.classList.remove('hidden');
  2521. }
  2522. }
  2523. async function submitSaveNATRule(e) {
  2524. e.preventDefault();
  2525. const id = document.getElementById('nat-modal-id').value;
  2526. const chain = document.getElementById('nat-modal-chain').value;
  2527. const action = document.getElementById('nat-modal-action').value;
  2528. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2529. const toport = document.getElementById('nat-modal-toport').value.trim();
  2530. const proto = document.getElementById('nat-modal-proto').value;
  2531. const src = document.getElementById('nat-modal-src').value.trim();
  2532. const dst = document.getElementById('nat-modal-dst').value.trim();
  2533. const dport = document.getElementById('nat-modal-dport').value.trim();
  2534. const inIface = document.getElementById('nat-modal-iniface').value;
  2535. const outIface = document.getElementById('nat-modal-outiface').value;
  2536. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2537. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2538. srclist = '!' + srclist.replace(/^!/, '');
  2539. }
  2540. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2541. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2542. dstlist = '!' + dstlist.replace(/^!/, '');
  2543. }
  2544. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2545. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2546. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2547. }
  2548. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2549. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2550. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2551. }
  2552. const comment = document.getElementById('nat-modal-comment').value.trim();
  2553. const disabled = document.getElementById('nat-modal-disabled').checked;
  2554. try {
  2555. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2556. method: 'POST',
  2557. headers: { 'Content-Type': 'application/json' },
  2558. body: JSON.stringify({
  2559. id,
  2560. chain,
  2561. action,
  2562. to_addresses: toaddr,
  2563. to_ports: toport,
  2564. protocol: proto,
  2565. src_address: src,
  2566. dst_address: dst,
  2567. dst_port: dport,
  2568. in_interface: inIface,
  2569. out_interface: outIface,
  2570. src_address_list: srclist,
  2571. dst_address_list: dstlist,
  2572. src_geoip: srcgeoip,
  2573. dst_geoip: dstgeoip,
  2574. comment,
  2575. disabled
  2576. })
  2577. });
  2578. if (res.ok) {
  2579. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2580. closeNATModal();
  2581. loadFirewall(false);
  2582. }
  2583. } catch (err) {
  2584. showToast('Error', err.message, 'error');
  2585. }
  2586. }
  2587. async function moveNATRule(id, dir) {
  2588. try {
  2589. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2590. method: 'POST',
  2591. headers: { 'Content-Type': 'application/json' },
  2592. body: JSON.stringify({ direction: dir })
  2593. });
  2594. if (res.ok) loadFirewall(false);
  2595. } catch (err) {
  2596. showToast('Error', err.message, 'error');
  2597. }
  2598. }
  2599. async function toggleNATRuleState(id, disabled) {
  2600. try {
  2601. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2602. method: 'POST',
  2603. headers: { 'Content-Type': 'application/json' },
  2604. body: JSON.stringify({ disabled })
  2605. });
  2606. if (res.ok) loadFirewall(false);
  2607. } catch (err) {
  2608. showToast('Error', err.message, 'error');
  2609. }
  2610. }
  2611. async function deleteNATRule(id) {
  2612. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2613. try {
  2614. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2615. if (res.ok) {
  2616. showToast('Deleted', 'NAT rule removed', 'success');
  2617. loadFirewall(false);
  2618. }
  2619. } catch (err) {
  2620. showToast('Error', err.message, 'error');
  2621. }
  2622. }
  2623. // ----------------- Mangle Rules -----------------
  2624. function renderMangleRules() {
  2625. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2626. const tbody = document.getElementById('mangle-table-body');
  2627. const empty = document.getElementById('mangle-empty');
  2628. if (!tbody) return;
  2629. tbody.innerHTML = '';
  2630. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2631. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2632. if (rules.length === 0) {
  2633. empty?.classList.remove('hidden');
  2634. return;
  2635. }
  2636. empty?.classList.add('hidden');
  2637. rules.forEach((r, idx) => {
  2638. const tr = document.createElement('tr');
  2639. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2640. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2641. tr.innerHTML = `
  2642. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2643. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2644. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2645. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2646. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2647. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2648. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2649. <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>
  2650. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2651. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2652. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2653. </td>
  2654. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2655. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2656. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2657. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2658. <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>
  2659. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2660. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2661. </td>
  2662. `;
  2663. tbody.appendChild(tr);
  2664. });
  2665. }
  2666. function openAddMangleModal() {
  2667. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2668. document.getElementById('mangle-modal-id').value = '';
  2669. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2670. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2671. document.getElementById('mangle-modal-newmark').value = '';
  2672. document.getElementById('mangle-modal-passthrough').checked = true;
  2673. document.getElementById('mangle-modal-src').value = '';
  2674. document.getElementById('mangle-modal-dst').value = '';
  2675. document.getElementById('mangle-modal-connmark').value = '';
  2676. document.getElementById('mangle-modal-comment').value = '';
  2677. document.getElementById('mangle-modal-disabled').checked = false;
  2678. populateInterfaceSelect('mangle-modal-iniface');
  2679. populateAddressListSelect('mangle-modal-srclist');
  2680. populateAddressListSelect('mangle-modal-dstlist');
  2681. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2682. if (srcInvEl) srcInvEl.checked = false;
  2683. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2684. if (dstInvEl) dstInvEl.checked = false;
  2685. populateGeoIPSelect('mangle-modal-srcgeoip');
  2686. populateGeoIPSelect('mangle-modal-dstgeoip');
  2687. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2688. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2689. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2690. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2691. document.getElementById('mangle-modal').classList.remove('hidden');
  2692. }
  2693. function openEditMangleModal(id) {
  2694. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2695. if (!r) return;
  2696. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2697. document.getElementById('mangle-modal-id').value = r.id;
  2698. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2699. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2700. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2701. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2702. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2703. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2704. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2705. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2706. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2707. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2708. const srcInv = (r.src_address_list || '').startsWith('!');
  2709. const dstInv = (r.dst_address_list || '').startsWith('!');
  2710. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2711. if (srcInvEl) srcInvEl.checked = srcInv;
  2712. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2713. if (dstInvEl) dstInvEl.checked = dstInv;
  2714. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2715. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2716. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2717. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2718. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2719. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2720. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2721. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2722. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2723. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2724. document.getElementById('mangle-modal').classList.remove('hidden');
  2725. }
  2726. function closeMangleModal() {
  2727. document.getElementById('mangle-modal').classList.add('hidden');
  2728. }
  2729. function toggleMangleActionFields() {
  2730. // Handled smoothly by single dynamic input
  2731. }
  2732. async function submitSaveMangleRule(e) {
  2733. e.preventDefault();
  2734. const id = document.getElementById('mangle-modal-id').value;
  2735. const chain = document.getElementById('mangle-modal-chain').value;
  2736. const action = document.getElementById('mangle-modal-action').value;
  2737. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2738. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2739. const src = document.getElementById('mangle-modal-src').value.trim();
  2740. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2741. const inIface = document.getElementById('mangle-modal-iniface').value;
  2742. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2743. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2744. srclist = '!' + srclist.replace(/^!/, '');
  2745. }
  2746. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2747. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2748. dstlist = '!' + dstlist.replace(/^!/, '');
  2749. }
  2750. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2751. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2752. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2753. }
  2754. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2755. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2756. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2757. }
  2758. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2759. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2760. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2761. const payload = {
  2762. id,
  2763. chain,
  2764. action,
  2765. passthrough,
  2766. src_address: src,
  2767. dst_address: dst,
  2768. in_interface: inIface,
  2769. src_address_list: srclist,
  2770. dst_address_list: dstlist,
  2771. src_geoip: srcgeoip,
  2772. dst_geoip: dstgeoip,
  2773. connection_mark: connmark,
  2774. comment,
  2775. disabled
  2776. };
  2777. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2778. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2779. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2780. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2781. try {
  2782. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2783. method: 'POST',
  2784. headers: { 'Content-Type': 'application/json' },
  2785. body: JSON.stringify(payload)
  2786. });
  2787. if (res.ok) {
  2788. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2789. closeMangleModal();
  2790. loadFirewall(false);
  2791. }
  2792. } catch (err) {
  2793. showToast('Error', err.message, 'error');
  2794. }
  2795. }
  2796. async function moveMangleRule(id, dir) {
  2797. try {
  2798. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2799. method: 'POST',
  2800. headers: { 'Content-Type': 'application/json' },
  2801. body: JSON.stringify({ direction: dir })
  2802. });
  2803. if (res.ok) loadFirewall(false);
  2804. } catch (err) {
  2805. showToast('Error', err.message, 'error');
  2806. }
  2807. }
  2808. async function toggleMangleRuleState(id, disabled) {
  2809. try {
  2810. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2811. method: 'POST',
  2812. headers: { 'Content-Type': 'application/json' },
  2813. body: JSON.stringify({ disabled })
  2814. });
  2815. if (res.ok) loadFirewall(false);
  2816. } catch (err) {
  2817. showToast('Error', err.message, 'error');
  2818. }
  2819. }
  2820. async function deleteMangleRule(id) {
  2821. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2822. try {
  2823. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2824. if (res.ok) {
  2825. showToast('Deleted', 'Mangle rule removed', 'success');
  2826. loadFirewall(false);
  2827. }
  2828. } catch (err) {
  2829. showToast('Error', err.message, 'error');
  2830. }
  2831. }
  2832. // ----------------- Address Lists -----------------
  2833. function renderAddressLists() {
  2834. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2835. const tbody = document.getElementById('addrlist-table-body');
  2836. const empty = document.getElementById('addrlist-empty');
  2837. if (!tbody) return;
  2838. tbody.innerHTML = '';
  2839. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2840. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2841. // Update filter select
  2842. const sel = document.getElementById('addrlist-filter-name');
  2843. if (sel) {
  2844. const cur = sel.value;
  2845. sel.innerHTML = '<option value="">All Lists</option>';
  2846. const set = new Set((state.addressLists || []).map(a => a.name));
  2847. set.forEach(n => {
  2848. const opt = document.createElement('option');
  2849. opt.value = n;
  2850. opt.innerText = n;
  2851. if (n === cur) opt.selected = true;
  2852. sel.appendChild(opt);
  2853. });
  2854. }
  2855. if (entries.length === 0) {
  2856. empty?.classList.remove('hidden');
  2857. return;
  2858. }
  2859. empty?.classList.add('hidden');
  2860. entries.forEach((e, idx) => {
  2861. const tr = document.createElement('tr');
  2862. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2863. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2864. tr.innerHTML = `
  2865. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2866. <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>
  2867. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2868. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2869. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2870. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2871. <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>
  2872. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2873. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2874. </td>
  2875. `;
  2876. tbody.appendChild(tr);
  2877. });
  2878. }
  2879. function openAddAddrListModal() {
  2880. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2881. document.getElementById('addrlist-modal-id').value = '';
  2882. document.getElementById('addrlist-modal-name').value = '';
  2883. document.getElementById('addrlist-modal-addr').value = '';
  2884. document.getElementById('addrlist-modal-comment').value = '';
  2885. document.getElementById('addrlist-modal-disabled').checked = false;
  2886. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2887. if (submitBtn) submitBtn.innerText = 'Add to List';
  2888. document.getElementById('addrlist-modal').classList.remove('hidden');
  2889. }
  2890. function openEditAddrListModal(id) {
  2891. const e = (state.addressLists || []).find(item => item.id === id);
  2892. if (!e) return;
  2893. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2894. document.getElementById('addrlist-modal-id').value = e.id;
  2895. document.getElementById('addrlist-modal-name').value = e.name;
  2896. document.getElementById('addrlist-modal-addr').value = e.address;
  2897. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2898. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2899. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2900. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2901. document.getElementById('addrlist-modal').classList.remove('hidden');
  2902. }
  2903. function closeAddrListModal() {
  2904. document.getElementById('addrlist-modal').classList.add('hidden');
  2905. }
  2906. async function submitSaveAddrList(e) {
  2907. e.preventDefault();
  2908. const id = document.getElementById('addrlist-modal-id').value;
  2909. const name = document.getElementById('addrlist-modal-name').value.trim();
  2910. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2911. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2912. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2913. try {
  2914. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2915. method: 'POST',
  2916. headers: { 'Content-Type': 'application/json' },
  2917. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2918. });
  2919. if (res.ok) {
  2920. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2921. closeAddrListModal();
  2922. loadFirewall(false);
  2923. } else {
  2924. const err = await res.json();
  2925. showToast('Error', err.message || 'Failed to save address list', 'error');
  2926. }
  2927. } catch (err) {
  2928. showToast('Error', err.message, 'error');
  2929. }
  2930. }
  2931. async function toggleAddrListState(id, disabled) {
  2932. try {
  2933. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2934. method: 'POST',
  2935. headers: { 'Content-Type': 'application/json' },
  2936. body: JSON.stringify({ disabled })
  2937. });
  2938. if (res.ok) {
  2939. loadFirewall(false);
  2940. }
  2941. } catch (err) {
  2942. showToast('Error', err.message, 'error');
  2943. }
  2944. }
  2945. async function deleteAddrList(id) {
  2946. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2947. try {
  2948. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2949. if (res.ok) {
  2950. showToast('Deleted', 'Address list item removed', 'info');
  2951. loadFirewall(false);
  2952. }
  2953. } catch (err) {
  2954. showToast('Error', err.message, 'error');
  2955. }
  2956. }
  2957. // ----------------- Geo-Location IP Management -----------------
  2958. async function loadGeoIP() {
  2959. try {
  2960. const [statusRes, countriesRes] = await Promise.all([
  2961. fetch(`${API_BASE}/firewall/geoip/status`),
  2962. fetch(`${API_BASE}/firewall/geoip/countries`)
  2963. ]);
  2964. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2965. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2966. updateGeoHeader();
  2967. renderGeoCountries();
  2968. } catch (err) {
  2969. console.error('Failed to load GeoIP:', err);
  2970. }
  2971. }
  2972. function getGeoUsageMap() {
  2973. const usage = {};
  2974. const checkRule = (r, type) => {
  2975. ['src_geoip', 'dst_geoip'].forEach(field => {
  2976. let val = (r && r[field]) || '';
  2977. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  2978. if (code) {
  2979. if (!usage[code]) usage[code] = [];
  2980. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  2981. if (!usage[code].includes(label)) usage[code].push(label);
  2982. }
  2983. });
  2984. };
  2985. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  2986. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  2987. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  2988. return usage;
  2989. }
  2990. function updateGeoHeader() {
  2991. const s = state.geoStatus || {};
  2992. const statusBadge = document.getElementById('geo-status-badge');
  2993. if (statusBadge) {
  2994. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2995. statusBadge.className = s.auto_update
  2996. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2997. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2998. }
  2999. const intervalLabel = document.getElementById('geo-interval-label');
  3000. if (intervalLabel) {
  3001. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3002. }
  3003. const usageMap = getGeoUsageMap();
  3004. const inUseCount = Object.keys(usageMap).length;
  3005. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3006. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3007. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3008. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3009. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3010. if (lastSyncEl) {
  3011. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3012. const d = new Date(s.last_updated);
  3013. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3014. } else {
  3015. lastSyncEl.innerText = 'Never (Sync Pending)';
  3016. }
  3017. }
  3018. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3019. if (nextSyncEl) {
  3020. if (s.next_update && !s.next_update.startsWith('0001')) {
  3021. const d = new Date(s.next_update);
  3022. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3023. } else {
  3024. nextSyncEl.innerText = '-';
  3025. }
  3026. }
  3027. const badge = document.getElementById('fw-badge-geo');
  3028. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3029. }
  3030. function renderGeoCountries() {
  3031. const tbody = document.getElementById('geo-table-body');
  3032. const empty = document.getElementById('geo-empty');
  3033. if (!tbody) return;
  3034. tbody.innerHTML = '';
  3035. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3036. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3037. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3038. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3039. const usageMap = getGeoUsageMap();
  3040. const countries = (state.geoCountries || []).filter(c => {
  3041. const isUsed = !!usageMap[c.code];
  3042. if (inUseOnly && !isUsed) return false;
  3043. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3044. if (continent && c.continent !== continent) return false;
  3045. if (q) {
  3046. const matchCode = c.code.toLowerCase().includes(q);
  3047. const matchName = c.name.toLowerCase().includes(q);
  3048. if (!matchCode && !matchName) return false;
  3049. }
  3050. return true;
  3051. });
  3052. if (countries.length === 0) {
  3053. empty?.classList.remove('hidden');
  3054. return;
  3055. }
  3056. empty?.classList.add('hidden');
  3057. countries.forEach(c => {
  3058. const tr = document.createElement('tr');
  3059. const isUsed = !!usageMap[c.code];
  3060. const rulesUsing = usageMap[c.code] || [];
  3061. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3062. let statusHtml = '';
  3063. if (isUsed) {
  3064. 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>`;
  3065. } else if (c.subnet_count > 0) {
  3066. 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>';
  3067. } else {
  3068. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3069. }
  3070. tr.innerHTML = `
  3071. <td class="py-2.5 px-3 text-center">
  3072. <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'}">
  3073. ${c.code}
  3074. </span>
  3075. </td>
  3076. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3077. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3078. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3079. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3080. </td>
  3081. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3082. <td class="py-2.5 px-3">
  3083. ${statusHtml}
  3084. </td>
  3085. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3086. <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>
  3087. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3088. </td>
  3089. `;
  3090. tbody.appendChild(tr);
  3091. });
  3092. }
  3093. function quickFilterGeo(preset) {
  3094. const searchInput = document.getElementById('geo-search-input');
  3095. const continentSel = document.getElementById('geo-continent-filter');
  3096. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3097. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3098. if (searchInput) searchInput.value = '';
  3099. if (continentSel) continentSel.value = '';
  3100. if (inUseCheck) inUseCheck.checked = false;
  3101. if (cachedCheck) cachedCheck.checked = false;
  3102. if (preset === 'GR') {
  3103. if (searchInput) searchInput.value = 'Greece';
  3104. } else if (preset === 'Europe') {
  3105. if (continentSel) continentSel.value = 'Europe';
  3106. } else if (preset === 'HIGHRISK') {
  3107. if (searchInput) searchInput.value = 'China';
  3108. }
  3109. renderGeoCountries();
  3110. }
  3111. async function toggleGeoCountry(code, enabled) {
  3112. try {
  3113. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3114. method: 'POST',
  3115. headers: { 'Content-Type': 'application/json' },
  3116. body: JSON.stringify({ enabled })
  3117. });
  3118. if (res.ok) {
  3119. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3120. loadGeoIP();
  3121. } else {
  3122. const err = await res.json();
  3123. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3124. }
  3125. } catch (err) {
  3126. showToast('Error', err.message, 'error');
  3127. }
  3128. }
  3129. async function updateGeoCountry(code) {
  3130. try {
  3131. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3132. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3133. if (res.ok) {
  3134. const data = await res.json();
  3135. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3136. loadGeoIP();
  3137. } else {
  3138. const err = await res.json();
  3139. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3140. }
  3141. } catch (err) {
  3142. showToast('Error', err.message, 'error');
  3143. }
  3144. }
  3145. async function triggerGeoUpdateNow() {
  3146. const spinner = document.getElementById('geo-update-spinner');
  3147. if (spinner) spinner.classList.remove('hidden');
  3148. try {
  3149. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3150. if (res.ok) {
  3151. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3152. setTimeout(() => {
  3153. loadGeoIP();
  3154. if (spinner) spinner.classList.add('hidden');
  3155. }, 2500);
  3156. } else {
  3157. const err = await res.json();
  3158. showToast('Notice', err.message || 'Update in progress', 'info');
  3159. if (spinner) spinner.classList.add('hidden');
  3160. }
  3161. } catch (err) {
  3162. showToast('Error', err.message, 'error');
  3163. if (spinner) spinner.classList.add('hidden');
  3164. }
  3165. }
  3166. async function applyGeoPreset(preset) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3172. });
  3173. if (res.ok) {
  3174. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3175. loadGeoIP();
  3176. }
  3177. } catch (err) {
  3178. showToast('Error', err.message, 'error');
  3179. }
  3180. }
  3181. function openGeoIntervalModal() {
  3182. const s = state.geoStatus || {};
  3183. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3184. const sel = document.getElementById('geo-cfg-interval');
  3185. const customBox = document.getElementById('geo-cfg-custom-box');
  3186. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3187. const curHours = s.interval_hours || 24;
  3188. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3189. if (matchOption) {
  3190. sel.value = String(curHours);
  3191. customBox.classList.add('hidden');
  3192. } else {
  3193. sel.value = 'custom';
  3194. customHoursInput.value = curHours;
  3195. customBox.classList.remove('hidden');
  3196. }
  3197. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3198. }
  3199. function closeGeoIntervalModal() {
  3200. document.getElementById('geo-interval-modal').classList.add('hidden');
  3201. }
  3202. function toggleCustomGeoInterval() {
  3203. const val = document.getElementById('geo-cfg-interval').value;
  3204. const customBox = document.getElementById('geo-cfg-custom-box');
  3205. if (val === 'custom') {
  3206. customBox.classList.remove('hidden');
  3207. } else {
  3208. customBox.classList.add('hidden');
  3209. }
  3210. }
  3211. async function submitGeoIntervalSettings(e) {
  3212. e.preventDefault();
  3213. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3214. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3215. let hours = 24;
  3216. if (intervalVal === 'custom') {
  3217. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3218. } else {
  3219. hours = parseInt(intervalVal, 10) || 24;
  3220. }
  3221. try {
  3222. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3223. method: 'POST',
  3224. headers: { 'Content-Type': 'application/json' },
  3225. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3226. });
  3227. if (res.ok) {
  3228. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3229. closeGeoIntervalModal();
  3230. loadGeoIP();
  3231. } else {
  3232. const err = await res.json();
  3233. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3234. }
  3235. } catch (err) {
  3236. showToast('Error', err.message, 'error');
  3237. }
  3238. }
  3239. async function viewGeoSubnets(code, name) {
  3240. if (!name) {
  3241. const found = (state.geoCountries || []).find(x => x.code === code);
  3242. name = found ? found.name : code;
  3243. }
  3244. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3245. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3246. const listEl = document.getElementById('geo-subnets-list');
  3247. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3248. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3249. try {
  3250. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3251. if (res.ok) {
  3252. const data = await res.json();
  3253. const subnets = data.subnets || [];
  3254. if (subnets.length === 0) {
  3255. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3256. } else {
  3257. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3258. }
  3259. } else {
  3260. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3261. }
  3262. } catch (err) {
  3263. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3264. }
  3265. }
  3266. function closeGeoSubnetsModal() {
  3267. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3268. }
  3269. // ----------------- Active Connections Tracking -----------------
  3270. async function loadConnections() {
  3271. try {
  3272. const res = await fetch(`${API_BASE}/firewall/connections`);
  3273. const data = await res.json();
  3274. state.connections = Array.isArray(data) ? data : [];
  3275. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3276. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3277. renderConnections();
  3278. } catch (err) {
  3279. console.error('Failed to load connections:', err);
  3280. }
  3281. }
  3282. function renderConnections() {
  3283. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3284. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3285. const tbody = document.getElementById('conns-table-body');
  3286. const empty = document.getElementById('conns-empty');
  3287. if (!tbody) return;
  3288. tbody.innerHTML = '';
  3289. const conns = (state.connections || []).filter(c => {
  3290. if (protoFilter && c.protocol !== protoFilter) return false;
  3291. if (search) {
  3292. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3293. if (!line.includes(search)) return false;
  3294. }
  3295. return true;
  3296. });
  3297. if (conns.length === 0) {
  3298. empty?.classList.remove('hidden');
  3299. return;
  3300. }
  3301. empty?.classList.add('hidden');
  3302. conns.slice(0, 150).forEach(c => {
  3303. const tr = document.createElement('tr');
  3304. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3305. let stateColor = 'text-slate-400';
  3306. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3307. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3308. tr.innerHTML = `
  3309. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3310. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3311. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3312. <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>
  3313. <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>
  3314. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3315. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3316. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3317. <td class="py-2.5 px-3 text-right font-sans">
  3318. <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>
  3319. </td>
  3320. `;
  3321. tbody.appendChild(tr);
  3322. });
  3323. }
  3324. async function killConnection(protocol, src, sport, dst, dport) {
  3325. try {
  3326. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3327. method: 'POST',
  3328. headers: { 'Content-Type': 'application/json' },
  3329. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3330. });
  3331. if (res.ok) {
  3332. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3333. loadConnections();
  3334. }
  3335. } catch (err) {
  3336. showToast('Error', err.message, 'error');
  3337. }
  3338. }
  3339. async function resetFirewallCounters() {
  3340. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3341. try {
  3342. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3343. if (res.ok) {
  3344. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3345. loadFirewall(false);
  3346. }
  3347. } catch (err) {
  3348. showToast('Error', err.message, 'error');
  3349. }
  3350. }
  3351. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3352. function switchRoutesSubTab(tab) {
  3353. state.routesSubTab = tab;
  3354. const tabs = ['routes', 'rules', 'tables'];
  3355. tabs.forEach(t => {
  3356. const panel = document.getElementById(`routes-subtab-${t}`);
  3357. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3358. if (panel) {
  3359. if (t === tab) panel.classList.remove('hidden');
  3360. else panel.classList.add('hidden');
  3361. }
  3362. if (btn) {
  3363. if (t === tab) {
  3364. 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';
  3365. } else {
  3366. 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';
  3367. }
  3368. }
  3369. });
  3370. }
  3371. async function loadRoutes() {
  3372. try {
  3373. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3374. fetch(`${API_BASE}/routes`),
  3375. fetch(`${API_BASE}/routing/rules`),
  3376. fetch(`${API_BASE}/routing/tables`)
  3377. ]);
  3378. if (routesRes.ok) state.routes = await routesRes.json();
  3379. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3380. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3381. const bRoutes = document.getElementById('routes-badge-routes');
  3382. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3383. const bRules = document.getElementById('routes-badge-rules');
  3384. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3385. const bTables = document.getElementById('routes-badge-tables');
  3386. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3387. const bRoutesCount = document.getElementById('badge-routes-count');
  3388. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3389. renderRoutesList();
  3390. renderPolicyRules();
  3391. renderRoutingTables();
  3392. } catch (err) {
  3393. console.error('Failed to load routing:', err);
  3394. }
  3395. }
  3396. function renderRoutesList() {
  3397. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3398. const tbody = document.getElementById('routes-table-body');
  3399. const empty = document.getElementById('routes-empty');
  3400. if (!tbody) return;
  3401. tbody.innerHTML = '';
  3402. // Update table filter select
  3403. const sel = document.getElementById('routes-filter-table');
  3404. if (sel) {
  3405. const cur = sel.value;
  3406. sel.innerHTML = '<option value="">All Tables</option>';
  3407. (state.routingTables || []).forEach(t => {
  3408. const opt = document.createElement('option');
  3409. opt.value = t.name;
  3410. opt.innerText = t.name;
  3411. if (t.name === cur) opt.selected = true;
  3412. sel.appendChild(opt);
  3413. });
  3414. }
  3415. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3416. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3417. if (routes.length === 0) {
  3418. empty?.classList.remove('hidden');
  3419. return;
  3420. }
  3421. empty?.classList.add('hidden');
  3422. routes.forEach(r => {
  3423. const tr = document.createElement('tr');
  3424. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3425. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3426. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3427. let flags = '';
  3428. if (r.dynamic) flags += 'D';
  3429. if (r.active) flags += 'A';
  3430. if (r.connect) flags += 'C';
  3431. if (r.static) flags += 'S';
  3432. if (r.disabled) flags += 'X';
  3433. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3434. tr.innerHTML = `
  3435. <td class="py-2.5 px-3 text-center">
  3436. <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'}">
  3437. ${flags || '-'}
  3438. </span>
  3439. </td>
  3440. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3441. <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>
  3442. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3443. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3444. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3445. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3446. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3447. ${r.static ? `
  3448. <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>
  3449. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3450. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3451. ` : `
  3452. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3453. `}
  3454. </td>
  3455. `;
  3456. tbody.appendChild(tr);
  3457. });
  3458. }
  3459. function openAddRouteModal() {
  3460. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3461. document.getElementById('route-modal-id').value = '';
  3462. document.getElementById('route-modal-old-dst').value = '';
  3463. document.getElementById('route-modal-old-gw').value = '';
  3464. document.getElementById('route-modal-old-distance').value = '';
  3465. document.getElementById('route-modal-old-table').value = '';
  3466. document.getElementById('route-modal-old-iface').value = '';
  3467. const dstInput = document.getElementById('route-modal-dst');
  3468. const gwInput = document.getElementById('route-modal-gw');
  3469. const distInput = document.getElementById('route-modal-distance');
  3470. const ifaceSelect = document.getElementById('route-modal-iface');
  3471. const tableSelect = document.getElementById('route-modal-table');
  3472. const commentInput = document.getElementById('route-modal-comment');
  3473. const disCheck = document.getElementById('route-modal-disabled');
  3474. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3475. dstInput.disabled = false;
  3476. dstInput.value = '0.0.0.0/0';
  3477. gwInput.disabled = false;
  3478. gwInput.value = '';
  3479. distInput.disabled = false;
  3480. distInput.value = '1';
  3481. ifaceSelect.disabled = false;
  3482. tableSelect.disabled = false;
  3483. commentInput.disabled = false;
  3484. commentInput.value = '';
  3485. disCheck.disabled = false;
  3486. disCheck.checked = false;
  3487. if (saveBtn) saveBtn.classList.remove('hidden');
  3488. populateInterfaceSelect('route-modal-iface');
  3489. // Populate tables
  3490. tableSelect.innerHTML = '';
  3491. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3492. const opt = document.createElement('option');
  3493. opt.value = t.name;
  3494. opt.innerText = t.name;
  3495. if (t.name === 'main') opt.selected = true;
  3496. tableSelect.appendChild(opt);
  3497. });
  3498. document.getElementById('route-modal').classList.remove('hidden');
  3499. }
  3500. function openEditRouteModal(id) {
  3501. const r = (state.routes || []).find(route => route.id === id);
  3502. if (!r) return;
  3503. const isStatic = !!r.static;
  3504. document.getElementById('route-modal-title').innerText = isStatic
  3505. ? `Edit Route: ${r.dst_address}`
  3506. : `Route Properties (Read Only): ${r.dst_address}`;
  3507. document.getElementById('route-modal-id').value = r.id;
  3508. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3509. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3510. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3511. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3512. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3513. const dstInput = document.getElementById('route-modal-dst');
  3514. const gwInput = document.getElementById('route-modal-gw');
  3515. const distInput = document.getElementById('route-modal-distance');
  3516. const ifaceSelect = document.getElementById('route-modal-iface');
  3517. const tableSelect = document.getElementById('route-modal-table');
  3518. const commentInput = document.getElementById('route-modal-comment');
  3519. const disCheck = document.getElementById('route-modal-disabled');
  3520. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3521. dstInput.value = r.dst_address;
  3522. gwInput.value = r.gateway || '';
  3523. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3524. commentInput.value = r.comment || '';
  3525. disCheck.checked = !!r.disabled;
  3526. dstInput.disabled = !isStatic;
  3527. gwInput.disabled = !isStatic;
  3528. distInput.disabled = !isStatic;
  3529. ifaceSelect.disabled = !isStatic;
  3530. tableSelect.disabled = !isStatic;
  3531. commentInput.disabled = !isStatic;
  3532. disCheck.disabled = !isStatic;
  3533. if (saveBtn) {
  3534. if (isStatic) {
  3535. saveBtn.classList.remove('hidden');
  3536. } else {
  3537. saveBtn.classList.add('hidden');
  3538. }
  3539. }
  3540. populateInterfaceSelect('route-modal-iface', r.interface);
  3541. tableSelect.innerHTML = '';
  3542. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3543. const opt = document.createElement('option');
  3544. opt.value = t.name;
  3545. opt.innerText = t.name;
  3546. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3547. tableSelect.appendChild(opt);
  3548. });
  3549. document.getElementById('route-modal').classList.remove('hidden');
  3550. }
  3551. function closeRouteModal() {
  3552. document.getElementById('route-modal').classList.add('hidden');
  3553. }
  3554. async function submitSaveRoute(e) {
  3555. e.preventDefault();
  3556. const id = document.getElementById('route-modal-id').value;
  3557. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3558. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3559. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3560. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3561. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3562. const dst = document.getElementById('route-modal-dst').value.trim();
  3563. const gw = document.getElementById('route-modal-gw').value.trim();
  3564. const table = document.getElementById('route-modal-table').value;
  3565. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3566. const iface = document.getElementById('route-modal-iface').value;
  3567. const comment = document.getElementById('route-modal-comment').value.trim();
  3568. const disabled = document.getElementById('route-modal-disabled').checked;
  3569. if (!dst) {
  3570. showToast('Error', 'Destination address is required', 'error');
  3571. return;
  3572. }
  3573. if (!gw && !iface) {
  3574. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3575. return;
  3576. }
  3577. const payload = {
  3578. id,
  3579. old_dst_address: oldDst,
  3580. old_gateway: oldGw,
  3581. old_routing_table: oldTable,
  3582. old_interface: oldIface,
  3583. dst_address: dst,
  3584. gateway: gw || iface,
  3585. routing_table: table,
  3586. distance,
  3587. interface: iface,
  3588. comment,
  3589. disabled
  3590. };
  3591. if (oldDistStr !== undefined && oldDistStr !== '') {
  3592. payload.old_distance = parseInt(oldDistStr, 10);
  3593. }
  3594. try {
  3595. const res = await fetch(`${API_BASE}/routes`, {
  3596. method: 'POST',
  3597. headers: { 'Content-Type': 'application/json' },
  3598. body: JSON.stringify(payload)
  3599. });
  3600. if (res.ok) {
  3601. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3602. closeRouteModal();
  3603. loadRoutes();
  3604. } else {
  3605. const err = await res.json();
  3606. showToast('Error', err.message || 'Failed to save route', 'error');
  3607. }
  3608. } catch (err) {
  3609. showToast('Error', err.message, 'error');
  3610. }
  3611. }
  3612. async function toggleRouteState(id, disabled) {
  3613. try {
  3614. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3615. method: 'POST',
  3616. headers: { 'Content-Type': 'application/json' },
  3617. body: JSON.stringify({ disabled })
  3618. });
  3619. if (res.ok) loadRoutes();
  3620. } catch (err) {
  3621. showToast('Error', err.message, 'error');
  3622. }
  3623. }
  3624. async function deleteRoute(id) {
  3625. if (!confirm('Are you sure you want to delete this route?')) return;
  3626. try {
  3627. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3628. if (res.ok) {
  3629. showToast('Deleted', 'Route removed', 'success');
  3630. loadRoutes();
  3631. }
  3632. } catch (err) {
  3633. showToast('Error', err.message, 'error');
  3634. }
  3635. }
  3636. // ----------------- Policy Rules (/ip route rule) -----------------
  3637. function renderPolicyRules() {
  3638. const tbody = document.getElementById('rules-table-body');
  3639. const empty = document.getElementById('rules-empty');
  3640. if (!tbody) return;
  3641. tbody.innerHTML = '';
  3642. const rules = state.policyRules || [];
  3643. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3644. if (rules.length === 0) {
  3645. empty?.classList.remove('hidden');
  3646. return;
  3647. }
  3648. empty?.classList.add('hidden');
  3649. rules.forEach(pr => {
  3650. const tr = document.createElement('tr');
  3651. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3652. tr.innerHTML = `
  3653. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3654. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3655. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3656. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3657. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3658. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3659. <td class="py-2.5 px-3 text-right font-sans">
  3660. ${pr.priority < 32766 && pr.priority > 0 ? `
  3661. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3662. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3663. </td>
  3664. `;
  3665. tbody.appendChild(tr);
  3666. });
  3667. }
  3668. function openAddPolicyRuleModal() {
  3669. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3670. document.getElementById('prule-modal-mark').value = '';
  3671. document.getElementById('prule-modal-src').value = '';
  3672. document.getElementById('prule-modal-dst').value = '';
  3673. const sel = document.getElementById('prule-modal-table');
  3674. sel.innerHTML = '';
  3675. (state.routingTables || []).forEach(t => {
  3676. const opt = document.createElement('option');
  3677. opt.value = t.name;
  3678. opt.innerText = t.name;
  3679. sel.appendChild(opt);
  3680. });
  3681. document.getElementById('prule-modal').classList.remove('hidden');
  3682. }
  3683. function closePolicyRuleModal() {
  3684. document.getElementById('prule-modal').classList.add('hidden');
  3685. }
  3686. async function submitSavePolicyRule(e) {
  3687. e.preventDefault();
  3688. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3689. const mark = document.getElementById('prule-modal-mark').value.trim();
  3690. const src = document.getElementById('prule-modal-src').value.trim();
  3691. const dst = document.getElementById('prule-modal-dst').value.trim();
  3692. const table = document.getElementById('prule-modal-table').value;
  3693. const action = document.getElementById('prule-modal-action').value;
  3694. try {
  3695. const res = await fetch(`${API_BASE}/routing/rules`, {
  3696. method: 'POST',
  3697. headers: { 'Content-Type': 'application/json' },
  3698. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3699. });
  3700. if (res.ok) {
  3701. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3702. closePolicyRuleModal();
  3703. loadRoutes();
  3704. } else {
  3705. const err = await res.json();
  3706. showToast('Error', err.message, 'error');
  3707. }
  3708. } catch (err) {
  3709. showToast('Error', err.message, 'error');
  3710. }
  3711. }
  3712. async function deletePolicyRule(id) {
  3713. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3714. try {
  3715. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3716. if (res.ok) {
  3717. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3718. loadRoutes();
  3719. }
  3720. } catch (err) {
  3721. showToast('Error', err.message, 'error');
  3722. }
  3723. }
  3724. // ----------------- Routing Tables -----------------
  3725. function renderRoutingTables() {
  3726. const tbody = document.getElementById('tables-table-body');
  3727. if (!tbody) return;
  3728. tbody.innerHTML = '';
  3729. (state.routingTables || []).forEach(t => {
  3730. const tr = document.createElement('tr');
  3731. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3732. tr.innerHTML = `
  3733. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3734. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3735. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3736. `;
  3737. tbody.appendChild(tr);
  3738. });
  3739. }
  3740. function openAddTableModal() {
  3741. document.getElementById('table-modal-name').value = '';
  3742. document.getElementById('table-modal-id').value = '';
  3743. document.getElementById('table-modal-comment').value = '';
  3744. document.getElementById('table-modal').classList.remove('hidden');
  3745. }
  3746. function closeTableModal() {
  3747. document.getElementById('table-modal').classList.add('hidden');
  3748. }
  3749. async function submitSaveTable(e) {
  3750. e.preventDefault();
  3751. const name = document.getElementById('table-modal-name').value.trim();
  3752. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3753. const comment = document.getElementById('table-modal-comment').value.trim();
  3754. try {
  3755. const res = await fetch(`${API_BASE}/routing/tables`, {
  3756. method: 'POST',
  3757. headers: { 'Content-Type': 'application/json' },
  3758. body: JSON.stringify({ name, table_id: id, comment })
  3759. });
  3760. if (res.ok) {
  3761. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3762. closeTableModal();
  3763. loadRoutes();
  3764. } else {
  3765. const err = await res.json();
  3766. showToast('Error', err.message, 'error');
  3767. }
  3768. } catch (err) {
  3769. showToast('Error', err.message, 'error');
  3770. }
  3771. }
  3772. async function loadDebianConfig() {
  3773. const view = document.getElementById('debian-config-view');
  3774. view.innerText = 'Generating live configuration...';
  3775. try {
  3776. const res = await fetch(`${API_BASE}/debian/config`);
  3777. const data = await res.json();
  3778. view.innerText = data.content || '# Empty config';
  3779. } catch (err) {
  3780. view.innerText = 'Failed to generate Debian network config.';
  3781. }
  3782. }
  3783. async function saveDebianConfig() {
  3784. try {
  3785. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3786. const data = await res.json();
  3787. if (res.ok) {
  3788. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3789. loadDebianConfig();
  3790. }
  3791. } catch (err) {
  3792. showToast('Error', err.message, 'error');
  3793. }
  3794. }
  3795. function showToast(title, message, type = 'info') {
  3796. const container = document.getElementById('toast-container');
  3797. const toast = document.createElement('div');
  3798. const borderColors = {
  3799. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3800. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3801. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3802. };
  3803. 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}`;
  3804. toast.innerHTML = `
  3805. <div class="flex-1">
  3806. <div class="font-bold text-xs text-white">${title}</div>
  3807. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3808. </div>
  3809. `;
  3810. container.appendChild(toast);
  3811. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3812. setTimeout(() => {
  3813. toast.classList.add('opacity-0', 'translate-y-2');
  3814. setTimeout(() => toast.remove(), 300);
  3815. }, 4000);
  3816. }
  3817. function formatTraffic(bytesPerSec) {
  3818. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3819. const kb = bytesPerSec / 1024;
  3820. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3821. const mb = kb / 1024;
  3822. return `${mb.toFixed(2)} MB/s`;
  3823. }
  3824. function toggleSidebar() {
  3825. const sb = document.getElementById('sidebar');
  3826. sb.classList.toggle('-translate-x-full');
  3827. }
  3828. // ======================== EoIP (Ethernet over IP) ========================
  3829. async function loadEoIP(populate = true) {
  3830. try {
  3831. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3832. const data = await res.json();
  3833. state.eoipTunnels = Array.isArray(data) ? data : [];
  3834. const badge = document.getElementById('eoip-count-badge');
  3835. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3836. const sideBadge = document.getElementById('badge-eoip-count');
  3837. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3838. renderEoIPTunnels();
  3839. } catch (err) {
  3840. console.error('Failed to load EoIP:', err);
  3841. }
  3842. }
  3843. function renderEoIPTunnels() {
  3844. const tbody = document.getElementById('eoip-table-body');
  3845. const empty = document.getElementById('eoip-empty');
  3846. if (!tbody) return;
  3847. tbody.innerHTML = '';
  3848. const tunnels = state.eoipTunnels || [];
  3849. if (tunnels.length === 0) {
  3850. empty?.classList.remove('hidden');
  3851. return;
  3852. }
  3853. empty?.classList.add('hidden');
  3854. tunnels.forEach(t => {
  3855. const tr = document.createElement('tr');
  3856. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3857. tr.innerHTML = `
  3858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3859. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3860. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3861. <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>
  3862. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3863. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3864. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3865. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3866. <td class="py-2.5 px-3 font-mono text-[11px]">
  3867. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3868. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3869. </td>
  3870. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3871. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3872. <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>
  3873. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3874. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3875. </td>
  3876. `;
  3877. tbody.appendChild(tr);
  3878. });
  3879. }
  3880. function openAddEoIPModal() {
  3881. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3882. document.getElementById('eoip-modal-id').value = '';
  3883. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3884. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3885. document.getElementById('eoip-modal-remote').value = '';
  3886. document.getElementById('eoip-modal-ip').value = '';
  3887. document.getElementById('eoip-modal-local').value = '';
  3888. document.getElementById('eoip-modal-mac').value = '';
  3889. document.getElementById('eoip-modal-mtu').value = '1500';
  3890. document.getElementById('eoip-modal-comment').value = '';
  3891. document.getElementById('eoip-modal-clampmss').checked = true;
  3892. document.getElementById('eoip-modal-disabled').checked = false;
  3893. document.getElementById('eoip-modal').classList.remove('hidden');
  3894. }
  3895. function openEditEoIPModal(id) {
  3896. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3897. if (!t) return;
  3898. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3899. document.getElementById('eoip-modal-id').value = t.id;
  3900. document.getElementById('eoip-modal-name').value = t.name;
  3901. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3902. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3903. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3904. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3905. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3906. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3907. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3908. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3909. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3910. document.getElementById('eoip-modal').classList.remove('hidden');
  3911. }
  3912. function closeEoIPModal() {
  3913. document.getElementById('eoip-modal').classList.add('hidden');
  3914. }
  3915. async function submitSaveEoIP(e) {
  3916. e.preventDefault();
  3917. const id = document.getElementById('eoip-modal-id').value;
  3918. const name = document.getElementById('eoip-modal-name').value.trim();
  3919. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3920. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3921. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3922. const local = document.getElementById('eoip-modal-local').value.trim();
  3923. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3924. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3925. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3926. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3927. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3928. try {
  3929. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3930. method: 'POST',
  3931. headers: { 'Content-Type': 'application/json' },
  3932. body: JSON.stringify({
  3933. id,
  3934. name,
  3935. tunnel_id: tunnelId,
  3936. remote_address: remote,
  3937. ip_address: ipAddress,
  3938. local_address: local,
  3939. mac_address: mac,
  3940. mtu,
  3941. clamp_mss: clampMss,
  3942. comment,
  3943. disabled
  3944. })
  3945. });
  3946. if (res.ok) {
  3947. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3948. closeEoIPModal();
  3949. loadEoIP(false);
  3950. fetchData(false);
  3951. } else {
  3952. const err = await res.json();
  3953. showToast('Error', err.message, 'error');
  3954. }
  3955. } catch (err) {
  3956. showToast('Error', err.message, 'error');
  3957. }
  3958. }
  3959. async function toggleEoIPState(id, disabled) {
  3960. try {
  3961. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3962. method: 'POST',
  3963. headers: { 'Content-Type': 'application/json' },
  3964. body: JSON.stringify({ disabled })
  3965. });
  3966. if (res.ok) {
  3967. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3968. loadEoIP(false);
  3969. fetchData(false);
  3970. }
  3971. } catch (err) {
  3972. showToast('Error', err.message, 'error');
  3973. }
  3974. }
  3975. async function deleteEoIP(id) {
  3976. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3977. try {
  3978. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3979. if (res.ok) {
  3980. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3981. loadEoIP(false);
  3982. fetchData(false);
  3983. }
  3984. } catch (err) {
  3985. showToast('Error', err.message, 'error');
  3986. }
  3987. }
  3988. // ======================== PPP Central Hub & Servers ========================
  3989. function switchPPPSubTab(tab) {
  3990. state.pppSubTab = tab;
  3991. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3992. tabs.forEach(t => {
  3993. const panel = document.getElementById(`ppp-subtab-${t}`);
  3994. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3995. if (panel) {
  3996. if (t === tab) panel.classList.remove('hidden');
  3997. else panel.classList.add('hidden');
  3998. }
  3999. if (btn) {
  4000. if (t === tab) {
  4001. 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';
  4002. } else {
  4003. 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';
  4004. }
  4005. }
  4006. });
  4007. const addBtn = document.getElementById('ppp-primary-add-btn');
  4008. if (addBtn) {
  4009. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4010. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4011. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4012. else addBtn.innerHTML = '<span>Save Config</span>';
  4013. }
  4014. if (tab === 'active') loadPPPSessions();
  4015. }
  4016. function openCurrentPPPModal() {
  4017. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4018. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4019. else if (state.pppSubTab === 'active') loadPPPSessions();
  4020. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4021. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4022. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4023. }
  4024. async function loadPPP(populateDropdowns = true) {
  4025. await Promise.all([
  4026. loadPPPSecrets(),
  4027. loadPPPProfiles(),
  4028. loadPPPServers(),
  4029. loadPPPSessions()
  4030. ]);
  4031. }
  4032. async function loadPPPSecrets() {
  4033. try {
  4034. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4035. const data = await res.json();
  4036. state.pppSecrets = Array.isArray(data) ? data : [];
  4037. const b = document.getElementById('ppp-badge-secrets');
  4038. if (b) b.innerText = state.pppSecrets.length;
  4039. const b2 = document.getElementById('secrets-count-badge');
  4040. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4041. renderPPPSecrets();
  4042. } catch (err) {
  4043. console.error('Failed to load PPP secrets:', err);
  4044. }
  4045. }
  4046. function renderPPPSecrets() {
  4047. const tbody = document.getElementById('secrets-table-body');
  4048. const empty = document.getElementById('secrets-empty');
  4049. if (!tbody) return;
  4050. tbody.innerHTML = '';
  4051. const secrets = state.pppSecrets || [];
  4052. if (secrets.length === 0) {
  4053. empty?.classList.remove('hidden');
  4054. return;
  4055. }
  4056. empty?.classList.add('hidden');
  4057. secrets.forEach(s => {
  4058. const tr = document.createElement('tr');
  4059. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4060. tr.innerHTML = `
  4061. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4062. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4063. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4064. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4065. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4066. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4067. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4068. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4069. <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>
  4070. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4071. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4072. </td>
  4073. `;
  4074. tbody.appendChild(tr);
  4075. });
  4076. }
  4077. async function loadPPPProfiles() {
  4078. try {
  4079. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4080. const data = await res.json();
  4081. state.pppProfiles = Array.isArray(data) ? data : [];
  4082. const b = document.getElementById('ppp-badge-profiles');
  4083. if (b) b.innerText = state.pppProfiles.length;
  4084. const b2 = document.getElementById('profiles-count-badge');
  4085. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4086. // Populate profile selects across modals
  4087. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4088. selects.forEach(sid => {
  4089. const el = document.getElementById(sid);
  4090. if (!el) return;
  4091. const cur = el.value;
  4092. el.innerHTML = '';
  4093. state.pppProfiles.forEach(p => {
  4094. const opt = document.createElement('option');
  4095. opt.value = p.name;
  4096. opt.innerText = `${p.name} (${p.remote_address})`;
  4097. if (p.name === cur) opt.selected = true;
  4098. el.appendChild(opt);
  4099. });
  4100. });
  4101. renderPPPProfiles();
  4102. } catch (err) {
  4103. console.error('Failed to load PPP profiles:', err);
  4104. }
  4105. }
  4106. function renderPPPProfiles() {
  4107. const tbody = document.getElementById('profiles-table-body');
  4108. if (!tbody) return;
  4109. tbody.innerHTML = '';
  4110. (state.pppProfiles || []).forEach(p => {
  4111. const isDefault = p.name.startsWith('default');
  4112. const tr = document.createElement('tr');
  4113. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4114. tr.innerHTML = `
  4115. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4116. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4117. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4118. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4119. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4120. <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>
  4121. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4122. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4123. ${!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>`}
  4124. </td>
  4125. `;
  4126. tbody.appendChild(tr);
  4127. });
  4128. }
  4129. async function loadPPPServers() {
  4130. try {
  4131. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4132. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4133. fetch(`${API_BASE}/vpn/servers/pptp`),
  4134. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4135. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4136. ]);
  4137. if (pppoeRes.ok) {
  4138. state.pppoeServer = await pppoeRes.json();
  4139. const s = state.pppoeServer;
  4140. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4141. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4142. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4143. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4144. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4145. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4146. const pill = document.getElementById('pppoe-server-status-pill');
  4147. if (pill) {
  4148. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4149. 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';
  4150. }
  4151. setDotBadge('ppp-badge-pppoe-state', s.running);
  4152. }
  4153. if (pptpRes.ok) {
  4154. state.pptpServer = await pptpRes.json();
  4155. const s = state.pptpServer;
  4156. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4157. document.getElementById('pptp-server-port').value = s.port || 1723;
  4158. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4159. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4160. const pill = document.getElementById('pptp-server-status-pill');
  4161. if (pill) {
  4162. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4163. 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';
  4164. }
  4165. setDotBadge('ppp-badge-pptp-state', s.running);
  4166. }
  4167. if (l2tpRes.ok) {
  4168. state.l2tpServer = await l2tpRes.json();
  4169. const s = state.l2tpServer;
  4170. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4171. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4172. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4173. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4174. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4175. const pill = document.getElementById('l2tp-server-status-pill');
  4176. if (pill) {
  4177. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4178. 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';
  4179. }
  4180. setDotBadge('ppp-badge-l2tp-state', s.running);
  4181. }
  4182. if (ipsecRes.ok) {
  4183. state.ipsecServer = await ipsecRes.json();
  4184. const s = state.ipsecServer;
  4185. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4186. if (modalEn) modalEn.checked = !!s.enabled;
  4187. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4188. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4189. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4190. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4191. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4192. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4193. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4194. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4195. const pill = document.getElementById('modal-ipsec-server-status');
  4196. if (pill) {
  4197. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4198. 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';
  4199. }
  4200. }
  4201. } catch (err) {
  4202. console.error('Failed to load VPN servers:', err);
  4203. }
  4204. }
  4205. async function loadPPPSessions() {
  4206. try {
  4207. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4208. const data = await res.json();
  4209. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4210. const b = document.getElementById('ppp-badge-active');
  4211. if (b) b.innerText = state.pppActiveSessions.length;
  4212. const sideB = document.getElementById('badge-ppp-sessions');
  4213. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4214. renderPPPSessions();
  4215. } catch (err) {
  4216. console.error('Failed to load active PPP sessions:', err);
  4217. }
  4218. }
  4219. function renderPPPSessions() {
  4220. const tbody = document.getElementById('active-ppp-table-body');
  4221. const empty = document.getElementById('active-ppp-empty');
  4222. if (!tbody) return;
  4223. tbody.innerHTML = '';
  4224. const list = state.pppActiveSessions || [];
  4225. if (list.length === 0) {
  4226. empty?.classList.remove('hidden');
  4227. return;
  4228. }
  4229. empty?.classList.add('hidden');
  4230. list.forEach(s => {
  4231. const tr = document.createElement('tr');
  4232. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4233. tr.innerHTML = `
  4234. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4235. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4236. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4237. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4238. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4239. <td class="py-2.5 px-3 text-[11px]">
  4240. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4241. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4242. </td>
  4243. <td class="py-2.5 px-3 text-right font-sans">
  4244. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4245. </td>
  4246. `;
  4247. tbody.appendChild(tr);
  4248. });
  4249. }
  4250. async function disconnectPPPSession(iface) {
  4251. if (!confirm(`Disconnect session ${iface}?`)) return;
  4252. try {
  4253. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4254. if (res.ok) {
  4255. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4256. loadPPPSessions();
  4257. }
  4258. } catch (err) {
  4259. showToast('Error', err.message, 'error');
  4260. }
  4261. }
  4262. // PPP Secret Modal handlers
  4263. function openAddPPPSecretModal() {
  4264. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4265. document.getElementById('secret-modal-id').value = '';
  4266. document.getElementById('secret-modal-name').value = '';
  4267. document.getElementById('secret-modal-password').value = '';
  4268. document.getElementById('secret-modal-service').value = 'any';
  4269. document.getElementById('secret-modal-profile').value = 'default';
  4270. document.getElementById('secret-modal-local').value = '';
  4271. document.getElementById('secret-modal-remote').value = '';
  4272. document.getElementById('secret-modal-comment').value = '';
  4273. document.getElementById('secret-modal-disabled').checked = false;
  4274. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4275. }
  4276. function openEditPPPSecretModal(id) {
  4277. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4278. if (!s) return;
  4279. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4280. document.getElementById('secret-modal-id').value = s.id;
  4281. document.getElementById('secret-modal-name').value = s.name;
  4282. document.getElementById('secret-modal-password').value = s.password;
  4283. document.getElementById('secret-modal-service').value = s.service || 'any';
  4284. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4285. document.getElementById('secret-modal-local').value = s.local_address || '';
  4286. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4287. document.getElementById('secret-modal-comment').value = s.comment || '';
  4288. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4289. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4290. }
  4291. function closePPPSecretModal() {
  4292. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4293. }
  4294. async function submitSavePPPSecret(e) {
  4295. e.preventDefault();
  4296. const id = document.getElementById('secret-modal-id').value;
  4297. const name = document.getElementById('secret-modal-name').value.trim();
  4298. const password = document.getElementById('secret-modal-password').value.trim();
  4299. const service = document.getElementById('secret-modal-service').value;
  4300. const profile = document.getElementById('secret-modal-profile').value;
  4301. const local = document.getElementById('secret-modal-local').value.trim();
  4302. const remote = document.getElementById('secret-modal-remote').value.trim();
  4303. const comment = document.getElementById('secret-modal-comment').value.trim();
  4304. const disabled = document.getElementById('secret-modal-disabled').checked;
  4305. try {
  4306. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4307. method: 'POST',
  4308. headers: { 'Content-Type': 'application/json' },
  4309. body: JSON.stringify({
  4310. id,
  4311. name,
  4312. password,
  4313. service,
  4314. profile,
  4315. local_address: local,
  4316. remote_address: remote,
  4317. comment,
  4318. disabled
  4319. })
  4320. });
  4321. if (res.ok) {
  4322. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4323. closePPPSecretModal();
  4324. loadPPPSecrets();
  4325. } else {
  4326. const err = await res.json();
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. } catch (err) {
  4330. showToast('Error', err.message, 'error');
  4331. }
  4332. }
  4333. async function togglePPPSecretState(id, disabled) {
  4334. try {
  4335. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4336. method: 'POST',
  4337. headers: { 'Content-Type': 'application/json' },
  4338. body: JSON.stringify({ disabled })
  4339. });
  4340. if (res.ok) {
  4341. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4342. loadPPPSecrets();
  4343. }
  4344. } catch (err) {
  4345. showToast('Error', err.message, 'error');
  4346. }
  4347. }
  4348. async function deletePPPSecret(id) {
  4349. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4350. try {
  4351. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4352. if (res.ok) {
  4353. showToast('Deleted', 'Secret account removed', 'success');
  4354. loadPPPSecrets();
  4355. }
  4356. } catch (err) {
  4357. showToast('Error', err.message, 'error');
  4358. }
  4359. }
  4360. // PPP Profile Modal handlers
  4361. function openAddPPPProfileModal() {
  4362. document.getElementById('profile-modal-name').value = '';
  4363. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4364. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4365. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4366. document.getElementById('profile-modal-encryption').value = 'required';
  4367. document.getElementById('profile-modal-onlyone').checked = true;
  4368. document.getElementById('profile-modal-comment').value = '';
  4369. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4370. }
  4371. function closePPPProfileModal() {
  4372. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4373. }
  4374. async function submitSavePPPProfile(e) {
  4375. e.preventDefault();
  4376. const name = document.getElementById('profile-modal-name').value.trim();
  4377. const local = document.getElementById('profile-modal-local').value.trim();
  4378. const remote = document.getElementById('profile-modal-remote').value.trim();
  4379. const dns = document.getElementById('profile-modal-dns').value.trim();
  4380. const enc = document.getElementById('profile-modal-encryption').value;
  4381. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4382. const comment = document.getElementById('profile-modal-comment').value.trim();
  4383. try {
  4384. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4385. method: 'POST',
  4386. headers: { 'Content-Type': 'application/json' },
  4387. body: JSON.stringify({
  4388. id: name,
  4389. name,
  4390. local_address: local,
  4391. remote_address: remote,
  4392. dns_servers: dns,
  4393. use_encryption: enc,
  4394. only_one: onlyone,
  4395. comment
  4396. })
  4397. });
  4398. if (res.ok) {
  4399. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4400. closePPPProfileModal();
  4401. loadPPPProfiles();
  4402. } else {
  4403. const err = await res.json();
  4404. showToast('Error', err.message, 'error');
  4405. }
  4406. } catch (err) {
  4407. showToast('Error', err.message, 'error');
  4408. }
  4409. }
  4410. async function deletePPPProfile(name) {
  4411. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4412. try {
  4413. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4414. if (res.ok) {
  4415. showToast('Deleted', 'Profile removed', 'success');
  4416. loadPPPProfiles();
  4417. } else {
  4418. const err = await res.json();
  4419. showToast('Error', err.message, 'error');
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // Server Config submissions
  4426. async function savePPPoEServerConfig(e) {
  4427. e.preventDefault();
  4428. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4429. const name = document.getElementById('pppoe-server-name').value.trim();
  4430. const iface = document.getElementById('pppoe-server-iface').value;
  4431. const profile = document.getElementById('pppoe-server-profile').value;
  4432. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4433. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4434. try {
  4435. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4436. method: 'POST',
  4437. headers: { 'Content-Type': 'application/json' },
  4438. body: JSON.stringify({
  4439. enabled,
  4440. service_name: name,
  4441. interface: iface,
  4442. default_profile: profile,
  4443. max_mtu: mtu,
  4444. max_mru: mtu,
  4445. one_session_per_host: onesession
  4446. })
  4447. });
  4448. if (res.ok) {
  4449. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4450. loadPPPServers();
  4451. fetchData(false);
  4452. } else {
  4453. const err = await res.json();
  4454. showToast('Error', err.message, 'error');
  4455. }
  4456. } catch (err) {
  4457. showToast('Error', err.message, 'error');
  4458. }
  4459. }
  4460. async function savePPTPServerConfig(e) {
  4461. e.preventDefault();
  4462. const enabled = document.getElementById('pptp-server-enabled').checked;
  4463. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4464. const profile = document.getElementById('pptp-server-profile').value;
  4465. const mppe = document.getElementById('pptp-server-mppe').checked;
  4466. try {
  4467. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4468. method: 'POST',
  4469. headers: { 'Content-Type': 'application/json' },
  4470. body: JSON.stringify({
  4471. enabled,
  4472. port,
  4473. default_profile: profile,
  4474. require_mppe: mppe
  4475. })
  4476. });
  4477. if (res.ok) {
  4478. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4479. loadPPPServers();
  4480. fetchData(false);
  4481. } else {
  4482. const err = await res.json();
  4483. showToast('Error', err.message, 'error');
  4484. }
  4485. } catch (err) {
  4486. showToast('Error', err.message, 'error');
  4487. }
  4488. }
  4489. async function saveL2TPServerConfig(e) {
  4490. e.preventDefault();
  4491. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4492. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4493. const profile = document.getElementById('l2tp-server-profile').value;
  4494. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4495. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4496. try {
  4497. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4498. method: 'POST',
  4499. headers: { 'Content-Type': 'application/json' },
  4500. body: JSON.stringify({
  4501. enabled,
  4502. port,
  4503. default_profile: profile,
  4504. use_ipsec: useipsec,
  4505. ipsec_secret: psk
  4506. })
  4507. });
  4508. if (res.ok) {
  4509. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4510. loadPPPServers();
  4511. fetchData(false);
  4512. } else {
  4513. const err = await res.json();
  4514. showToast('Error', err.message, 'error');
  4515. }
  4516. } catch (err) {
  4517. showToast('Error', err.message, 'error');
  4518. }
  4519. }
  4520. // IPSec Server Modal
  4521. function openIPSecServerModal() {
  4522. loadPPPServers();
  4523. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4524. }
  4525. function closeIPSecServerModal() {
  4526. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4527. }
  4528. async function submitSaveIPSecServer(e) {
  4529. e.preventDefault();
  4530. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4531. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4532. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4533. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4534. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4535. try {
  4536. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4537. method: 'POST',
  4538. headers: { 'Content-Type': 'application/json' },
  4539. body: JSON.stringify({
  4540. enabled,
  4541. preshared_key: psk,
  4542. pool_address: pool,
  4543. dns_servers: dns,
  4544. local_subnet: subnet
  4545. })
  4546. });
  4547. if (res.ok) {
  4548. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4549. closeIPSecServerModal();
  4550. loadPPPServers();
  4551. fetchData(false);
  4552. } else {
  4553. const err = await res.json();
  4554. showToast('Error', err.message, 'error');
  4555. }
  4556. } catch (err) {
  4557. showToast('Error', err.message, 'error');
  4558. }
  4559. }
  4560. // WireGuard Client Config Viewer
  4561. let currentWGClientConf = '';
  4562. async function openWGClientConfModal(iface, clientIP) {
  4563. try {
  4564. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4565. method: 'POST',
  4566. headers: { 'Content-Type': 'application/json' },
  4567. body: JSON.stringify({
  4568. interface: iface,
  4569. address: clientIP || '10.10.0.2/32',
  4570. dns: '1.1.1.1, 8.8.8.8'
  4571. })
  4572. });
  4573. if (res.ok) {
  4574. const data = await res.json();
  4575. currentWGClientConf = data.config;
  4576. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4577. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4578. } else {
  4579. const err = await res.json();
  4580. showToast('Error', err.message, 'error');
  4581. }
  4582. } catch (err) {
  4583. showToast('Error', err.message, 'error');
  4584. }
  4585. }
  4586. function closeWGClientConfModal() {
  4587. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4588. }
  4589. function copyWGClientConf() {
  4590. if (!currentWGClientConf) return;
  4591. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4592. }
  4593. function downloadWGClientConf() {
  4594. if (!currentWGClientConf) return;
  4595. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4596. const a = document.createElement('a');
  4597. a.href = URL.createObjectURL(blob);
  4598. a.download = 'wireguard-client.conf';
  4599. document.body.appendChild(a);
  4600. a.click();
  4601. document.body.removeChild(a);
  4602. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4603. }
  4604. // =========================================================================
  4605. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4606. // =========================================================================
  4607. state.activeDynSubTab = 'bgp-peers';
  4608. state.activeBgpSubTab = 'bgp-peers';
  4609. state.activeOspfSubTab = 'ospf-ifaces';
  4610. state.bgpInstance = null;
  4611. state.bgpPeers = [];
  4612. state.bgpNets = [];
  4613. state.bgpRoutes = [];
  4614. state.ospfInstance = null;
  4615. state.ospfInterfaces = [];
  4616. state.ospfAreas = [];
  4617. state.ospfNeighbors = [];
  4618. state.ospfRoutes = [];
  4619. function switchBgpSubTab(subTab) {
  4620. state.activeBgpSubTab = subTab;
  4621. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4622. tabs.forEach(t => {
  4623. const el = document.getElementById(`dyn-subtab-${t}`);
  4624. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4625. if (el) el.classList.toggle('hidden', t !== subTab);
  4626. if (btn) {
  4627. if (t === subTab) {
  4628. 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';
  4629. } else {
  4630. 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';
  4631. }
  4632. }
  4633. });
  4634. }
  4635. function switchOspfSubTab(subTab) {
  4636. state.activeOspfSubTab = subTab;
  4637. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4638. tabs.forEach(t => {
  4639. const el = document.getElementById(`dyn-subtab-${t}`);
  4640. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4641. if (el) el.classList.toggle('hidden', t !== subTab);
  4642. if (btn) {
  4643. if (t === subTab) {
  4644. 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';
  4645. } else {
  4646. 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';
  4647. }
  4648. }
  4649. });
  4650. }
  4651. function switchDynSubTab(subTab) {
  4652. if (subTab.startsWith('bgp')) {
  4653. if (state.activeTab !== 'bgp') navigate('bgp');
  4654. switchBgpSubTab(subTab);
  4655. } else if (subTab.startsWith('ospf')) {
  4656. if (state.activeTab !== 'ospf') navigate('ospf');
  4657. switchOspfSubTab(subTab);
  4658. }
  4659. }
  4660. async function loadDynamicRouting(showToastMsg = false) {
  4661. try {
  4662. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes, filtersRes] = await Promise.all([
  4663. fetch(`${API_BASE}/routing/dynamic/summary`),
  4664. fetch(`${API_BASE}/routing/bgp/instance`),
  4665. fetch(`${API_BASE}/routing/bgp/peers`),
  4666. fetch(`${API_BASE}/routing/bgp/networks`),
  4667. fetch(`${API_BASE}/routing/bgp/routes`),
  4668. fetch(`${API_BASE}/routing/ospf/instance`),
  4669. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4670. fetch(`${API_BASE}/routing/ospf/areas`),
  4671. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4672. fetch(`${API_BASE}/routing/ospf/routes`),
  4673. fetch(`${API_BASE}/routing/filters`)
  4674. ]);
  4675. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4676. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4677. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4678. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4679. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4680. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4681. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4682. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4683. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4684. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4685. if (filtersRes && filtersRes.ok) state.routingFilters = await filtersRes.json();
  4686. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4687. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4688. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4689. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4690. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4691. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4692. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4693. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  4694. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  4695. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  4696. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  4697. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  4698. } catch (err) {
  4699. console.error('Failed to load dynamic routing:', err);
  4700. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4701. }
  4702. }
  4703. function renderBgpStatusPill() {
  4704. const pill = document.getElementById('bgp-live-status-pill');
  4705. if (!pill) return;
  4706. const inst = state.bgpInstance;
  4707. if (!inst || !inst.enabled) {
  4708. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4709. pill.innerText = 'BGP DISABLED';
  4710. } else if (inst.running) {
  4711. 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';
  4712. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4713. } else {
  4714. 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';
  4715. pill.innerText = 'BGP STARTING...';
  4716. }
  4717. }
  4718. function renderBgpPeers() {
  4719. const tbody = document.getElementById('bgp-peers-table-body');
  4720. if (!tbody) return;
  4721. const empty = document.getElementById('bgp-peers-empty');
  4722. const countBadge = document.getElementById('bgp-peers-count-badge');
  4723. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4724. const peers = state.bgpPeers || [];
  4725. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4726. if (navBadge) navBadge.innerText = peers.length;
  4727. if (peers.length === 0) {
  4728. tbody.innerHTML = '';
  4729. if (empty) empty.classList.remove('hidden');
  4730. return;
  4731. }
  4732. if (empty) empty.classList.add('hidden');
  4733. tbody.innerHTML = peers.map(p => {
  4734. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4735. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4736. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4737. let stateBadge = '';
  4738. if (p.disabled) {
  4739. 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>';
  4740. } else if (p.state === 'Established') {
  4741. 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>';
  4742. } else if (p.state === 'Connect' || p.state === 'Active') {
  4743. 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>`;
  4744. } else {
  4745. 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>`;
  4746. }
  4747. return `
  4748. <tr class="hover:bg-slate-800/40 transition">
  4749. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4750. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4751. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4752. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4753. <td class="py-2.5 px-3">${stateBadge}</td>
  4754. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4755. <td class="py-2.5 px-3 text-slate-300">
  4756. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4757. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4758. </td>
  4759. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  4760. ${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> ` : ''}
  4761. ${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>` : ''}
  4762. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  4763. </td>
  4764. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4765. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4766. <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'}">
  4767. ${p.disabled ? 'Enable' : 'Disable'}
  4768. </button>
  4769. <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">
  4770. Edit
  4771. </button>
  4772. <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">
  4773. Delete
  4774. </button>
  4775. </td>
  4776. </tr>
  4777. `;
  4778. }).join('');
  4779. }
  4780. function renderBgpNetworks() {
  4781. const tbody = document.getElementById('bgp-nets-table-body');
  4782. if (!tbody) return;
  4783. const empty = document.getElementById('bgp-nets-empty');
  4784. const countBadge = document.getElementById('bgp-nets-count-badge');
  4785. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4786. const nets = state.bgpNets || [];
  4787. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4788. if (navBadge) navBadge.innerText = nets.length;
  4789. if (nets.length === 0) {
  4790. tbody.innerHTML = '';
  4791. if (empty) empty.classList.remove('hidden');
  4792. return;
  4793. }
  4794. if (empty) empty.classList.add('hidden');
  4795. tbody.innerHTML = nets.map(n => `
  4796. <tr class="hover:bg-slate-800/40 transition">
  4797. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4798. <td class="py-2.5 px-3">
  4799. ${n.disabled
  4800. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4801. : '<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>'}
  4802. </td>
  4803. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4804. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4805. <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">
  4806. Delete
  4807. </button>
  4808. </td>
  4809. </tr>
  4810. `).join('');
  4811. }
  4812. function renderBgpRoutes() {
  4813. const tbody = document.getElementById('bgp-routes-table-body');
  4814. if (!tbody) return;
  4815. const empty = document.getElementById('bgp-routes-empty');
  4816. const countBadge = document.getElementById('bgp-routes-count-badge');
  4817. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4818. const routes = state.bgpRoutes || [];
  4819. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4820. if (navBadge) navBadge.innerText = routes.length;
  4821. if (routes.length === 0) {
  4822. tbody.innerHTML = '';
  4823. if (empty) empty.classList.remove('hidden');
  4824. return;
  4825. }
  4826. if (empty) empty.classList.add('hidden');
  4827. tbody.innerHTML = routes.map(r => `
  4828. <tr class="hover:bg-slate-800/40 transition">
  4829. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4830. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4831. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4832. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4833. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4834. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4835. </tr>
  4836. `).join('');
  4837. }
  4838. function renderOspfStatusPill() {
  4839. const pill = document.getElementById('ospf-live-status-pill');
  4840. if (!pill) return;
  4841. const inst = state.ospfInstance;
  4842. if (!inst || !inst.enabled) {
  4843. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4844. pill.innerText = 'OSPF DISABLED';
  4845. } else if (inst.running) {
  4846. 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';
  4847. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4848. } else {
  4849. 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';
  4850. pill.innerText = 'OSPF STARTING...';
  4851. }
  4852. }
  4853. function renderOspfInterfaces() {
  4854. const tbody = document.getElementById('ospf-ifaces-table-body');
  4855. if (!tbody) return;
  4856. const empty = document.getElementById('ospf-ifaces-empty');
  4857. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4858. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4859. const ifaces = state.ospfInterfaces || [];
  4860. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4861. if (navBadge) navBadge.innerText = ifaces.length;
  4862. if (ifaces.length === 0) {
  4863. tbody.innerHTML = '';
  4864. if (empty) empty.classList.remove('hidden');
  4865. return;
  4866. }
  4867. if (empty) empty.classList.add('hidden');
  4868. tbody.innerHTML = ifaces.map(i => {
  4869. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4870. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4871. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4872. return `
  4873. <tr class="hover:bg-slate-800/40 transition">
  4874. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4875. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4876. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4877. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4878. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4879. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4880. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4881. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4882. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4883. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4884. <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'}">
  4885. ${i.disabled ? 'Enable' : 'Disable'}
  4886. </button>
  4887. <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">
  4888. Edit
  4889. </button>
  4890. <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">
  4891. Delete
  4892. </button>
  4893. </td>
  4894. </tr>
  4895. `;
  4896. }).join('');
  4897. }
  4898. function renderOspfAreas() {
  4899. const tbody = document.getElementById('ospf-areas-table-body');
  4900. if (!tbody) return;
  4901. const countBadge = document.getElementById('ospf-areas-count-badge');
  4902. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4903. const areas = state.ospfAreas || [];
  4904. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4905. if (navBadge) navBadge.innerText = areas.length;
  4906. tbody.innerHTML = areas.map(a => `
  4907. <tr class="hover:bg-slate-800/40 transition">
  4908. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4909. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4910. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4911. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4912. <td class="py-2.5 px-3 text-right font-sans">
  4913. <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">
  4914. Delete
  4915. </button>
  4916. </td>
  4917. </tr>
  4918. `).join('');
  4919. }
  4920. function renderOspfNeighbors() {
  4921. const tbody = document.getElementById('ospf-nbrs-table-body');
  4922. if (!tbody) return;
  4923. const empty = document.getElementById('ospf-nbrs-empty');
  4924. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4925. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4926. const nbrs = state.ospfNeighbors || [];
  4927. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4928. if (navBadge) navBadge.innerText = nbrs.length;
  4929. if (nbrs.length === 0) {
  4930. tbody.innerHTML = '';
  4931. if (empty) empty.classList.remove('hidden');
  4932. return;
  4933. }
  4934. if (empty) empty.classList.add('hidden');
  4935. tbody.innerHTML = nbrs.map(n => {
  4936. let stateBadge = '';
  4937. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4938. 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>`;
  4939. } else {
  4940. 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>`;
  4941. }
  4942. return `
  4943. <tr class="hover:bg-slate-800/40 transition">
  4944. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4945. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4946. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4947. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4948. <td class="py-2.5 px-3">${stateBadge}</td>
  4949. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4950. </tr>
  4951. `;
  4952. }).join('');
  4953. }
  4954. function renderOspfRoutes() {
  4955. const tbody = document.getElementById('ospf-routes-table-body');
  4956. if (!tbody) return;
  4957. const empty = document.getElementById('ospf-routes-empty');
  4958. const countBadge = document.getElementById('ospf-routes-count-badge');
  4959. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4960. const routes = state.ospfRoutes || [];
  4961. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4962. if (navBadge) navBadge.innerText = routes.length;
  4963. if (routes.length === 0) {
  4964. tbody.innerHTML = '';
  4965. if (empty) empty.classList.remove('hidden');
  4966. return;
  4967. }
  4968. if (empty) empty.classList.add('hidden');
  4969. tbody.innerHTML = routes.map(r => `
  4970. <tr class="hover:bg-slate-800/40 transition">
  4971. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4972. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4973. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4974. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4975. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4976. </tr>
  4977. `).join('');
  4978. }
  4979. // BGP Modals & Actions
  4980. function openBgpInstanceModal() {
  4981. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4982. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4983. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4984. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4985. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4986. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4987. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4988. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4989. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4990. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4991. }
  4992. function closeBgpInstanceModal() {
  4993. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4994. }
  4995. async function submitBgpInstance(e) {
  4996. e.preventDefault();
  4997. const payload = {
  4998. enabled: document.getElementById('modal-bgp-enabled').checked,
  4999. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  5000. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5001. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5002. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5003. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5004. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5005. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5006. };
  5007. try {
  5008. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5009. method: 'POST',
  5010. headers: { 'Content-Type': 'application/json' },
  5011. body: JSON.stringify(payload)
  5012. });
  5013. if (res.ok) {
  5014. closeBgpInstanceModal();
  5015. showToast('Success', 'BGP instance configuration updated', 'success');
  5016. loadDynamicRouting();
  5017. } else {
  5018. const err = await res.json();
  5019. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5020. }
  5021. } catch (err) {
  5022. showToast('Error', err.message, 'error');
  5023. }
  5024. }
  5025. function openAddBgpPeerModal() {
  5026. document.getElementById('bgp-peer-form').reset();
  5027. document.getElementById('modal-bgp-peer-id').value = '';
  5028. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5029. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5030. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5031. if (inFilterEl) inFilterEl.value = '';
  5032. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5033. if (outFilterEl) outFilterEl.value = '';
  5034. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5035. }
  5036. function openEditBgpPeerModal(id) {
  5037. const p = (state.bgpPeers || []).find(item => item.id === id);
  5038. if (!p) return;
  5039. document.getElementById('modal-bgp-peer-id').value = p.id;
  5040. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5041. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5042. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5043. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5044. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5045. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5046. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5047. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5048. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5049. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5050. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5051. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5052. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5053. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5054. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5055. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5056. }
  5057. function closeBgpPeerModal() {
  5058. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5059. }
  5060. async function submitBgpPeer(e) {
  5061. e.preventDefault();
  5062. const payload = {
  5063. id: document.getElementById('modal-bgp-peer-id').value,
  5064. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5065. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5066. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5067. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5068. password: document.getElementById('modal-bgp-peer-password').value,
  5069. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5070. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5071. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5072. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5073. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5074. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5075. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5076. };
  5077. try {
  5078. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5079. method: 'POST',
  5080. headers: { 'Content-Type': 'application/json' },
  5081. body: JSON.stringify(payload)
  5082. });
  5083. if (res.ok) {
  5084. closeBgpPeerModal();
  5085. showToast('Success', 'BGP Peer saved', 'success');
  5086. loadDynamicRouting();
  5087. } else {
  5088. const err = await res.json();
  5089. showToast('Error', err.error || 'Failed to save peer', 'error');
  5090. }
  5091. } catch (err) {
  5092. showToast('Error', err.message, 'error');
  5093. }
  5094. }
  5095. async function deleteBgpPeer(id) {
  5096. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5097. try {
  5098. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5099. if (res.ok) {
  5100. showToast('Deleted', 'BGP peer removed', 'success');
  5101. loadDynamicRouting();
  5102. }
  5103. } catch (err) {
  5104. showToast('Error', err.message, 'error');
  5105. }
  5106. }
  5107. async function toggleBgpPeerState(id, disabled) {
  5108. try {
  5109. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5110. method: 'POST',
  5111. headers: { 'Content-Type': 'application/json' },
  5112. body: JSON.stringify({ disabled })
  5113. });
  5114. if (res.ok) {
  5115. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5116. loadDynamicRouting();
  5117. }
  5118. } catch (err) {
  5119. showToast('Error', err.message, 'error');
  5120. }
  5121. }
  5122. function openAddBgpNetworkModal() {
  5123. document.getElementById('bgp-network-form').reset();
  5124. document.getElementById('modal-bgp-net-id').value = '';
  5125. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5126. }
  5127. function closeBgpNetworkModal() {
  5128. document.getElementById('bgp-network-modal').classList.add('hidden');
  5129. }
  5130. async function submitBgpNetwork(e) {
  5131. e.preventDefault();
  5132. const payload = {
  5133. id: document.getElementById('modal-bgp-net-id').value,
  5134. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5135. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5136. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5137. };
  5138. try {
  5139. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5140. method: 'POST',
  5141. headers: { 'Content-Type': 'application/json' },
  5142. body: JSON.stringify(payload)
  5143. });
  5144. if (res.ok) {
  5145. closeBgpNetworkModal();
  5146. showToast('Success', 'BGP network advertisement saved', 'success');
  5147. loadDynamicRouting();
  5148. } else {
  5149. const err = await res.json();
  5150. showToast('Error', err.error || 'Failed to save network', 'error');
  5151. }
  5152. } catch (err) {
  5153. showToast('Error', err.message, 'error');
  5154. }
  5155. }
  5156. async function deleteBgpNetwork(id) {
  5157. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5158. try {
  5159. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5160. if (res.ok) {
  5161. showToast('Deleted', 'Network advertisement removed', 'success');
  5162. loadDynamicRouting();
  5163. }
  5164. } catch (err) {
  5165. showToast('Error', err.message, 'error');
  5166. }
  5167. }
  5168. // OSPF Modals & Actions
  5169. function openOspfInstanceModal() {
  5170. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5171. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5172. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5173. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5174. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5175. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5176. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5177. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5178. }
  5179. function closeOspfInstanceModal() {
  5180. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5181. }
  5182. async function submitOspfInstance(e) {
  5183. e.preventDefault();
  5184. const payload = {
  5185. enabled: document.getElementById('modal-ospf-enabled').checked,
  5186. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5187. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5188. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5189. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5190. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5191. };
  5192. try {
  5193. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5194. method: 'POST',
  5195. headers: { 'Content-Type': 'application/json' },
  5196. body: JSON.stringify(payload)
  5197. });
  5198. if (res.ok) {
  5199. closeOspfInstanceModal();
  5200. showToast('Success', 'OSPF instance configuration updated', 'success');
  5201. loadDynamicRouting();
  5202. } else {
  5203. const err = await res.json();
  5204. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5205. }
  5206. } catch (err) {
  5207. showToast('Error', err.message, 'error');
  5208. }
  5209. }
  5210. function openAddOspfAreaModal() {
  5211. document.getElementById('ospf-area-form').reset();
  5212. document.getElementById('modal-ospf-area-id').value = '';
  5213. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5214. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5215. }
  5216. function closeOspfAreaModal() {
  5217. document.getElementById('ospf-area-modal').classList.add('hidden');
  5218. }
  5219. async function submitOspfArea(e) {
  5220. e.preventDefault();
  5221. const payload = {
  5222. id: document.getElementById('modal-ospf-area-id').value,
  5223. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5224. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5225. area_type: document.getElementById('modal-ospf-area-type').value,
  5226. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5227. };
  5228. try {
  5229. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5230. method: 'POST',
  5231. headers: { 'Content-Type': 'application/json' },
  5232. body: JSON.stringify(payload)
  5233. });
  5234. if (res.ok) {
  5235. closeOspfAreaModal();
  5236. showToast('Success', 'OSPF area saved', 'success');
  5237. loadDynamicRouting();
  5238. } else {
  5239. const err = await res.json();
  5240. showToast('Error', err.error || 'Failed to save area', 'error');
  5241. }
  5242. } catch (err) {
  5243. showToast('Error', err.message, 'error');
  5244. }
  5245. }
  5246. async function deleteOspfArea(id) {
  5247. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5248. try {
  5249. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5250. if (res.ok) {
  5251. showToast('Deleted', 'OSPF area removed', 'success');
  5252. loadDynamicRouting();
  5253. }
  5254. } catch (err) {
  5255. showToast('Error', err.message, 'error');
  5256. }
  5257. }
  5258. function populateOspfInterfaceDevices() {
  5259. const select = document.getElementById('modal-ospf-iface-device');
  5260. if (!select) return;
  5261. const current = select.value;
  5262. select.innerHTML = '<option value="">Any matching interface</option>';
  5263. (state.interfaces || []).forEach(iface => {
  5264. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5265. });
  5266. if (current) select.value = current;
  5267. }
  5268. function openAddOspfInterfaceModal() {
  5269. document.getElementById('ospf-interface-form').reset();
  5270. document.getElementById('modal-ospf-iface-id').value = '';
  5271. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5272. document.getElementById('modal-ospf-iface-cost').value = '10';
  5273. document.getElementById('modal-ospf-iface-priority').value = '1';
  5274. document.getElementById('modal-ospf-iface-hello').value = '10';
  5275. document.getElementById('modal-ospf-iface-dead').value = '40';
  5276. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5277. populateOspfInterfaceDevices();
  5278. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5279. }
  5280. function openEditOspfInterfaceModal(id) {
  5281. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5282. if (!item) return;
  5283. populateOspfInterfaceDevices();
  5284. document.getElementById('modal-ospf-iface-id').value = item.id;
  5285. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5286. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5287. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5288. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5289. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5290. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5291. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5292. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5293. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5294. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5295. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5296. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5297. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5298. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5299. }
  5300. function closeOspfInterfaceModal() {
  5301. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5302. }
  5303. async function submitOspfInterface(e) {
  5304. e.preventDefault();
  5305. const payload = {
  5306. id: document.getElementById('modal-ospf-iface-id').value,
  5307. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5308. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5309. interface: document.getElementById('modal-ospf-iface-device').value,
  5310. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5311. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5312. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5313. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5314. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5315. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5316. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5317. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5318. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5319. };
  5320. try {
  5321. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5322. method: 'POST',
  5323. headers: { 'Content-Type': 'application/json' },
  5324. body: JSON.stringify(payload)
  5325. });
  5326. if (res.ok) {
  5327. closeOspfInterfaceModal();
  5328. showToast('Success', 'OSPF interface template saved', 'success');
  5329. loadDynamicRouting();
  5330. } else {
  5331. const err = await res.json();
  5332. showToast('Error', err.error || 'Failed to save interface', 'error');
  5333. }
  5334. } catch (err) {
  5335. showToast('Error', err.message, 'error');
  5336. }
  5337. }
  5338. async function deleteOspfInterface(id) {
  5339. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5340. try {
  5341. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5342. if (res.ok) {
  5343. showToast('Deleted', 'OSPF interface removed', 'success');
  5344. loadDynamicRouting();
  5345. }
  5346. } catch (err) {
  5347. showToast('Error', err.message, 'error');
  5348. }
  5349. }
  5350. async function toggleOspfInterfaceState(id, disabled) {
  5351. try {
  5352. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5353. method: 'POST',
  5354. headers: { 'Content-Type': 'application/json' },
  5355. body: JSON.stringify({ disabled })
  5356. });
  5357. if (res.ok) {
  5358. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5359. loadDynamicRouting();
  5360. }
  5361. } catch (err) {
  5362. showToast('Error', err.message, 'error');
  5363. }
  5364. }
  5365. // ============================================================================
  5366. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5367. // ============================================================================
  5368. function switchBridgeSubTab(tab) {
  5369. state.bridgeSubTab = tab;
  5370. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5371. tabs.forEach(t => {
  5372. const panel = document.getElementById(`bridge-subtab-${t}`);
  5373. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5374. if (panel) {
  5375. if (t === tab) panel.classList.remove('hidden');
  5376. else panel.classList.add('hidden');
  5377. }
  5378. if (btn) {
  5379. if (t === tab) {
  5380. 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';
  5381. } else {
  5382. 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';
  5383. }
  5384. }
  5385. });
  5386. const addBtn = document.getElementById('bridge-top-action-btn');
  5387. if (addBtn) {
  5388. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5389. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5390. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5391. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5392. }
  5393. if (tab === 'hosts') loadBridgeHosts();
  5394. }
  5395. function openCurrentBridgeModal() {
  5396. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5397. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5398. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5399. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5400. }
  5401. async function loadBridge() {
  5402. try {
  5403. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5404. fetch(`${API_BASE}/bridge/bridges`),
  5405. fetch(`${API_BASE}/bridge/ports`),
  5406. fetch(`${API_BASE}/bridge/vlans`),
  5407. fetch(`${API_BASE}/bridge/summary`),
  5408. fetch(`${API_BASE}/vpn/eoip`),
  5409. fetch(`${API_BASE}/vlans`)
  5410. ]);
  5411. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5412. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5413. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5414. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5415. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5416. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5417. // Badges & Stats
  5418. const bBridges = document.getElementById('bridge-badge-bridges');
  5419. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5420. const bPorts = document.getElementById('bridge-badge-ports');
  5421. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5422. const bVlans = document.getElementById('bridge-badge-vlans');
  5423. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5424. const bHosts = document.getElementById('bridge-badge-hosts');
  5425. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5426. const sBr = document.getElementById('bridge-stat-bridges');
  5427. if (sBr) sBr.innerText = (state.bridges || []).length;
  5428. const sPorts = document.getElementById('bridge-stat-ports');
  5429. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5430. const sHosts = document.getElementById('bridge-stat-hosts');
  5431. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5432. renderBridges();
  5433. renderBridgePorts();
  5434. renderBridgeVLANs();
  5435. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5436. } catch (err) {
  5437. console.error('Failed to load bridge subsystem:', err);
  5438. }
  5439. }
  5440. // ----------------- Bridges -----------------
  5441. function renderBridges() {
  5442. const tbody = document.getElementById('bridge-table-body');
  5443. const empty = document.getElementById('bridge-empty-bridges');
  5444. const countBadge = document.getElementById('bridge-count-badge');
  5445. if (!tbody) return;
  5446. tbody.innerHTML = '';
  5447. const bridges = state.bridges || [];
  5448. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5449. if (bridges.length === 0) {
  5450. empty?.classList.remove('hidden');
  5451. return;
  5452. }
  5453. empty?.classList.add('hidden');
  5454. bridges.forEach((b, idx) => {
  5455. const tr = document.createElement('tr');
  5456. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5457. // Format IP addresses pill list
  5458. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5459. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5460. ipsHtml = b.ip_addresses.map(ip => `
  5461. <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">
  5462. <span>${ip}</span>
  5463. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5464. </span>
  5465. `).join(' ');
  5466. }
  5467. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5468. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5469. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5470. tr.innerHTML = `
  5471. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5472. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5473. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5474. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5475. </td>
  5476. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5477. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5478. <td class="py-2.5 px-3">
  5479. <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>
  5480. </td>
  5481. <td class="py-2.5 px-3 text-center">
  5482. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5483. </td>
  5484. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5485. <td class="py-2.5 px-3">
  5486. <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>
  5487. </td>
  5488. <td class="py-2.5 px-3">
  5489. <div class="flex items-center gap-1.5 flex-wrap">
  5490. ${ipsHtml}
  5491. <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>
  5492. </div>
  5493. </td>
  5494. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5495. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5496. </td>
  5497. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5498. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5499. <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>
  5500. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5501. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5502. </td>
  5503. `;
  5504. tbody.appendChild(tr);
  5505. });
  5506. }
  5507. function openAddBridgeModal() {
  5508. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5509. document.getElementById('bridge-modal-id').value = '';
  5510. document.getElementById('bridge-modal-name').value = 'bridge1';
  5511. document.getElementById('bridge-modal-name').disabled = false;
  5512. document.getElementById('bridge-modal-mtu').value = '1500';
  5513. document.getElementById('bridge-modal-mac').value = '';
  5514. document.getElementById('bridge-modal-stp').value = 'rstp';
  5515. document.getElementById('bridge-modal-priority').value = '32768';
  5516. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5517. document.getElementById('bridge-modal-pvid').value = '1';
  5518. document.getElementById('bridge-modal-fastforward').checked = true;
  5519. document.getElementById('bridge-modal-comment').value = '';
  5520. document.getElementById('bridge-modal-disabled').checked = false;
  5521. toggleBridgeModalVlanFiltering();
  5522. document.getElementById('bridge-modal').classList.remove('hidden');
  5523. }
  5524. function openEditBridgeModal(id) {
  5525. const b = (state.bridges || []).find(x => x.id === id);
  5526. if (!b) return;
  5527. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5528. document.getElementById('bridge-modal-id').value = b.id;
  5529. document.getElementById('bridge-modal-name').value = b.name;
  5530. document.getElementById('bridge-modal-name').disabled = true;
  5531. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5532. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5533. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5534. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5535. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5536. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5537. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5538. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5539. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5540. toggleBridgeModalVlanFiltering();
  5541. document.getElementById('bridge-modal').classList.remove('hidden');
  5542. }
  5543. function closeBridgeModal() {
  5544. document.getElementById('bridge-modal').classList.add('hidden');
  5545. }
  5546. function toggleBridgeModalVlanFiltering() {
  5547. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5548. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5549. if (pvidBox) {
  5550. if (chk) pvidBox.classList.remove('opacity-40');
  5551. else pvidBox.classList.add('opacity-40');
  5552. }
  5553. }
  5554. async function submitSaveBridge(e) {
  5555. e.preventDefault();
  5556. const id = document.getElementById('bridge-modal-id').value;
  5557. const name = document.getElementById('bridge-modal-name').value.trim();
  5558. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5559. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5560. const stp = document.getElementById('bridge-modal-stp').value;
  5561. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5562. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5563. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5564. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5565. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5566. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5567. try {
  5568. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5569. method: 'POST',
  5570. headers: { 'Content-Type': 'application/json' },
  5571. body: JSON.stringify({
  5572. id,
  5573. name,
  5574. mtu,
  5575. mac_address: mac,
  5576. stp,
  5577. priority,
  5578. vlan_filtering: vlanFiltering,
  5579. pvid,
  5580. fast_forward: fastForward,
  5581. comment,
  5582. disabled
  5583. })
  5584. });
  5585. if (res.ok) {
  5586. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5587. closeBridgeModal();
  5588. loadBridge();
  5589. fetchData(false);
  5590. } else {
  5591. const err = await res.json();
  5592. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5593. }
  5594. } catch (err) {
  5595. showToast('Error', err.message, 'error');
  5596. }
  5597. }
  5598. async function toggleBridgeState(id, disabled) {
  5599. try {
  5600. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5601. method: 'POST',
  5602. headers: { 'Content-Type': 'application/json' },
  5603. body: JSON.stringify({ disabled })
  5604. });
  5605. if (res.ok) {
  5606. loadBridge();
  5607. fetchData(false);
  5608. }
  5609. } catch (err) {
  5610. showToast('Error', err.message, 'error');
  5611. }
  5612. }
  5613. async function deleteBridge(id) {
  5614. const b = (state.bridges || []).find(x => x.id === id);
  5615. const name = b ? b.name : id;
  5616. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5617. try {
  5618. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5619. if (res.ok) {
  5620. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5621. loadBridge();
  5622. fetchData(false);
  5623. } else {
  5624. const err = await res.json();
  5625. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5626. }
  5627. } catch (err) {
  5628. showToast('Error', err.message, 'error');
  5629. }
  5630. }
  5631. // ----------------- Bridge IP Assignments -----------------
  5632. function openAddBridgeIPModal(id, name) {
  5633. document.getElementById('bridge-ip-modal-id').value = id;
  5634. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5635. document.getElementById('bridge-ip-modal-cidr').value = '';
  5636. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5637. }
  5638. function closeBridgeIPModal() {
  5639. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5640. }
  5641. async function submitAddBridgeIP(e) {
  5642. e.preventDefault();
  5643. const id = document.getElementById('bridge-ip-modal-id').value;
  5644. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5645. try {
  5646. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5647. method: 'POST',
  5648. headers: { 'Content-Type': 'application/json' },
  5649. body: JSON.stringify({ ip })
  5650. });
  5651. if (res.ok) {
  5652. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5653. closeBridgeIPModal();
  5654. loadBridge();
  5655. fetchData(false);
  5656. } else {
  5657. const err = await res.json();
  5658. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5659. }
  5660. } catch (err) {
  5661. showToast('Error', err.message, 'error');
  5662. }
  5663. }
  5664. async function deleteBridgeIP(id, ip) {
  5665. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5666. try {
  5667. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5668. method: 'DELETE',
  5669. headers: { 'Content-Type': 'application/json' },
  5670. body: JSON.stringify({ ip })
  5671. });
  5672. if (res.ok) {
  5673. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5674. loadBridge();
  5675. fetchData(false);
  5676. }
  5677. } catch (err) {
  5678. showToast('Error', err.message, 'error');
  5679. }
  5680. }
  5681. // ----------------- Bridge Ports -----------------
  5682. function renderBridgePorts() {
  5683. const tbody = document.getElementById('bridge-ports-table-body');
  5684. const empty = document.getElementById('bridge-empty-ports');
  5685. const countBadge = document.getElementById('bridge-ports-count-badge');
  5686. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5687. if (!tbody) return;
  5688. tbody.innerHTML = '';
  5689. // Update filter select
  5690. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5691. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5692. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5693. if (ports.length === 0) {
  5694. empty?.classList.remove('hidden');
  5695. return;
  5696. }
  5697. empty?.classList.add('hidden');
  5698. ports.forEach((p, idx) => {
  5699. const tr = document.createElement('tr');
  5700. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5701. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5702. tr.innerHTML = `
  5703. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5704. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5705. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5706. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5707. </td>
  5708. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5709. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5710. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5711. <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>
  5712. <td class="py-2.5 px-3">
  5713. ${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>'}
  5714. </td>
  5715. <td class="py-2.5 px-3">
  5716. <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>
  5717. </td>
  5718. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5719. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5720. <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>
  5721. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5722. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5723. </td>
  5724. `;
  5725. tbody.appendChild(tr);
  5726. });
  5727. }
  5728. function openAddBridgePortModal() {
  5729. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5730. document.getElementById('bridge-port-modal-id').value = '';
  5731. populateBridgeSelect('bridge-port-modal-bridge');
  5732. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5733. document.getElementById('bridge-port-modal-pvid').value = '1';
  5734. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5735. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5736. document.getElementById('bridge-port-modal-horizon').value = '0';
  5737. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5738. document.getElementById('bridge-port-modal-priority').value = '128';
  5739. document.getElementById('bridge-port-modal-learn').checked = true;
  5740. document.getElementById('bridge-port-modal-comment').value = '';
  5741. document.getElementById('bridge-port-modal-disabled').checked = false;
  5742. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5743. }
  5744. function openEditBridgePortModal(id) {
  5745. const p = (state.bridgePorts || []).find(x => x.id === id);
  5746. if (!p) return;
  5747. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5748. document.getElementById('bridge-port-modal-id').value = p.id;
  5749. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5750. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5751. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5752. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5753. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5754. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5755. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5756. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5757. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5758. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5759. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5760. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5761. }
  5762. function closeBridgePortModal() {
  5763. document.getElementById('bridge-port-modal').classList.add('hidden');
  5764. }
  5765. async function submitSaveBridgePort(e) {
  5766. e.preventDefault();
  5767. const id = document.getElementById('bridge-port-modal-id').value;
  5768. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5769. const iface = document.getElementById('bridge-port-modal-interface').value;
  5770. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5771. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5772. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5773. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5774. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5775. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5776. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5777. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5778. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5779. try {
  5780. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5781. method: 'POST',
  5782. headers: { 'Content-Type': 'application/json' },
  5783. body: JSON.stringify({
  5784. id,
  5785. bridge,
  5786. interface: iface,
  5787. pvid,
  5788. frame_types: frameTypes,
  5789. ingress_filtering: ingressFiltering,
  5790. horizon,
  5791. path_cost: pathCost,
  5792. priority,
  5793. learn,
  5794. comment,
  5795. disabled
  5796. })
  5797. });
  5798. if (res.ok) {
  5799. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5800. closeBridgePortModal();
  5801. loadBridge();
  5802. fetchData(false);
  5803. } else {
  5804. const err = await res.json();
  5805. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5806. }
  5807. } catch (err) {
  5808. showToast('Error', err.message, 'error');
  5809. }
  5810. }
  5811. async function toggleBridgePortState(id, disabled) {
  5812. try {
  5813. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5814. method: 'POST',
  5815. headers: { 'Content-Type': 'application/json' },
  5816. body: JSON.stringify({ disabled })
  5817. });
  5818. if (res.ok) {
  5819. loadBridge();
  5820. fetchData(false);
  5821. }
  5822. } catch (err) {
  5823. showToast('Error', err.message, 'error');
  5824. }
  5825. }
  5826. async function deleteBridgePort(id) {
  5827. const p = (state.bridgePorts || []).find(x => x.id === id);
  5828. const iface = p ? p.interface : id;
  5829. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5830. try {
  5831. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5832. if (res.ok) {
  5833. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5834. loadBridge();
  5835. fetchData(false);
  5836. }
  5837. } catch (err) {
  5838. showToast('Error', err.message, 'error');
  5839. }
  5840. }
  5841. // ----------------- Bridge VLANs -----------------
  5842. function renderBridgeVLANs() {
  5843. const tbody = document.getElementById('bridge-vlans-table-body');
  5844. const empty = document.getElementById('bridge-empty-vlans');
  5845. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5846. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5847. if (!tbody) return;
  5848. tbody.innerHTML = '';
  5849. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5850. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5851. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5852. if (vlans.length === 0) {
  5853. empty?.classList.remove('hidden');
  5854. return;
  5855. }
  5856. empty?.classList.add('hidden');
  5857. vlans.forEach((v, idx) => {
  5858. const tr = document.createElement('tr');
  5859. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5860. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5861. ? 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(' ')
  5862. : '<span class="text-slate-600">none</span>';
  5863. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5864. ? 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(' ')
  5865. : '<span class="text-slate-600">none</span>';
  5866. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5867. tr.innerHTML = `
  5868. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5869. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5870. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5871. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5872. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5873. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5874. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5875. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5876. <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>
  5877. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5878. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5879. </td>
  5880. `;
  5881. tbody.appendChild(tr);
  5882. });
  5883. }
  5884. function openAddBridgeVLANModal() {
  5885. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5886. document.getElementById('bridge-vlan-modal-id').value = '';
  5887. populateBridgeSelect('bridge-vlan-modal-bridge');
  5888. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5889. document.getElementById('bridge-vlan-modal-comment').value = '';
  5890. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5891. updateBridgeVlanPortCheckboxes();
  5892. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5893. }
  5894. function openEditBridgeVLANModal(id) {
  5895. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5896. if (!v) return;
  5897. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5898. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5899. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5900. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5901. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5902. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5903. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5904. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5905. }
  5906. function closeBridgeVlanModal() {
  5907. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5908. }
  5909. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5910. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5911. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5912. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5913. if (!taggedBox || !untaggedBox) return;
  5914. // Ports belonging to the selected bridge
  5915. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5916. if (memberPorts.length === 0) {
  5917. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5918. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5919. return;
  5920. }
  5921. taggedBox.innerHTML = memberPorts.map(p => `
  5922. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5923. <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">
  5924. <span>${p.interface}</span>
  5925. </label>
  5926. `).join('');
  5927. untaggedBox.innerHTML = memberPorts.map(p => `
  5928. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5929. <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">
  5930. <span>${p.interface}</span>
  5931. </label>
  5932. `).join('');
  5933. }
  5934. async function submitSaveBridgeVLAN(e) {
  5935. e.preventDefault();
  5936. const id = document.getElementById('bridge-vlan-modal-id').value;
  5937. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5938. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5939. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5940. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5941. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5942. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5943. try {
  5944. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5945. method: 'POST',
  5946. headers: { 'Content-Type': 'application/json' },
  5947. body: JSON.stringify({
  5948. id,
  5949. bridge,
  5950. vlan_ids: vlanIDs,
  5951. tagged,
  5952. untagged,
  5953. comment,
  5954. disabled
  5955. })
  5956. });
  5957. if (res.ok) {
  5958. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5959. closeBridgeVlanModal();
  5960. loadBridge();
  5961. } else {
  5962. const err = await res.json();
  5963. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5964. }
  5965. } catch (err) {
  5966. showToast('Error', err.message, 'error');
  5967. }
  5968. }
  5969. async function toggleBridgeVLANState(id, disabled) {
  5970. try {
  5971. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5972. method: 'POST',
  5973. headers: { 'Content-Type': 'application/json' },
  5974. body: JSON.stringify({ disabled })
  5975. });
  5976. if (res.ok) loadBridge();
  5977. } catch (err) {
  5978. showToast('Error', err.message, 'error');
  5979. }
  5980. }
  5981. async function deleteBridgeVLAN(id) {
  5982. if (!confirm('Delete this bridge VLAN entry?')) return;
  5983. try {
  5984. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5985. if (res.ok) {
  5986. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5987. loadBridge();
  5988. }
  5989. } catch (err) {
  5990. showToast('Error', err.message, 'error');
  5991. }
  5992. }
  5993. // ----------------- Hosts / MAC Table -----------------
  5994. async function loadBridgeHosts() {
  5995. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5996. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5997. try {
  5998. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5999. const res = await fetch(url);
  6000. if (res.ok) {
  6001. state.bridgeHosts = await res.json();
  6002. renderBridgeHosts();
  6003. }
  6004. } catch (err) {
  6005. console.error('Failed to load bridge hosts:', err);
  6006. }
  6007. }
  6008. function renderBridgeHosts() {
  6009. const tbody = document.getElementById('bridge-hosts-table-body');
  6010. const empty = document.getElementById('bridge-empty-hosts');
  6011. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6012. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6013. if (!tbody) return;
  6014. tbody.innerHTML = '';
  6015. const hosts = (state.bridgeHosts || []).filter(h => {
  6016. if (!search) return true;
  6017. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6018. });
  6019. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6020. if (hosts.length === 0) {
  6021. empty?.classList.remove('hidden');
  6022. return;
  6023. }
  6024. empty?.classList.add('hidden');
  6025. hosts.forEach(h => {
  6026. const tr = document.createElement('tr');
  6027. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6028. let flagBadges = '';
  6029. 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>';
  6030. 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>';
  6031. 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>';
  6032. tr.innerHTML = `
  6033. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6034. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6035. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6036. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6037. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6038. <td class="py-2.5 px-3">${flagBadges}</td>
  6039. `;
  6040. tbody.appendChild(tr);
  6041. });
  6042. }
  6043. async function flushBridgeHosts() {
  6044. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6045. if (!selBridge) {
  6046. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6047. return;
  6048. }
  6049. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6050. try {
  6051. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6052. method: 'POST',
  6053. headers: { 'Content-Type': 'application/json' },
  6054. body: JSON.stringify({ bridge: selBridge })
  6055. });
  6056. if (res.ok) {
  6057. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6058. loadBridgeHosts();
  6059. }
  6060. } catch (err) {
  6061. showToast('Error', err.message, 'error');
  6062. }
  6063. }
  6064. // ----------------- Helpers -----------------
  6065. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6066. const sel = document.getElementById(selectId);
  6067. if (!sel) return;
  6068. const prevVal = currentVal || sel.value;
  6069. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6070. (state.bridges || []).forEach(b => {
  6071. const opt = document.createElement('option');
  6072. opt.value = b.name;
  6073. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6074. if (b.name === prevVal) opt.selected = true;
  6075. sel.appendChild(opt);
  6076. });
  6077. }
  6078. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6079. const sel = document.getElementById(selectId);
  6080. if (!sel) return;
  6081. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6082. // 1. Physical Interfaces
  6083. const grpPhys = document.createElement('optgroup');
  6084. grpPhys.label = 'Physical Interfaces';
  6085. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6086. const opt = document.createElement('option');
  6087. opt.value = i.name;
  6088. opt.innerText = `${i.name} (${i.role || i.type})`;
  6089. if (i.name === currentVal) opt.selected = true;
  6090. grpPhys.appendChild(opt);
  6091. });
  6092. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6093. // 2. VLAN Sub-interfaces
  6094. const grpVlans = document.createElement('optgroup');
  6095. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6096. (state.vlans || []).forEach(v => {
  6097. const opt = document.createElement('option');
  6098. opt.value = v.name;
  6099. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6100. if (v.name === currentVal) opt.selected = true;
  6101. grpVlans.appendChild(opt);
  6102. });
  6103. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6104. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6105. const grpEoip = document.createElement('optgroup');
  6106. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6107. (state.eoipTunnels || []).forEach(t => {
  6108. const opt = document.createElement('option');
  6109. opt.value = t.name;
  6110. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6111. if (t.name === currentVal) opt.selected = true;
  6112. grpEoip.appendChild(opt);
  6113. });
  6114. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6115. }
  6116. // -------------------------------------------------------------
  6117. // Routing Filters Management (/routing filter)
  6118. // -------------------------------------------------------------
  6119. function renderRoutingFilters() {
  6120. const tbody = document.getElementById('routing-filters-table-body');
  6121. if (!tbody) return;
  6122. const empty = document.getElementById('routing-filters-empty');
  6123. const countBadge = document.getElementById('routing-filters-count-badge');
  6124. const navBadge = document.getElementById('badge-filters-count');
  6125. const chainSelect = document.getElementById('routing-filter-chain-select');
  6126. const allRules = state.routingFilters || [];
  6127. if (navBadge) navBadge.innerText = allRules.length;
  6128. // Populate chain filter select options dynamically
  6129. if (chainSelect) {
  6130. const currentVal = state.filterChainSelected || 'all';
  6131. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6132. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6133. uniqueChains.map(ch => {
  6134. const count = allRules.filter(r => r.chain === ch).length;
  6135. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6136. }).join('');
  6137. chainSelect.value = currentVal;
  6138. }
  6139. // Filter rules by selected chain
  6140. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6141. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6142. : allRules.slice();
  6143. // Sort by chain then rule_order
  6144. filteredRules.sort((a, b) => {
  6145. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6146. return (a.rule_order || 0) - (b.rule_order || 0);
  6147. });
  6148. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6149. if (filteredRules.length === 0) {
  6150. tbody.innerHTML = '';
  6151. if (empty) empty.classList.remove('hidden');
  6152. return;
  6153. }
  6154. if (empty) empty.classList.add('hidden');
  6155. tbody.innerHTML = filteredRules.map(r => {
  6156. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6157. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6158. let actionBadge = '';
  6159. if (r.action === 'accept') {
  6160. 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>';
  6161. } else if (r.action === 'discard') {
  6162. 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>';
  6163. } else if (r.action === 'reject') {
  6164. 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>';
  6165. } else {
  6166. 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>`;
  6167. }
  6168. // Prefix match
  6169. let matchPfx = '';
  6170. if (r.prefix) {
  6171. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6172. if (r.prefix_len) {
  6173. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6174. }
  6175. } else {
  6176. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6177. }
  6178. // Other matches
  6179. const matchExtra = [];
  6180. if (r.match_protocol && r.match_protocol !== 'any') {
  6181. 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>`);
  6182. }
  6183. if (r.match_as_path) {
  6184. 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>`);
  6185. }
  6186. if (r.match_community) {
  6187. 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>`);
  6188. }
  6189. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6190. // Set modifications
  6191. const setBadges = [];
  6192. if (r.set_local_pref > 0) {
  6193. 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>`);
  6194. }
  6195. if (r.set_metric > 0) {
  6196. 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>`);
  6197. }
  6198. if (r.set_as_prepend > 0) {
  6199. 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>`);
  6200. }
  6201. if (r.set_community) {
  6202. 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>`);
  6203. }
  6204. if (r.set_next_hop) {
  6205. 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>`);
  6206. }
  6207. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6208. return `
  6209. <tr class="hover:bg-slate-800/40 transition">
  6210. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6211. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6212. <td class="py-2.5 px-3">
  6213. <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>
  6214. </td>
  6215. <td class="py-2.5 px-3">${actionBadge}</td>
  6216. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6217. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6218. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6219. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6220. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6221. <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'}">
  6222. ${r.disabled ? 'Enable' : 'Disable'}
  6223. </button>
  6224. <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">
  6225. Edit
  6226. </button>
  6227. <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">
  6228. Delete
  6229. </button>
  6230. </td>
  6231. </tr>
  6232. `;
  6233. }).join('');
  6234. }
  6235. function filterRoutingFiltersByChain(chain) {
  6236. state.filterChainSelected = chain;
  6237. renderRoutingFilters();
  6238. }
  6239. function openAddRoutingFilterModal(defaultChain = '') {
  6240. const form = document.getElementById('routing-filter-form');
  6241. if (form) form.reset();
  6242. const idEl = document.getElementById('modal-rf-id');
  6243. if (idEl) idEl.value = '';
  6244. const titleEl = document.getElementById('modal-rf-title');
  6245. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6246. const chainEl = document.getElementById('modal-rf-chain');
  6247. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6248. const orderEl = document.getElementById('modal-rf-order');
  6249. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6250. const actEl = document.getElementById('modal-rf-action');
  6251. if (actEl) actEl.value = 'accept';
  6252. const protoEl = document.getElementById('modal-rf-protocol');
  6253. if (protoEl) protoEl.value = 'any';
  6254. const disEl = document.getElementById('modal-rf-disabled');
  6255. if (disEl) disEl.checked = false;
  6256. const modal = document.getElementById('modal-routing-filter');
  6257. if (modal) modal.classList.remove('hidden');
  6258. }
  6259. function openEditRoutingFilterModal(id) {
  6260. const r = (state.routingFilters || []).find(item => item.id === id);
  6261. if (!r) return;
  6262. const idEl = document.getElementById('modal-rf-id');
  6263. if (idEl) idEl.value = r.id;
  6264. const titleEl = document.getElementById('modal-rf-title');
  6265. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6266. const chainEl = document.getElementById('modal-rf-chain');
  6267. if (chainEl) chainEl.value = r.chain || '';
  6268. const orderEl = document.getElementById('modal-rf-order');
  6269. if (orderEl) orderEl.value = r.rule_order || 10;
  6270. const actEl = document.getElementById('modal-rf-action');
  6271. if (actEl) actEl.value = r.action || 'accept';
  6272. const pfxEl = document.getElementById('modal-rf-prefix');
  6273. if (pfxEl) pfxEl.value = r.prefix || '';
  6274. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6275. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6276. const protoEl = document.getElementById('modal-rf-protocol');
  6277. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6278. const aspEl = document.getElementById('modal-rf-as-path');
  6279. if (aspEl) aspEl.value = r.match_as_path || '';
  6280. const commEl = document.getElementById('modal-rf-community');
  6281. if (commEl) commEl.value = r.match_community || '';
  6282. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6283. if (lpEl) lpEl.value = r.set_local_pref || '';
  6284. const metEl = document.getElementById('modal-rf-set-metric');
  6285. if (metEl) metEl.value = r.set_metric || '';
  6286. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6287. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6288. const setCommEl = document.getElementById('modal-rf-set-community');
  6289. if (setCommEl) setCommEl.value = r.set_community || '';
  6290. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6291. if (nhEl) nhEl.value = r.set_next_hop || '';
  6292. const comEl = document.getElementById('modal-rf-comment');
  6293. if (comEl) comEl.value = r.comment || '';
  6294. const disEl = document.getElementById('modal-rf-disabled');
  6295. if (disEl) disEl.checked = !!r.disabled;
  6296. const modal = document.getElementById('modal-routing-filter');
  6297. if (modal) modal.classList.remove('hidden');
  6298. }
  6299. function closeRoutingFilterModal() {
  6300. const modal = document.getElementById('modal-routing-filter');
  6301. if (modal) modal.classList.add('hidden');
  6302. }
  6303. async function submitRoutingFilter(e) {
  6304. e.preventDefault();
  6305. const payload = {
  6306. id: document.getElementById('modal-rf-id').value,
  6307. chain: document.getElementById('modal-rf-chain').value.trim(),
  6308. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6309. action: document.getElementById('modal-rf-action').value,
  6310. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6311. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6312. match_protocol: document.getElementById('modal-rf-protocol').value,
  6313. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6314. match_community: document.getElementById('modal-rf-community').value.trim(),
  6315. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6316. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6317. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6318. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6319. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6320. comment: document.getElementById('modal-rf-comment').value.trim(),
  6321. disabled: document.getElementById('modal-rf-disabled').checked
  6322. };
  6323. try {
  6324. const res = await fetch(`${API_BASE}/routing/filters`, {
  6325. method: 'POST',
  6326. headers: { 'Content-Type': 'application/json' },
  6327. body: JSON.stringify(payload)
  6328. });
  6329. if (res.ok) {
  6330. closeRoutingFilterModal();
  6331. showToast('Success', 'Routing filter rule saved', 'success');
  6332. loadDynamicRouting();
  6333. } else {
  6334. const err = await res.json();
  6335. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6336. }
  6337. } catch (err) {
  6338. showToast('Error', err.message, 'error');
  6339. }
  6340. }
  6341. async function deleteRoutingFilter(id) {
  6342. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6343. try {
  6344. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6345. if (res.ok) {
  6346. showToast('Deleted', 'Routing filter rule removed', 'info');
  6347. loadDynamicRouting();
  6348. } else {
  6349. const err = await res.json();
  6350. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6351. }
  6352. } catch (err) {
  6353. showToast('Error', err.message, 'error');
  6354. }
  6355. }
  6356. async function toggleRoutingFilterState(id, disabled) {
  6357. try {
  6358. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6359. method: 'POST',
  6360. headers: { 'Content-Type': 'application/json' },
  6361. body: JSON.stringify({ disabled })
  6362. });
  6363. if (res.ok) {
  6364. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6365. loadDynamicRouting();
  6366. } else {
  6367. const err = await res.json();
  6368. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6369. }
  6370. } catch (err) {
  6371. showToast('Error', err.message, 'error');
  6372. }
  6373. }
  6374. // ==========================================
  6375. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6376. // ==========================================
  6377. function loadToolsView() {
  6378. populateToolsInterfaces();
  6379. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6380. }
  6381. function populateToolsInterfaces() {
  6382. const pingSel = document.getElementById('tools-ping-iface');
  6383. const traceSel = document.getElementById('tools-tr-iface');
  6384. let opts = '<option value="">Auto (Default Route)</option>';
  6385. if (Array.isArray(state.interfaces)) {
  6386. state.interfaces.forEach(iface => {
  6387. if (iface.name) {
  6388. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6389. }
  6390. });
  6391. }
  6392. if (pingSel) {
  6393. const cur = pingSel.value;
  6394. pingSel.innerHTML = opts;
  6395. if (cur) pingSel.value = cur;
  6396. }
  6397. if (traceSel) {
  6398. const cur = traceSel.value;
  6399. traceSel.innerHTML = opts;
  6400. if (cur) traceSel.value = cur;
  6401. }
  6402. }
  6403. function switchToolsSubTab(subTab) {
  6404. state.activeToolsSubTab = subTab;
  6405. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6406. tabs.forEach(t => {
  6407. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6408. const view = document.getElementById(`tools-view-${t}`);
  6409. if (btn) {
  6410. if (t === subTab) {
  6411. 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';
  6412. } else {
  6413. 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';
  6414. }
  6415. }
  6416. if (view) {
  6417. if (t === subTab) {
  6418. view.classList.remove('hidden');
  6419. } else {
  6420. view.classList.add('hidden');
  6421. }
  6422. }
  6423. });
  6424. }
  6425. function setPortPreset(port) {
  6426. const input = document.getElementById('tools-port-num');
  6427. if (input) input.value = port;
  6428. }
  6429. async function executePing(e) {
  6430. if (e) e.preventDefault();
  6431. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6432. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6433. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6434. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '5', 10);
  6435. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6436. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6437. if (!target) {
  6438. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6439. return;
  6440. }
  6441. const btn = document.getElementById('tools-ping-btn');
  6442. const spinner = document.getElementById('tools-ping-spinner');
  6443. if (btn) btn.disabled = true;
  6444. if (spinner) spinner.classList.remove('hidden');
  6445. try {
  6446. const res = await fetch(`${API_BASE}/tools/ping`, {
  6447. method: 'POST',
  6448. headers: { 'Content-Type': 'application/json' },
  6449. body: JSON.stringify({
  6450. target,
  6451. count,
  6452. size,
  6453. timeout,
  6454. interface: iface,
  6455. dont_frag: dontFrag
  6456. })
  6457. });
  6458. const data = await res.json();
  6459. if (!res.ok) {
  6460. showToast('Ping Error', data.error || 'Failed to execute ping', 'error');
  6461. return;
  6462. }
  6463. const resCard = document.getElementById('tools-ping-results');
  6464. if (resCard) resCard.classList.remove('hidden');
  6465. const sentEl = document.getElementById('tools-ping-stat-sent');
  6466. if (sentEl) sentEl.innerText = data.packets_sent ?? 0;
  6467. const recvEl = document.getElementById('tools-ping-stat-recv');
  6468. if (recvEl) recvEl.innerText = data.packets_recv ?? 0;
  6469. const lossEl = document.getElementById('tools-ping-stat-loss');
  6470. if (lossEl) {
  6471. const loss = data.packet_loss_pct ?? 0;
  6472. lossEl.innerText = `${loss.toFixed(0)}%`;
  6473. lossEl.className = loss === 0
  6474. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  6475. : (loss < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  6476. }
  6477. const avgEl = document.getElementById('tools-ping-stat-avg');
  6478. if (avgEl) avgEl.innerText = data.avg_rtt_ms ? `${data.avg_rtt_ms.toFixed(2)} ms` : '--';
  6479. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6480. if (minMaxEl) {
  6481. if (data.min_rtt_ms !== undefined && data.max_rtt_ms !== undefined && data.min_rtt_ms > 0) {
  6482. minMaxEl.innerText = `${data.min_rtt_ms.toFixed(1)} / ${data.max_rtt_ms.toFixed(1)} ms`;
  6483. } else {
  6484. minMaxEl.innerText = '--';
  6485. }
  6486. }
  6487. const badge = document.getElementById('tools-ping-status-badge');
  6488. if (badge) {
  6489. if (data.packet_loss_pct === 0) {
  6490. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  6491. badge.innerText = '100% OK';
  6492. } else if (data.packets_recv > 0) {
  6493. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  6494. badge.innerText = `${data.packet_loss_pct}% LOSS`;
  6495. } else {
  6496. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  6497. badge.innerText = 'UNREACHABLE';
  6498. }
  6499. }
  6500. const tbody = document.getElementById('tools-ping-tbody') || document.getElementById('tools-ping-table-body');
  6501. if (tbody) {
  6502. if (Array.isArray(data.replies) && data.replies.length > 0) {
  6503. tbody.innerHTML = data.replies.map(r => `
  6504. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6505. <td class="py-2 px-3 text-slate-300">#${r.seq}</td>
  6506. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(r.from)}</td>
  6507. <td class="py-2 px-3 text-slate-400">${r.bytes} bytes</td>
  6508. <td class="py-2 px-3 text-slate-300">${r.ttl}</td>
  6509. <td class="py-2 px-3 font-bold text-amber-300">${r.time_ms.toFixed(2)} ms</td>
  6510. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  6511. </tr>
  6512. `).join('');
  6513. } else {
  6514. 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>`;
  6515. }
  6516. }
  6517. const rawEl = document.getElementById('tools-ping-raw');
  6518. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6519. showToast('Ping Finished', `Sent ${data.packets_sent}, received ${data.packets_recv} (${data.packet_loss_pct}% loss)`, data.packet_loss_pct === 0 ? 'success' : 'info');
  6520. } catch (err) {
  6521. showToast('Ping Error', err.message, 'error');
  6522. } finally {
  6523. if (btn) btn.disabled = false;
  6524. if (spinner) spinner.classList.add('hidden');
  6525. }
  6526. }
  6527. async function executeTraceroute(e) {
  6528. if (e) e.preventDefault();
  6529. const target = document.getElementById('tools-tr-target')?.value?.trim();
  6530. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  6531. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  6532. const iface = document.getElementById('tools-tr-iface')?.value || '';
  6533. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  6534. if (!target) {
  6535. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6536. return;
  6537. }
  6538. const btn = document.getElementById('tools-tr-btn');
  6539. const spinner = document.getElementById('tools-tr-spinner');
  6540. if (btn) btn.disabled = true;
  6541. if (spinner) spinner.classList.remove('hidden');
  6542. try {
  6543. const res = await fetch(`${API_BASE}/tools/traceroute`, {
  6544. method: 'POST',
  6545. headers: { 'Content-Type': 'application/json' },
  6546. body: JSON.stringify({
  6547. target,
  6548. max_hops: maxHops,
  6549. protocol,
  6550. interface: iface,
  6551. resolve
  6552. })
  6553. });
  6554. const data = await res.json();
  6555. if (!res.ok) {
  6556. showToast('Traceroute Error', data.error || 'Failed to execute traceroute', 'error');
  6557. return;
  6558. }
  6559. const resCard = document.getElementById('tools-tr-results');
  6560. if (resCard) resCard.classList.remove('hidden');
  6561. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  6562. const statHops = document.getElementById('tools-tr-hops-count');
  6563. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  6564. const tbody = document.getElementById('tools-tr-tbody');
  6565. if (tbody) {
  6566. if (hopsCount > 0) {
  6567. tbody.innerHTML = data.hops.map(h => {
  6568. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  6569. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  6570. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  6571. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  6572. return `
  6573. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}">
  6574. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  6575. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  6576. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  6577. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  6578. <td class="py-2.5 px-3 text-right">
  6579. ${isTimeout
  6580. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  6581. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  6582. </td>
  6583. </tr>
  6584. `;
  6585. }).join('');
  6586. } else {
  6587. 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>`;
  6588. }
  6589. }
  6590. const rawEl = document.getElementById('tools-tr-raw');
  6591. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6592. showToast('Traceroute Finished', `Traced ${hopsCount} hops to ${target}`, 'info');
  6593. } catch (err) {
  6594. showToast('Traceroute Error', err.message, 'error');
  6595. } finally {
  6596. if (btn) btn.disabled = false;
  6597. if (spinner) spinner.classList.add('hidden');
  6598. }
  6599. }
  6600. async function executeMTR(e) {
  6601. if (e) e.preventDefault();
  6602. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  6603. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  6604. if (!target) {
  6605. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6606. return;
  6607. }
  6608. const btn = document.getElementById('tools-mtr-btn');
  6609. const spinner = document.getElementById('tools-mtr-spinner');
  6610. if (btn) btn.disabled = true;
  6611. if (spinner) spinner.classList.remove('hidden');
  6612. try {
  6613. const res = await fetch(`${API_BASE}/tools/mtr`, {
  6614. method: 'POST',
  6615. headers: { 'Content-Type': 'application/json' },
  6616. body: JSON.stringify({ target, count: cycles })
  6617. });
  6618. const data = await res.json();
  6619. if (!res.ok) {
  6620. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  6621. return;
  6622. }
  6623. const resCard = document.getElementById('tools-mtr-results');
  6624. if (resCard) resCard.classList.remove('hidden');
  6625. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  6626. const statHops = document.getElementById('tools-mtr-hops-count');
  6627. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  6628. const tbody = document.getElementById('tools-mtr-tbody');
  6629. if (tbody) {
  6630. if (hopsCount > 0) {
  6631. tbody.innerHTML = data.hops.map(h => {
  6632. 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');
  6633. return `
  6634. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6635. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  6636. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  6637. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  6638. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  6639. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  6640. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  6641. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  6642. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  6643. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  6644. </tr>
  6645. `;
  6646. }).join('');
  6647. } else {
  6648. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  6649. }
  6650. }
  6651. const rawEl = document.getElementById('tools-mtr-raw');
  6652. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6653. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  6654. } catch (err) {
  6655. showToast('MTR Error', err.message, 'error');
  6656. } finally {
  6657. if (btn) btn.disabled = false;
  6658. if (spinner) spinner.classList.add('hidden');
  6659. }
  6660. }
  6661. async function executeDNS(e) {
  6662. if (e) e.preventDefault();
  6663. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  6664. const type = document.getElementById('tools-dns-type')?.value || 'A';
  6665. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  6666. if (!domain) {
  6667. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  6668. return;
  6669. }
  6670. const btn = document.getElementById('tools-dns-btn');
  6671. const spinner = document.getElementById('tools-dns-spinner');
  6672. if (btn) btn.disabled = true;
  6673. if (spinner) spinner.classList.remove('hidden');
  6674. try {
  6675. const res = await fetch(`${API_BASE}/tools/dns`, {
  6676. method: 'POST',
  6677. headers: { 'Content-Type': 'application/json' },
  6678. body: JSON.stringify({ domain, type, server })
  6679. });
  6680. const data = await res.json();
  6681. if (!res.ok) {
  6682. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  6683. return;
  6684. }
  6685. const resCard = document.getElementById('tools-dns-results');
  6686. if (resCard) resCard.classList.remove('hidden');
  6687. const metaEl = document.getElementById('tools-dns-meta');
  6688. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  6689. const tbody = document.getElementById('tools-dns-tbody');
  6690. if (tbody) {
  6691. if (Array.isArray(data.records) && data.records.length > 0) {
  6692. tbody.innerHTML = data.records.map(r => `
  6693. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6694. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  6695. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  6696. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  6697. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  6698. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  6699. </tr>
  6700. `).join('');
  6701. } else {
  6702. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  6703. }
  6704. }
  6705. const rawEl = document.getElementById('tools-dns-raw');
  6706. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6707. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  6708. } catch (err) {
  6709. showToast('DNS Error', err.message, 'error');
  6710. } finally {
  6711. if (btn) btn.disabled = false;
  6712. if (spinner) spinner.classList.add('hidden');
  6713. }
  6714. }
  6715. async function executePortProbe(e) {
  6716. if (e) e.preventDefault();
  6717. const target = document.getElementById('tools-port-target')?.value?.trim();
  6718. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  6719. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  6720. if (!target || !port) {
  6721. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  6722. return;
  6723. }
  6724. const btn = document.getElementById('tools-port-btn');
  6725. const spinner = document.getElementById('tools-port-spinner');
  6726. if (btn) btn.disabled = true;
  6727. if (spinner) spinner.classList.remove('hidden');
  6728. try {
  6729. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  6730. method: 'POST',
  6731. headers: { 'Content-Type': 'application/json' },
  6732. body: JSON.stringify({ target, port, timeout })
  6733. });
  6734. const data = await res.json();
  6735. if (!res.ok) {
  6736. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  6737. return;
  6738. }
  6739. const resCard = document.getElementById('tools-port-results');
  6740. if (resCard) resCard.classList.remove('hidden');
  6741. const banner = document.getElementById('tools-port-banner');
  6742. const icon = document.getElementById('tools-port-icon');
  6743. const title = document.getElementById('tools-port-title');
  6744. const sub = document.getElementById('tools-port-sub');
  6745. const latency = document.getElementById('tools-port-latency');
  6746. if (data.open) {
  6747. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  6748. if (icon) {
  6749. 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';
  6750. icon.innerText = '✓';
  6751. }
  6752. if (title) {
  6753. title.className = 'text-sm font-bold text-emerald-300';
  6754. title.innerText = `PORT ${port} OPEN / LISTENING`;
  6755. }
  6756. if (sub) {
  6757. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  6758. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  6759. }
  6760. if (latency) {
  6761. latency.className = 'text-base font-bold font-mono text-emerald-300';
  6762. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  6763. }
  6764. } else {
  6765. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  6766. if (icon) {
  6767. 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';
  6768. icon.innerText = '✕';
  6769. }
  6770. if (title) {
  6771. title.className = 'text-sm font-bold text-rose-300';
  6772. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  6773. }
  6774. if (sub) {
  6775. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  6776. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  6777. }
  6778. if (latency) {
  6779. latency.className = 'text-base font-bold font-mono text-slate-500';
  6780. latency.innerText = '--';
  6781. }
  6782. }
  6783. const rawEl = document.getElementById('tools-port-raw');
  6784. 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'}`);
  6785. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  6786. } catch (err) {
  6787. showToast('Probe Error', err.message, 'error');
  6788. } finally {
  6789. if (btn) btn.disabled = false;
  6790. if (spinner) spinner.classList.add('hidden');
  6791. }
  6792. }