app.js 278 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607
  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. };
  44. const API_BASE = '/api';
  45. // Initialize on page load
  46. document.addEventListener('DOMContentLoaded', () => {
  47. const hash = window.location.hash.replace('#', '') || 'dashboard';
  48. navigate(hash);
  49. fetchData();
  50. // Live polling every 2.5 seconds
  51. setInterval(() => {
  52. if (state.isPolling) {
  53. fetchData(false);
  54. }
  55. }, 2500);
  56. });
  57. // Navigation Handler
  58. function navigate(tabName) {
  59. state.activeTab = tabName;
  60. window.location.hash = tabName;
  61. // Update nav links styling
  62. document.querySelectorAll('.nav-link').forEach(link => {
  63. 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';
  64. });
  65. const activeNav = document.getElementById(`nav-${tabName}`);
  66. if (activeNav) {
  67. 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';
  68. }
  69. // Update page headers
  70. const titles = {
  71. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  72. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  73. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  74. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  75. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  76. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  77. 'dynamic-routing': { title: 'Dynamic Routing (BGP & OSPF)', sub: 'FRRouting BGP peering sessions, advertised networks, and OSPFv2 link-state routing' },
  78. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  79. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  80. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  81. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  82. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  83. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  84. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  85. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  86. };
  87. const header = titles[tabName] || titles.dashboard;
  88. const pTitle = document.getElementById('page-title');
  89. if (pTitle) pTitle.innerText = header.title;
  90. const pSub = document.getElementById('page-subtitle');
  91. if (pSub) pSub.innerText = header.sub;
  92. // Toggle sections dynamically for all section elements
  93. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  94. if (el.id === `section-${tabName}`) {
  95. el.classList.remove('hidden');
  96. } else {
  97. el.classList.add('hidden');
  98. }
  99. });
  100. if (tabName === 'bridge') loadBridge();
  101. if (tabName === 'firewall') loadFirewall();
  102. if (tabName === 'routes') loadRoutes();
  103. if (tabName === 'dynamic-routing') loadDynamicRouting();
  104. if (tabName === 'ppp') loadPPP();
  105. if (tabName === 'eoip') loadEoIP();
  106. if (tabName === 'persistence') loadDebianConfig();
  107. if (tabName === 'pppoe') loadPPPoE();
  108. if (tabName === 'wireguard') loadWireGuard();
  109. if (tabName === 'ipsec') loadIPSec();
  110. if (tabName === 'l2tp') loadL2TP();
  111. if (tabName === 'pptp') loadPPTP();
  112. }
  113. // Fetch all core system, network and VPN telemetry
  114. async function fetchData(isManual = false) {
  115. const spinner = document.getElementById('refresh-spinner');
  116. if (isManual && spinner) spinner.classList.add('animate-spin');
  117. try {
  118. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes] = await Promise.all([
  119. fetch(`${API_BASE}/system/status`),
  120. fetch(`${API_BASE}/interfaces`),
  121. fetch(`${API_BASE}/vlans`),
  122. fetch(`${API_BASE}/vpn/status`),
  123. fetch(`${API_BASE}/firewall/summary`),
  124. fetch(`${API_BASE}/routing/dynamic/summary`),
  125. fetch(`${API_BASE}/bridge/summary`)
  126. ]);
  127. if (brSummaryRes.ok) {
  128. state.bridgeSummary = await brSummaryRes.json();
  129. const bBridge = document.getElementById('badge-bridge-count');
  130. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  131. const sBr = document.getElementById('bridge-stat-bridges');
  132. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  133. const sPorts = document.getElementById('bridge-stat-ports');
  134. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  135. const sHosts = document.getElementById('bridge-stat-hosts');
  136. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  137. }
  138. if (statusRes.ok) state.systemStatus = await statusRes.json();
  139. if (ifacesRes.ok) {
  140. const ifacesData = await ifacesRes.json();
  141. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  142. state.interfaces = rawIfaces.filter(i => {
  143. if (!i.name) return false;
  144. if (i.name.startsWith('ep_')) return false;
  145. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  146. });
  147. }
  148. if (vlansRes.ok) {
  149. const vlansData = await vlansRes.json();
  150. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  151. }
  152. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  153. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  154. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  155. updateSystemMetrics();
  156. updateBadges();
  157. if (state.activeTab === 'dashboard') renderDashboard();
  158. if (state.activeTab === 'interfaces') renderInterfacesList();
  159. if (state.activeTab === 'vlans') renderVlansList();
  160. if (state.activeTab === 'firewall') loadFirewall(false);
  161. if (state.activeTab === 'routes') loadRoutes(false);
  162. if (state.activeTab === 'dynamic-routing') loadDynamicRouting(false);
  163. if (state.activeTab === 'ppp') loadPPP(false);
  164. if (state.activeTab === 'eoip') loadEoIP(false);
  165. if (state.activeTab === 'pppoe') loadPPPoE(false);
  166. if (state.activeTab === 'wireguard') loadWireGuard(false);
  167. if (state.activeTab === 'ipsec') loadIPSec(false);
  168. if (state.activeTab === 'l2tp') loadL2TP(false);
  169. if (state.activeTab === 'pptp') loadPPTP(false);
  170. } catch (err) {
  171. console.error('Failed to fetch router state:', err);
  172. } finally {
  173. if (isManual && spinner) {
  174. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  175. }
  176. }
  177. }
  178. // Update Top KPI and Sidebar Telemetry
  179. function updateSystemMetrics() {
  180. const s = state.systemStatus;
  181. const v = state.vpnStatus;
  182. if (!s) return;
  183. // Sidebar
  184. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  185. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  186. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  187. if (s.cpu_pct !== undefined) {
  188. const pct = s.cpu_pct;
  189. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  190. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  191. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  192. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  193. } else if (s.cpu_load && s.cpu_load.length > 0) {
  194. const cores = s.cpu_cores || 4;
  195. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  196. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  197. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  198. }
  199. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  200. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  201. // Dashboard Stats
  202. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  203. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  204. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  205. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  206. // VPN Status Indicators
  207. if (v) {
  208. const totalActive = v.total_active_tunnels || 0;
  209. const statVpnActive = document.getElementById('stat-vpn-active');
  210. if (statVpnActive) statVpnActive.innerText = totalActive;
  211. const tunnelsDot = document.getElementById('tunnels-dot');
  212. const tunnelsLabel = document.getElementById('tunnels-label');
  213. if (tunnelsDot && tunnelsLabel) {
  214. if (totalActive > 0) {
  215. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  216. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  217. } else {
  218. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  219. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  220. }
  221. }
  222. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  223. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  224. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  225. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  226. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  227. }
  228. // Total Live Bandwidth Rate
  229. let totalRx = 0;
  230. let totalTx = 0;
  231. (state.interfaces || []).forEach(i => {
  232. if (i.rate) {
  233. totalRx += i.rate.rx_bytes_sec || 0;
  234. totalTx += i.rate.tx_bytes_sec || 0;
  235. }
  236. });
  237. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  238. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  239. }
  240. function setDotBadge(id, active) {
  241. const el = document.getElementById(id);
  242. if (!el) return;
  243. if (active) {
  244. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  245. } else {
  246. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  247. }
  248. }
  249. function updateBadges() {
  250. const bIfaces = document.getElementById('badge-ifaces-count');
  251. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  252. const bVlans = document.getElementById('badge-vlans-count');
  253. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  254. if (state.fwSummary) {
  255. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  256. const badgeFw = document.getElementById('badge-firewall-count');
  257. if (badgeFw) badgeFw.innerText = totalFwRules;
  258. }
  259. if (state.vpnStatus) {
  260. const v = state.vpnStatus;
  261. const bEoIP = document.getElementById('badge-eoip-count');
  262. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  263. const bPPPSess = document.getElementById('badge-ppp-sessions');
  264. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  265. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  266. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  267. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  268. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  269. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  270. }
  271. if (state.dynSummary) {
  272. const d = state.dynSummary;
  273. setDotBadge('badge-bgp-dot', d.bgp_running);
  274. setDotBadge('badge-ospf-dot', d.ospf_running);
  275. }
  276. }
  277. // Render Dashboard View
  278. function renderDashboard() {
  279. const matrix = document.getElementById('port-matrix');
  280. matrix.innerHTML = '';
  281. (state.interfaces || []).forEach(iface => {
  282. const isUp = iface.state === 'UP';
  283. const isVlan = iface.is_vlan;
  284. const portCard = document.createElement('div');
  285. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  286. isUp
  287. ? (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')
  288. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  289. }`;
  290. portCard.onclick = () => openIfaceModal(iface.name);
  291. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  292. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  293. portCard.innerHTML = `
  294. <div class="flex items-center justify-between mb-2">
  295. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  296. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  297. </div>
  298. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  299. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  300. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  301. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  302. </div>
  303. `;
  304. matrix.appendChild(portCard);
  305. });
  306. const ifaceTbody = document.getElementById('quick-interfaces-table');
  307. ifaceTbody.innerHTML = '';
  308. (state.interfaces || []).slice(0, 6).forEach(i => {
  309. const isUp = i.state === 'UP';
  310. const tr = document.createElement('tr');
  311. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  312. tr.onclick = () => openIfaceModal(i.name);
  313. tr.innerHTML = `
  314. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  315. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  316. <span>${i.name}</span>
  317. </td>
  318. <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>
  319. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  320. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  321. `;
  322. ifaceTbody.appendChild(tr);
  323. });
  324. const vlanTbody = document.getElementById('quick-vlans-table');
  325. vlanTbody.innerHTML = '';
  326. const vlans = state.vlans || [];
  327. if (vlans.length === 0) {
  328. 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>`;
  329. } else {
  330. vlans.slice(0, 6).forEach(v => {
  331. const tr = document.createElement('tr');
  332. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  333. tr.onclick = () => openIfaceModal(v.name);
  334. tr.innerHTML = `
  335. <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>
  336. <td class="py-2.5 text-white font-bold">${v.name}</td>
  337. <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>
  338. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  339. `;
  340. vlanTbody.appendChild(tr);
  341. });
  342. }
  343. }
  344. // Expand / Collapse Handlers
  345. function toggleExpand(parentName) {
  346. if (state.expandedParents.has(parentName)) {
  347. state.expandedParents.delete(parentName);
  348. } else {
  349. state.expandedParents.add(parentName);
  350. }
  351. renderInterfacesList();
  352. }
  353. function expandAllIfaces(expand) {
  354. if (expand) {
  355. (state.interfaces || []).forEach(i => {
  356. if (!i.is_vlan) state.expandedParents.add(i.name);
  357. });
  358. } else {
  359. state.expandedParents.clear();
  360. }
  361. renderInterfacesList();
  362. }
  363. // Filter and Render Hierarchical Interfaces List
  364. function filterIfaces(filter) {
  365. state.ifaceFilter = filter;
  366. document.querySelectorAll('.filter-btn').forEach(btn => {
  367. 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';
  368. });
  369. const activeBtn = document.getElementById(`filter-${filter}`);
  370. if (activeBtn) {
  371. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  372. }
  373. renderInterfacesList();
  374. }
  375. function renderInterfacesList() {
  376. const tbody = document.getElementById('interfaces-tree-tbody');
  377. const emptyState = document.getElementById('interfaces-empty-state');
  378. const summary = document.getElementById('ifaces-list-summary');
  379. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  380. tbody.innerHTML = '';
  381. const allIfaces = state.interfaces || [];
  382. const allVlans = state.vlans || [];
  383. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  384. const filteredParents = parentIfaces.filter(parent => {
  385. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  386. if (query) {
  387. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  388. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  389. if (!matchParent && !matchVlan) return false;
  390. }
  391. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  392. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  393. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  394. return true;
  395. });
  396. if (summary) {
  397. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  398. }
  399. if (filteredParents.length === 0) {
  400. emptyState?.classList.remove('hidden');
  401. return;
  402. }
  403. emptyState?.classList.add('hidden');
  404. filteredParents.forEach(parent => {
  405. const isUp = parent.state === 'UP';
  406. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  407. const isExpanded = state.expandedParents.has(parent.name);
  408. const parentRow = document.createElement('tr');
  409. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  410. parentRow.innerHTML = `
  411. <td class="py-3 px-3 text-center">
  412. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  413. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  414. <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">
  415. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  416. </svg>
  417. </button>
  418. </td>
  419. <td class="py-3 px-4">
  420. <div class="flex items-center space-x-2.5">
  421. <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">
  422. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  423. </div>
  424. <div>
  425. <div class="flex items-center gap-2">
  426. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  427. ${childVlans.length > 0
  428. ? `<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>`
  429. : `<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>`
  430. }
  431. </div>
  432. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  433. </div>
  434. </div>
  435. </td>
  436. <td class="py-3 px-4 font-sans">
  437. <div class="flex items-center gap-1.5">
  438. <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>
  439. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  440. </div>
  441. </td>
  442. <td class="py-3 px-4">
  443. ${parent.ipv4 && parent.ipv4.length > 0
  444. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  445. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  446. }
  447. </td>
  448. <td class="py-3 px-4 text-slate-400 text-[11px]">
  449. <div>${parent.mac || 'N/A'}</div>
  450. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  451. </td>
  452. <td class="py-3 px-4 text-[11px]">
  453. <div class="flex items-center space-x-2">
  454. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  455. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  456. </div>
  457. </td>
  458. <td class="py-3 px-4 font-sans">
  459. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  460. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  461. 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'
  462. }" title="Click to toggle link status">
  463. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  464. <span>${parent.state}</span>
  465. </button>
  466. </td>
  467. <td class="py-3 px-4 text-right space-x-2 font-sans">
  468. <button onclick="openVlanModal('${parent.name}')"
  469. 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">
  470. + Add VLAN
  471. </button>
  472. <button onclick="openIfaceModal('${parent.name}')"
  473. 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">
  474. Configure
  475. </button>
  476. </td>
  477. `;
  478. tbody.appendChild(parentRow);
  479. if (isExpanded) {
  480. const drawerRow = document.createElement('tr');
  481. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  482. const drawerCell = document.createElement('td');
  483. drawerCell.colSpan = 8;
  484. drawerCell.className = 'p-0';
  485. drawerCell.innerHTML = `
  486. <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">
  487. <div class="flex items-center justify-between mb-3">
  488. <div class="flex items-center space-x-3">
  489. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  490. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  491. </span>
  492. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  493. ${childVlans.length} Attached
  494. </span>
  495. </div>
  496. <button onclick="openVlanModal('${parent.name}')"
  497. 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">
  498. <span>+ Create VLAN on ${parent.name}</span>
  499. </button>
  500. </div>
  501. ${childVlans.length === 0 ? `
  502. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  503. <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>
  504. <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">
  505. <span>+ Create Your First VLAN on ${parent.name}</span>
  506. </button>
  507. </div>
  508. ` : `
  509. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  510. <table class="w-full text-left text-xs font-mono">
  511. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  512. <tr>
  513. <th class="py-2.5 px-4">VLAN ID</th>
  514. <th class="py-2.5 px-4">Interface Device</th>
  515. <th class="py-2.5 px-4">Subnet Gateway</th>
  516. <th class="py-2.5 px-4">Role / Alias</th>
  517. <th class="py-2.5 px-4">MTU</th>
  518. <th class="py-2.5 px-4">Throughput</th>
  519. <th class="py-2.5 px-4">Status</th>
  520. <th class="py-2.5 px-4 text-right">Actions</th>
  521. </tr>
  522. </thead>
  523. <tbody class="divide-y divide-slate-800/70">
  524. ${childVlans.map(v => {
  525. const isVlanUp = v.state === 'UP';
  526. return `
  527. <tr class="hover:bg-slate-800/40 transition">
  528. <td class="py-2.5 px-4">
  529. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  530. VLAN ${v.vlan_id}
  531. </span>
  532. </td>
  533. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  534. <span class="text-cyan-500">└─</span>
  535. <span>${v.name}</span>
  536. </td>
  537. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  538. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  539. </td>
  540. <td class="py-2.5 px-4 font-sans text-slate-300">
  541. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  542. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  543. </td>
  544. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  545. <td class="py-2.5 px-4 text-[11px]">
  546. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  547. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  548. </td>
  549. <td class="py-2.5 px-4 font-sans">
  550. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  551. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  552. 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'
  553. }">
  554. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  555. <span>${v.state}</span>
  556. </button>
  557. </td>
  558. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  559. <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>
  560. <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>
  561. </td>
  562. </tr>
  563. `;
  564. }).join('')}
  565. </tbody>
  566. </table>
  567. </div>
  568. `}
  569. </div>
  570. `;
  571. drawerRow.appendChild(drawerCell);
  572. tbody.appendChild(drawerRow);
  573. }
  574. });
  575. }
  576. // Render VLANs Dedicated View
  577. function renderVlansList() {
  578. const tbody = document.getElementById('vlans-table-body');
  579. const emptyState = document.getElementById('vlans-empty-state');
  580. const countBadge = document.getElementById('vlans-table-count');
  581. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  582. tbody.innerHTML = '';
  583. const allVlans = state.vlans || [];
  584. countBadge.innerText = allVlans.length;
  585. const filtered = allVlans.filter(v => {
  586. if (!query) return true;
  587. return v.name.toLowerCase().includes(query) ||
  588. String(v.vlan_id).includes(query) ||
  589. (v.description || '').toLowerCase().includes(query) ||
  590. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  591. });
  592. if (allVlans.length === 0) {
  593. emptyState.classList.remove('hidden');
  594. return;
  595. }
  596. emptyState.classList.add('hidden');
  597. filtered.forEach(v => {
  598. const isUp = v.state === 'UP';
  599. const tr = document.createElement('tr');
  600. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  601. tr.innerHTML = `
  602. <td class="py-3 px-4">
  603. <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">
  604. VLAN ${v.vlan_id}
  605. </span>
  606. </td>
  607. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  608. <td class="py-3 px-4 text-slate-300">
  609. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  610. </td>
  611. <td class="py-3 px-4 text-emerald-400 font-medium">
  612. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  613. </td>
  614. <td class="py-3 px-4 text-slate-300 font-sans">
  615. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  616. </td>
  617. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  618. <td class="py-3 px-4 font-sans">
  619. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  620. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  621. 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'
  622. }">
  623. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  624. <span>${v.state}</span>
  625. </button>
  626. </td>
  627. <td class="py-3 px-4 text-right space-x-2 font-sans">
  628. <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>
  629. <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>
  630. </td>
  631. `;
  632. tbody.appendChild(tr);
  633. });
  634. }
  635. // Toggle interface UP / DOWN
  636. async function toggleInterfaceState(name, newState) {
  637. try {
  638. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  639. method: 'POST',
  640. headers: { 'Content-Type': 'application/json' },
  641. body: JSON.stringify({ state: newState })
  642. });
  643. const data = await res.json();
  644. if (res.ok) {
  645. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  646. fetchData(false);
  647. } else {
  648. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  649. }
  650. } catch (err) {
  651. showToast('Error', err.message, 'error');
  652. }
  653. }
  654. // ---------------- MikroTik Flag & Utilities ----------------
  655. function renderMikroTikFlag(running, disabled) {
  656. if (running) {
  657. 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>`;
  658. }
  659. if (disabled) {
  660. 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>`;
  661. }
  662. 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>`;
  663. }
  664. function copyToClipboard(text, label = 'Text') {
  665. navigator.clipboard.writeText(text).then(() => {
  666. showToast('Copied', `${label} copied to clipboard`, 'success');
  667. }).catch(() => {
  668. prompt('Copy value:', text);
  669. });
  670. }
  671. // ======================== PPPoE Multi-Instance ========================
  672. async function loadPPPoE(populateInputs = true) {
  673. try {
  674. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  675. const list = await res.json();
  676. state.pppoeList = Array.isArray(list) ? list : [];
  677. const badge = document.getElementById('pppoe-count-badge');
  678. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  679. const tbody = document.getElementById('pppoe-table-body');
  680. const empty = document.getElementById('pppoe-empty');
  681. if (!tbody) return;
  682. tbody.innerHTML = '';
  683. if (state.pppoeList.length === 0) {
  684. if (empty) empty.classList.remove('hidden');
  685. } else {
  686. if (empty) empty.classList.add('hidden');
  687. state.pppoeList.forEach(inst => {
  688. const tr = document.createElement('tr');
  689. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  690. tr.innerHTML = `
  691. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  692. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  693. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  694. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  695. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  696. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  697. <td class="py-2.5 px-3 text-center">
  698. <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'}">
  699. ${inst.default_route ? 'Yes' : 'No'}
  700. </span>
  701. </td>
  702. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  703. ${inst.running ? `
  704. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  705. ` : `
  706. <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>
  707. `}
  708. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  709. ${inst.disabled ? 'Enable' : 'Disable'}
  710. </button>
  711. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  712. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  713. </td>
  714. `;
  715. tbody.appendChild(tr);
  716. });
  717. }
  718. } catch (err) {
  719. console.error('Failed to load PPPoE:', err);
  720. }
  721. }
  722. function openAddPPPoEModal() {
  723. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  724. document.getElementById('pppoe-modal-edit-orig').value = '';
  725. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  726. document.getElementById('pppoe-modal-name').readOnly = false;
  727. document.getElementById('pppoe-modal-user').value = '';
  728. document.getElementById('pppoe-modal-pass').value = '';
  729. document.getElementById('pppoe-modal-service').value = '';
  730. document.getElementById('pppoe-modal-mtu').value = '1492';
  731. document.getElementById('pppoe-modal-defroute').checked = true;
  732. document.getElementById('pppoe-modal-reconnect').checked = true;
  733. document.getElementById('pppoe-modal-disabled').checked = false;
  734. // Populate interfaces
  735. const sel = document.getElementById('pppoe-modal-iface');
  736. sel.innerHTML = '';
  737. (state.interfaces || []).forEach(i => {
  738. if (i.name === 'lo') return;
  739. const opt = document.createElement('option');
  740. opt.value = i.name;
  741. opt.innerText = `${i.name} (${i.role || i.type})`;
  742. sel.appendChild(opt);
  743. });
  744. document.getElementById('pppoe-modal').classList.remove('hidden');
  745. }
  746. function openEditPPPoEModal(name) {
  747. const inst = (state.pppoeList || []).find(i => i.name === name);
  748. if (!inst) return;
  749. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  750. document.getElementById('pppoe-modal-edit-orig').value = name;
  751. document.getElementById('pppoe-modal-name').value = inst.name;
  752. document.getElementById('pppoe-modal-name').readOnly = true;
  753. document.getElementById('pppoe-modal-user').value = inst.username || '';
  754. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  755. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  756. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  757. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  758. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  759. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  760. const sel = document.getElementById('pppoe-modal-iface');
  761. sel.innerHTML = '';
  762. (state.interfaces || []).forEach(i => {
  763. if (i.name === 'lo') return;
  764. const opt = document.createElement('option');
  765. opt.value = i.name;
  766. opt.innerText = `${i.name} (${i.role || i.type})`;
  767. if (i.name === inst.interface) opt.selected = true;
  768. sel.appendChild(opt);
  769. });
  770. document.getElementById('pppoe-modal').classList.remove('hidden');
  771. }
  772. function closePPPoEModal() {
  773. document.getElementById('pppoe-modal').classList.add('hidden');
  774. }
  775. async function submitSavePPPoE(e) {
  776. e.preventDefault();
  777. const name = document.getElementById('pppoe-modal-name').value.trim();
  778. const iface = document.getElementById('pppoe-modal-iface').value;
  779. const user = document.getElementById('pppoe-modal-user').value.trim();
  780. const pass = document.getElementById('pppoe-modal-pass').value;
  781. const service = document.getElementById('pppoe-modal-service').value.trim();
  782. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  783. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  784. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  785. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  786. try {
  787. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  788. method: 'POST',
  789. headers: { 'Content-Type': 'application/json' },
  790. body: JSON.stringify({
  791. name,
  792. interface: iface,
  793. username: user,
  794. password: pass,
  795. service_name: service,
  796. mtu,
  797. default_route: defRoute,
  798. auto_reconnect: reconnect,
  799. disabled
  800. })
  801. });
  802. if (res.ok) {
  803. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  804. closePPPoEModal();
  805. loadPPPoE(false);
  806. fetchData(false);
  807. } else {
  808. const err = await res.json();
  809. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  810. }
  811. } catch (err) {
  812. showToast('Error', err.message, 'error');
  813. }
  814. }
  815. async function connectPPPoEInstance(name) {
  816. try {
  817. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  818. if (res.ok) {
  819. showToast('Connecting', `Dialing ${name}...`, 'info');
  820. setTimeout(() => loadPPPoE(false), 2000);
  821. }
  822. } catch (err) {
  823. showToast('Error', err.message, 'error');
  824. }
  825. }
  826. async function disconnectPPPoEInstance(name) {
  827. try {
  828. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  829. if (res.ok) {
  830. showToast('Disconnected', `${name} session terminated`, 'info');
  831. setTimeout(() => loadPPPoE(false), 1000);
  832. }
  833. } catch (err) {
  834. showToast('Error', err.message, 'error');
  835. }
  836. }
  837. async function togglePPPoEState(name, enable) {
  838. try {
  839. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  840. method: 'POST',
  841. headers: { 'Content-Type': 'application/json' },
  842. body: JSON.stringify({ enabled: enable })
  843. });
  844. if (res.ok) {
  845. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  846. loadPPPoE(false);
  847. }
  848. } catch (err) {
  849. showToast('Error', err.message, 'error');
  850. }
  851. }
  852. async function deletePPPoEInstance(name) {
  853. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  854. try {
  855. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  856. if (res.ok) {
  857. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  858. loadPPPoE(false);
  859. fetchData(false);
  860. }
  861. } catch (err) {
  862. showToast('Error', err.message, 'error');
  863. }
  864. }
  865. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  866. state.wgSubTab = 'ifaces';
  867. function switchWGSubTab(tab) {
  868. state.wgSubTab = tab;
  869. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  870. const peersPanel = document.getElementById('wg-subtab-peers');
  871. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  872. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  873. if (tab === 'ifaces') {
  874. ifacesPanel?.classList.remove('hidden');
  875. peersPanel?.classList.add('hidden');
  876. 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';
  877. 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';
  878. } else {
  879. ifacesPanel?.classList.add('hidden');
  880. peersPanel?.classList.remove('hidden');
  881. 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';
  882. 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';
  883. renderWGPeers();
  884. }
  885. }
  886. async function loadWireGuard(populateInputs = true) {
  887. try {
  888. const [ifacesRes, peersRes] = await Promise.all([
  889. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  890. fetch(`${API_BASE}/vpn/wireguard/peers`)
  891. ]);
  892. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  893. const peers = peersRes.ok ? await peersRes.json() : [];
  894. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  895. state.wgPeers = Array.isArray(peers) ? peers : [];
  896. // Badges
  897. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  898. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  899. const peersCountBadge = document.getElementById('wg-peers-count');
  900. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  901. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  902. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  903. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  904. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  905. // Render Interfaces
  906. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  907. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  908. if (ifacesTbody) {
  909. ifacesTbody.innerHTML = '';
  910. if (state.wgInterfaces.length === 0) {
  911. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  912. } else {
  913. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  914. state.wgInterfaces.forEach(iface => {
  915. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  916. const tr = document.createElement('tr');
  917. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  918. tr.innerHTML = `
  919. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  920. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  921. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  922. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  923. <td class="py-2.5 px-3 text-slate-300 font-mono">
  924. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  925. ${(iface.public_key || '').substring(0, 10)}... 📋
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  929. <td class="py-2.5 px-3 text-center">
  930. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  931. </td>
  932. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  933. ${iface.running ? `
  934. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  935. ` : `
  936. <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>
  937. `}
  938. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  939. ${iface.disabled ? 'Enable' : 'Disable'}
  940. </button>
  941. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  942. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  943. </td>
  944. `;
  945. ifacesTbody.appendChild(tr);
  946. });
  947. }
  948. }
  949. // Populate filter dropdown in peers tab
  950. const filterSel = document.getElementById('wg-peers-filter-iface');
  951. if (filterSel) {
  952. const currentVal = filterSel.value;
  953. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  954. state.wgInterfaces.forEach(i => {
  955. const opt = document.createElement('option');
  956. opt.value = i.name;
  957. opt.innerText = i.name;
  958. if (i.name === currentVal) opt.selected = true;
  959. filterSel.appendChild(opt);
  960. });
  961. }
  962. renderWGPeers();
  963. } catch (err) {
  964. console.error('Failed to load WireGuard:', err);
  965. }
  966. }
  967. function renderWGPeers() {
  968. const filterSel = document.getElementById('wg-peers-filter-iface');
  969. const selectedIface = filterSel ? filterSel.value : '';
  970. const tbody = document.getElementById('wg-peers-table-body');
  971. const empty = document.getElementById('wg-peers-empty');
  972. if (!tbody) return;
  973. tbody.innerHTML = '';
  974. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  975. if (filtered.length === 0) {
  976. if (empty) empty.classList.remove('hidden');
  977. } else {
  978. if (empty) empty.classList.add('hidden');
  979. filtered.forEach(p => {
  980. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  981. const tr = document.createElement('tr');
  982. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  983. tr.innerHTML = `
  984. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  985. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  986. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  987. <td class="py-2.5 px-3 text-slate-300 font-mono">
  988. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  989. ${p.public_key.substring(0, 10)}... 📋
  990. </span>
  991. </td>
  992. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  993. <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>
  994. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  995. <td class="py-2.5 px-3 font-mono text-[11px]">
  996. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  997. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  998. </td>
  999. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1000. <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>
  1001. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1002. </td>
  1003. `;
  1004. tbody.appendChild(tr);
  1005. });
  1006. }
  1007. }
  1008. function openAddWGInterfaceModal() {
  1009. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1010. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1011. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1012. document.getElementById('wg-iface-modal-name').readOnly = false;
  1013. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1014. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1015. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1016. document.getElementById('wg-iface-modal-pubkey').value = '';
  1017. document.getElementById('wg-iface-modal-privkey').value = '';
  1018. document.getElementById('wg-iface-modal-disabled').checked = false;
  1019. generateWGInterfaceKeys();
  1020. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1021. }
  1022. function openEditWGInterfaceModal(name) {
  1023. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1024. if (!iface) return;
  1025. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1026. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1027. document.getElementById('wg-iface-modal-name').value = iface.name;
  1028. document.getElementById('wg-iface-modal-name').readOnly = true;
  1029. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1030. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1031. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1032. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1033. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1034. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1035. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1036. }
  1037. function closeAddWGInterfaceModal() {
  1038. document.getElementById('wg-iface-modal').classList.add('hidden');
  1039. }
  1040. async function generateWGInterfaceKeys() {
  1041. try {
  1042. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1043. const keys = await res.json();
  1044. if (res.ok) {
  1045. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1046. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1050. }
  1051. }
  1052. async function submitSaveWGInterface(e) {
  1053. e.preventDefault();
  1054. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1055. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1056. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1057. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1058. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1059. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1060. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1063. method: 'POST',
  1064. headers: { 'Content-Type': 'application/json' },
  1065. body: JSON.stringify({
  1066. name,
  1067. listen_port: port,
  1068. address: addr,
  1069. mtu,
  1070. public_key: pub,
  1071. private_key: priv,
  1072. disabled
  1073. })
  1074. });
  1075. if (res.ok) {
  1076. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1077. closeAddWGInterfaceModal();
  1078. loadWireGuard(false);
  1079. fetchData(false);
  1080. }
  1081. } catch (err) {
  1082. showToast('Error', err.message, 'error');
  1083. }
  1084. }
  1085. async function startWGInterface(name) {
  1086. try {
  1087. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1088. if (res.ok) {
  1089. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1090. loadWireGuard(false);
  1091. fetchData(false);
  1092. }
  1093. } catch (err) {
  1094. showToast('Error', err.message, 'error');
  1095. }
  1096. }
  1097. async function stopWGInterface(name) {
  1098. try {
  1099. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1100. if (res.ok) {
  1101. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1102. loadWireGuard(false);
  1103. fetchData(false);
  1104. }
  1105. } catch (err) {
  1106. showToast('Error', err.message, 'error');
  1107. }
  1108. }
  1109. async function toggleWGInterfaceState(name, enable) {
  1110. try {
  1111. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1112. method: 'POST',
  1113. headers: { 'Content-Type': 'application/json' },
  1114. body: JSON.stringify({ enabled: enable })
  1115. });
  1116. if (res.ok) {
  1117. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1118. loadWireGuard(false);
  1119. }
  1120. } catch (err) {
  1121. showToast('Error', err.message, 'error');
  1122. }
  1123. }
  1124. async function deleteWGInterface(name) {
  1125. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1126. try {
  1127. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1128. if (res.ok) {
  1129. showToast('Deleted', `Interface ${name} removed`, 'success');
  1130. loadWireGuard(false);
  1131. fetchData(false);
  1132. }
  1133. } catch (err) {
  1134. showToast('Error', err.message, 'error');
  1135. }
  1136. }
  1137. function openAddWGPeerModal() {
  1138. const sel = document.getElementById('wg-peer-modal-iface');
  1139. sel.innerHTML = '';
  1140. (state.wgInterfaces || []).forEach(i => {
  1141. const opt = document.createElement('option');
  1142. opt.value = i.name;
  1143. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1144. sel.appendChild(opt);
  1145. });
  1146. if ((state.wgInterfaces || []).length === 0) {
  1147. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1148. openAddWGInterfaceModal();
  1149. return;
  1150. }
  1151. document.getElementById('wg-peer-modal-name').value = '';
  1152. document.getElementById('wg-peer-modal-pubkey').value = '';
  1153. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1154. document.getElementById('wg-peer-modal-endpoint').value = '';
  1155. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1156. document.getElementById('wg-peer-modal-preshared').value = '';
  1157. document.getElementById('wg-peer-modal-disabled').checked = false;
  1158. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1159. }
  1160. function closeAddWGPeerModal() {
  1161. document.getElementById('wg-peer-modal').classList.add('hidden');
  1162. }
  1163. async function submitSaveWGPeer(e) {
  1164. e.preventDefault();
  1165. const iface = document.getElementById('wg-peer-modal-iface').value;
  1166. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1167. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1168. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1169. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1170. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1171. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1172. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1173. let epAddr = ep;
  1174. let epPort = 0;
  1175. if (ep.includes(':')) {
  1176. const parts = ep.split(':');
  1177. epAddr = parts[0];
  1178. epPort = parseInt(parts[1], 10) || 0;
  1179. }
  1180. try {
  1181. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1182. method: 'POST',
  1183. headers: { 'Content-Type': 'application/json' },
  1184. body: JSON.stringify({
  1185. interface: iface,
  1186. name,
  1187. public_key: pub,
  1188. allowed_ips: allowed,
  1189. endpoint_address: epAddr,
  1190. endpoint_port: epPort,
  1191. persistent_keepalive: keepalive,
  1192. preshared_key: psk,
  1193. disabled
  1194. })
  1195. });
  1196. if (res.ok) {
  1197. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1198. closeAddWGPeerModal();
  1199. loadWireGuard(false);
  1200. }
  1201. } catch (err) {
  1202. showToast('Error', err.message, 'error');
  1203. }
  1204. }
  1205. async function deleteWGPeer(iface, pubkey) {
  1206. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1207. try {
  1208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1209. method: 'DELETE'
  1210. });
  1211. if (res.ok) {
  1212. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1213. loadWireGuard(false);
  1214. }
  1215. } catch (err) {
  1216. showToast('Error', err.message, 'error');
  1217. }
  1218. }
  1219. // ======================== IPSec Multi-Tunnel ========================
  1220. async function loadIPSec(populateInputs = true) {
  1221. try {
  1222. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1223. const list = await res.json();
  1224. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1225. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1226. const badge = document.getElementById('ipsec-sas-badge');
  1227. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1228. const tbody = document.getElementById('ipsec-table-body');
  1229. const empty = document.getElementById('ipsec-empty');
  1230. if (!tbody) return;
  1231. tbody.innerHTML = '';
  1232. if (state.ipsecTunnels.length === 0) {
  1233. if (empty) empty.classList.remove('hidden');
  1234. } else {
  1235. if (empty) empty.classList.add('hidden');
  1236. state.ipsecTunnels.forEach(c => {
  1237. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1238. const tr = document.createElement('tr');
  1239. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1240. tr.innerHTML = `
  1241. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1242. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1243. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1244. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1245. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1246. <td class="py-2.5 px-4 font-sans">
  1247. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1248. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1249. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1250. </td>
  1251. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1252. ${isEstablished ? `
  1253. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1254. ` : `
  1255. <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>
  1256. `}
  1257. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1258. ${c.disabled ? 'Enable' : 'Disable'}
  1259. </button>
  1260. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1261. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1262. </td>
  1263. `;
  1264. tbody.appendChild(tr);
  1265. });
  1266. }
  1267. } catch (err) {
  1268. console.error('Failed to load IPSec:', err);
  1269. }
  1270. }
  1271. function openAddIPSecModal() {
  1272. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1273. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1274. document.getElementById('ipsec-modal-name').readOnly = false;
  1275. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1276. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1277. document.getElementById('ipsec-modal-remotegw').value = '';
  1278. document.getElementById('ipsec-modal-psk').value = '';
  1279. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1280. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1281. document.getElementById('ipsec-modal-autostart').checked = true;
  1282. document.getElementById('ipsec-modal-disabled').checked = false;
  1283. document.getElementById('ipsec-modal').classList.remove('hidden');
  1284. }
  1285. function openEditIPSecModal(name) {
  1286. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1287. if (!conn) return;
  1288. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1289. document.getElementById('ipsec-modal-name').value = conn.name;
  1290. document.getElementById('ipsec-modal-name').readOnly = true;
  1291. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1292. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1293. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1294. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1295. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1296. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1297. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1298. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1299. document.getElementById('ipsec-modal').classList.remove('hidden');
  1300. }
  1301. function closeAddIPSecModal() {
  1302. document.getElementById('ipsec-modal').classList.add('hidden');
  1303. }
  1304. async function submitSaveIPSec(e) {
  1305. e.preventDefault();
  1306. const name = document.getElementById('ipsec-modal-name').value.trim();
  1307. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1308. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1309. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1310. const psk = document.getElementById('ipsec-modal-psk').value;
  1311. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1312. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1313. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1314. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1315. try {
  1316. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1317. method: 'POST',
  1318. headers: { 'Content-Type': 'application/json' },
  1319. body: JSON.stringify({
  1320. name,
  1321. local_addrs: '%any',
  1322. remote_addrs: remotegw,
  1323. local_subnet: localts,
  1324. remote_subnet: remotets,
  1325. preshared_key: psk,
  1326. ike_proposals: ike,
  1327. esp_proposals: esp,
  1328. auto_start: autostart,
  1329. disabled
  1330. })
  1331. });
  1332. if (res.ok) {
  1333. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1334. closeAddIPSecModal();
  1335. loadIPSec(false);
  1336. fetchData(false);
  1337. }
  1338. } catch (err) {
  1339. showToast('Error', err.message, 'error');
  1340. }
  1341. }
  1342. async function startIPSecTunnel(name) {
  1343. try {
  1344. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1345. if (res.ok) {
  1346. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1347. setTimeout(() => loadIPSec(false), 2000);
  1348. }
  1349. } catch (err) {
  1350. showToast('Error', err.message, 'error');
  1351. }
  1352. }
  1353. async function stopIPSecTunnel(name) {
  1354. try {
  1355. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1356. if (res.ok) {
  1357. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1358. loadIPSec(false);
  1359. }
  1360. } catch (err) {
  1361. showToast('Error', err.message, 'error');
  1362. }
  1363. }
  1364. async function toggleIPSecState(name, enable) {
  1365. try {
  1366. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1367. method: 'POST',
  1368. headers: { 'Content-Type': 'application/json' },
  1369. body: JSON.stringify({ enabled: enable })
  1370. });
  1371. if (res.ok) {
  1372. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1373. loadIPSec(false);
  1374. }
  1375. } catch (err) {
  1376. showToast('Error', err.message, 'error');
  1377. }
  1378. }
  1379. async function deleteIPSecConn(name) {
  1380. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1381. try {
  1382. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1383. if (res.ok) {
  1384. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1385. loadIPSec(false);
  1386. fetchData(false);
  1387. }
  1388. } catch (err) {
  1389. showToast('Error', err.message, 'error');
  1390. }
  1391. }
  1392. // ======================== L2TP Multi-Instance ========================
  1393. async function loadL2TP(populateInputs = true) {
  1394. try {
  1395. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1396. const list = await res.json();
  1397. state.l2tpList = Array.isArray(list) ? list : [];
  1398. const badge = document.getElementById('l2tp-count-badge');
  1399. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1400. const tbody = document.getElementById('l2tp-table-body');
  1401. const empty = document.getElementById('l2tp-empty');
  1402. if (!tbody) return;
  1403. tbody.innerHTML = '';
  1404. if (state.l2tpList.length === 0) {
  1405. if (empty) empty.classList.remove('hidden');
  1406. } else {
  1407. if (empty) empty.classList.add('hidden');
  1408. state.l2tpList.forEach(inst => {
  1409. const tr = document.createElement('tr');
  1410. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1411. tr.innerHTML = `
  1412. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1413. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1414. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1415. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1416. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1417. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1418. <td class="py-2.5 px-3 text-center">
  1419. <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'}">
  1420. ${inst.default_route ? 'Yes' : 'No'}
  1421. </span>
  1422. </td>
  1423. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1424. ${inst.running ? `
  1425. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1426. ` : `
  1427. <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>
  1428. `}
  1429. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1430. ${inst.disabled ? 'Enable' : 'Disable'}
  1431. </button>
  1432. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1433. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1434. </td>
  1435. `;
  1436. tbody.appendChild(tr);
  1437. });
  1438. }
  1439. } catch (err) {
  1440. console.error('Failed to load L2TP:', err);
  1441. }
  1442. }
  1443. function openAddL2TPModal() {
  1444. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1445. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1446. document.getElementById('l2tp-modal-name').readOnly = false;
  1447. document.getElementById('l2tp-modal-server').value = '';
  1448. document.getElementById('l2tp-modal-user').value = '';
  1449. document.getElementById('l2tp-modal-pass').value = '';
  1450. document.getElementById('l2tp-modal-ipsec').value = '';
  1451. document.getElementById('l2tp-modal-defroute').checked = true;
  1452. document.getElementById('l2tp-modal-disabled').checked = false;
  1453. document.getElementById('l2tp-modal').classList.remove('hidden');
  1454. }
  1455. function openEditL2TPModal(name) {
  1456. const inst = (state.l2tpList || []).find(i => i.name === name);
  1457. if (!inst) return;
  1458. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1459. document.getElementById('l2tp-modal-name').value = inst.name;
  1460. document.getElementById('l2tp-modal-name').readOnly = true;
  1461. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1462. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1463. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1464. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1465. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1466. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1467. document.getElementById('l2tp-modal').classList.remove('hidden');
  1468. }
  1469. function closeL2TPModal() {
  1470. document.getElementById('l2tp-modal').classList.add('hidden');
  1471. }
  1472. async function submitSaveL2TP(e) {
  1473. e.preventDefault();
  1474. const name = document.getElementById('l2tp-modal-name').value.trim();
  1475. const server = document.getElementById('l2tp-modal-server').value.trim();
  1476. const user = document.getElementById('l2tp-modal-user').value.trim();
  1477. const pass = document.getElementById('l2tp-modal-pass').value;
  1478. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1479. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1480. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1483. method: 'POST',
  1484. headers: { 'Content-Type': 'application/json' },
  1485. body: JSON.stringify({
  1486. name,
  1487. connect_to: server,
  1488. username: user,
  1489. password: pass,
  1490. ipsec_secret: ipsec,
  1491. default_route: defRoute,
  1492. disabled
  1493. })
  1494. });
  1495. if (res.ok) {
  1496. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1497. closeL2TPModal();
  1498. loadL2TP(false);
  1499. fetchData(false);
  1500. }
  1501. } catch (err) {
  1502. showToast('Error', err.message, 'error');
  1503. }
  1504. }
  1505. async function connectL2TPInstance(name) {
  1506. try {
  1507. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1508. if (res.ok) {
  1509. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1510. setTimeout(() => loadL2TP(false), 2000);
  1511. }
  1512. } catch (err) {
  1513. showToast('Error', err.message, 'error');
  1514. }
  1515. }
  1516. async function disconnectL2TPInstance(name) {
  1517. try {
  1518. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1519. if (res.ok) {
  1520. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1521. loadL2TP(false);
  1522. }
  1523. } catch (err) {
  1524. showToast('Error', err.message, 'error');
  1525. }
  1526. }
  1527. async function toggleL2TPState(name, enable) {
  1528. try {
  1529. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1530. method: 'POST',
  1531. headers: { 'Content-Type': 'application/json' },
  1532. body: JSON.stringify({ enabled: enable })
  1533. });
  1534. if (res.ok) {
  1535. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1536. loadL2TP(false);
  1537. }
  1538. } catch (err) {
  1539. showToast('Error', err.message, 'error');
  1540. }
  1541. }
  1542. async function deleteL2TPInstance(name) {
  1543. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1544. try {
  1545. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1546. if (res.ok) {
  1547. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1548. loadL2TP(false);
  1549. fetchData(false);
  1550. }
  1551. } catch (err) {
  1552. showToast('Error', err.message, 'error');
  1553. }
  1554. }
  1555. // ======================== PPTP Multi-Instance ========================
  1556. async function loadPPTP(populateInputs = true) {
  1557. try {
  1558. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1559. const list = await res.json();
  1560. state.pptpList = Array.isArray(list) ? list : [];
  1561. const badge = document.getElementById('pptp-count-badge');
  1562. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1563. const tbody = document.getElementById('pptp-table-body');
  1564. const empty = document.getElementById('pptp-empty');
  1565. if (!tbody) return;
  1566. tbody.innerHTML = '';
  1567. if (state.pptpList.length === 0) {
  1568. if (empty) empty.classList.remove('hidden');
  1569. } else {
  1570. if (empty) empty.classList.add('hidden');
  1571. state.pptpList.forEach(inst => {
  1572. const tr = document.createElement('tr');
  1573. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1574. tr.innerHTML = `
  1575. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1576. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1577. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1578. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1579. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1580. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1581. <td class="py-2.5 px-3 text-center">
  1582. <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'}">
  1583. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1584. </span>
  1585. </td>
  1586. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1587. ${inst.running ? `
  1588. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1589. ` : `
  1590. <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>
  1591. `}
  1592. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1593. ${inst.disabled ? 'Enable' : 'Disable'}
  1594. </button>
  1595. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1596. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1597. </td>
  1598. `;
  1599. tbody.appendChild(tr);
  1600. });
  1601. }
  1602. } catch (err) {
  1603. console.error('Failed to load PPTP:', err);
  1604. }
  1605. }
  1606. function openAddPPTPModal() {
  1607. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1608. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1609. document.getElementById('pptp-modal-name').readOnly = false;
  1610. document.getElementById('pptp-modal-server').value = '';
  1611. document.getElementById('pptp-modal-user').value = '';
  1612. document.getElementById('pptp-modal-pass').value = '';
  1613. document.getElementById('pptp-modal-mppe').checked = true;
  1614. document.getElementById('pptp-modal-defroute').checked = true;
  1615. document.getElementById('pptp-modal-disabled').checked = false;
  1616. document.getElementById('pptp-modal').classList.remove('hidden');
  1617. }
  1618. function openEditPPTPModal(name) {
  1619. const inst = (state.pptpList || []).find(i => i.name === name);
  1620. if (!inst) return;
  1621. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1622. document.getElementById('pptp-modal-name').value = inst.name;
  1623. document.getElementById('pptp-modal-name').readOnly = true;
  1624. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1625. document.getElementById('pptp-modal-user').value = inst.username || '';
  1626. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1627. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1628. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1629. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1630. document.getElementById('pptp-modal').classList.remove('hidden');
  1631. }
  1632. function closePPTPModal() {
  1633. document.getElementById('pptp-modal').classList.add('hidden');
  1634. }
  1635. async function submitSavePPTP(e) {
  1636. e.preventDefault();
  1637. const name = document.getElementById('pptp-modal-name').value.trim();
  1638. const server = document.getElementById('pptp-modal-server').value.trim();
  1639. const user = document.getElementById('pptp-modal-user').value.trim();
  1640. const pass = document.getElementById('pptp-modal-pass').value;
  1641. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1642. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1643. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1644. try {
  1645. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1646. method: 'POST',
  1647. headers: { 'Content-Type': 'application/json' },
  1648. body: JSON.stringify({
  1649. name,
  1650. connect_to: server,
  1651. username: user,
  1652. password: pass,
  1653. require_mppe: mppe,
  1654. default_route: defRoute,
  1655. auto_reconnect: true,
  1656. disabled
  1657. })
  1658. });
  1659. if (res.ok) {
  1660. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1661. closePPTPModal();
  1662. loadPPTP(false);
  1663. fetchData(false);
  1664. }
  1665. } catch (err) {
  1666. showToast('Error', err.message, 'error');
  1667. }
  1668. }
  1669. async function connectPPTPInstance(name) {
  1670. try {
  1671. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1672. if (res.ok) {
  1673. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1674. setTimeout(() => loadPPTP(false), 2000);
  1675. }
  1676. } catch (err) {
  1677. showToast('Error', err.message, 'error');
  1678. }
  1679. }
  1680. async function disconnectPPTPInstance(name) {
  1681. try {
  1682. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1683. if (res.ok) {
  1684. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1685. loadPPTP(false);
  1686. }
  1687. } catch (err) {
  1688. showToast('Error', err.message, 'error');
  1689. }
  1690. }
  1691. async function togglePPTPState(name, enable) {
  1692. try {
  1693. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1694. method: 'POST',
  1695. headers: { 'Content-Type': 'application/json' },
  1696. body: JSON.stringify({ enabled: enable })
  1697. });
  1698. if (res.ok) {
  1699. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1700. loadPPTP(false);
  1701. }
  1702. } catch (err) {
  1703. showToast('Error', err.message, 'error');
  1704. }
  1705. }
  1706. async function deletePPTPInstance(name) {
  1707. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1708. try {
  1709. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1710. if (res.ok) {
  1711. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1712. loadPPTP(false);
  1713. fetchData(false);
  1714. }
  1715. } catch (err) {
  1716. showToast('Error', err.message, 'error');
  1717. }
  1718. }
  1719. // ---------------- Modal & Helper Functions ----------------
  1720. function openVlanModal(defaultParent = '') {
  1721. const select = document.getElementById('vlan-parent');
  1722. select.innerHTML = '';
  1723. const allIfaces = state.interfaces || [];
  1724. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1725. if (eligible.length === 0) {
  1726. allIfaces.forEach(i => eligible.push(i));
  1727. }
  1728. eligible.forEach(i => {
  1729. const opt = document.createElement('option');
  1730. opt.value = i.name;
  1731. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1732. if (i.name === defaultParent) opt.selected = true;
  1733. select.appendChild(opt);
  1734. });
  1735. document.getElementById('vlan-id').value = '';
  1736. document.getElementById('vlan-name').value = '';
  1737. document.getElementById('vlan-ip').value = '';
  1738. document.getElementById('vlan-desc').value = '';
  1739. autoSuggestVlanName();
  1740. document.getElementById('vlan-modal').classList.remove('hidden');
  1741. }
  1742. function closeVlanModal() {
  1743. document.getElementById('vlan-modal').classList.add('hidden');
  1744. }
  1745. function autoSuggestVlanName() {
  1746. const parent = document.getElementById('vlan-parent').value;
  1747. const id = document.getElementById('vlan-id').value;
  1748. const nameInput = document.getElementById('vlan-name');
  1749. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1750. }
  1751. function setSubnetPreset(cidr) {
  1752. const ipInput = document.getElementById('vlan-ip');
  1753. const id = document.getElementById('vlan-id').value || '10';
  1754. ipInput.value = `192.168.${id}.1${cidr}`;
  1755. }
  1756. async function submitCreateVlan(e) {
  1757. e.preventDefault();
  1758. const btn = document.getElementById('vlan-submit-btn');
  1759. btn.disabled = true;
  1760. btn.innerText = 'Creating...';
  1761. const parent = document.getElementById('vlan-parent').value;
  1762. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1763. const name = document.getElementById('vlan-name').value.trim();
  1764. const ip = document.getElementById('vlan-ip').value.trim();
  1765. const role = document.getElementById('vlan-role').value;
  1766. const desc = document.getElementById('vlan-desc').value.trim();
  1767. try {
  1768. const res = await fetch(`${API_BASE}/vlans`, {
  1769. method: 'POST',
  1770. headers: { 'Content-Type': 'application/json' },
  1771. body: JSON.stringify({
  1772. parent_name: parent,
  1773. vlan_id: id,
  1774. name: name,
  1775. ip_address: ip,
  1776. role: role,
  1777. description: desc,
  1778. mtu: 1500,
  1779. auto_up: true
  1780. })
  1781. });
  1782. const data = await res.json();
  1783. if (res.ok) {
  1784. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1785. state.expandedParents.add(parent);
  1786. closeVlanModal();
  1787. await fetchData(true);
  1788. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1789. } else {
  1790. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1791. }
  1792. } catch (err) {
  1793. showToast('Error', err.message, 'error');
  1794. } finally {
  1795. btn.disabled = false;
  1796. btn.innerText = 'Create VLAN';
  1797. }
  1798. }
  1799. async function confirmDeleteVlan(name) {
  1800. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1801. try {
  1802. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1803. if (res.ok) {
  1804. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1805. closeIfaceModal();
  1806. fetchData(true);
  1807. }
  1808. } catch (err) {
  1809. showToast('Error', err.message, 'error');
  1810. }
  1811. }
  1812. function openIfaceModal(name) {
  1813. const iface = (state.interfaces || []).find(i => i.name === name);
  1814. if (!iface) return;
  1815. state.currentModalIface = iface.name;
  1816. document.getElementById('modal-iface-name').innerText = iface.name;
  1817. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1818. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1819. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1820. document.getElementById('modal-iface-desc').value = iface.description || '';
  1821. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1822. if (iface.is_vlan) {
  1823. delBtn.classList.remove('hidden');
  1824. } else {
  1825. delBtn.classList.add('hidden');
  1826. }
  1827. renderModalIPs(iface);
  1828. document.getElementById('iface-modal').classList.remove('hidden');
  1829. }
  1830. function renderModalIPs(iface) {
  1831. const container = document.getElementById('modal-ip-list');
  1832. container.innerHTML = '';
  1833. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1834. if (addrs.length === 0) {
  1835. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1836. return;
  1837. }
  1838. addrs.forEach(addr => {
  1839. const row = document.createElement('div');
  1840. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1841. row.innerHTML = `
  1842. <span class="text-white">${addr}</span>
  1843. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1844. `;
  1845. container.appendChild(row);
  1846. });
  1847. }
  1848. function closeIfaceModal() {
  1849. document.getElementById('iface-modal').classList.add('hidden');
  1850. state.currentModalIface = null;
  1851. }
  1852. async function setIfaceState(name, newState) {
  1853. await toggleInterfaceState(name, newState);
  1854. const updated = (state.interfaces || []).find(i => i.name === name);
  1855. if (updated) openIfaceModal(name);
  1856. }
  1857. async function applyMTU() {
  1858. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1859. try {
  1860. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1861. method: 'POST',
  1862. headers: { 'Content-Type': 'application/json' },
  1863. body: JSON.stringify({ mtu })
  1864. });
  1865. if (res.ok) {
  1866. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1867. fetchData(false);
  1868. }
  1869. } catch (err) {
  1870. showToast('Error', err.message, 'error');
  1871. }
  1872. }
  1873. async function addInterfaceIP() {
  1874. const ip = document.getElementById('modal-new-ip').value.trim();
  1875. if (!ip) return;
  1876. try {
  1877. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1878. method: 'POST',
  1879. headers: { 'Content-Type': 'application/json' },
  1880. body: JSON.stringify({ ip })
  1881. });
  1882. if (res.ok) {
  1883. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1884. document.getElementById('modal-new-ip').value = '';
  1885. await fetchData(false);
  1886. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1887. if (iface) renderModalIPs(iface);
  1888. } else {
  1889. const err = await res.json();
  1890. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1891. }
  1892. } catch (err) {
  1893. showToast('Error', err.message, 'error');
  1894. }
  1895. }
  1896. async function removeInterfaceIP(ip) {
  1897. if (!confirm(`Remove IP ${ip}?`)) return;
  1898. try {
  1899. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1900. method: 'DELETE',
  1901. headers: { 'Content-Type': 'application/json' },
  1902. body: JSON.stringify({ ip })
  1903. });
  1904. if (res.ok) {
  1905. showToast('IP Removed', `Removed ${ip}`, 'success');
  1906. await fetchData(false);
  1907. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1908. if (iface) renderModalIPs(iface);
  1909. }
  1910. } catch (err) {
  1911. showToast('Error', err.message, 'error');
  1912. }
  1913. }
  1914. async function saveInterfaceMetadata() {
  1915. const role = document.getElementById('modal-iface-role').value;
  1916. const desc = document.getElementById('modal-iface-desc').value.trim();
  1917. try {
  1918. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1919. method: 'POST',
  1920. headers: { 'Content-Type': 'application/json' },
  1921. body: JSON.stringify({ role, description: desc })
  1922. });
  1923. if (res.ok) {
  1924. showToast('Saved', 'Metadata updated', 'success');
  1925. closeIfaceModal();
  1926. fetchData(false);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1933. state.fwSubTab = 'filter';
  1934. state.routesSubTab = 'routes';
  1935. function renderRuleFlag(disabled, hasComment) {
  1936. let flags = '';
  1937. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1938. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1939. return flags || '<span class="text-slate-600">-</span>';
  1940. }
  1941. function renderActionBadge(action) {
  1942. const act = (action || '').toLowerCase();
  1943. let color = 'bg-slate-800 text-slate-300';
  1944. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1945. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1946. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1947. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1948. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1949. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1950. }
  1951. function switchFWSubTab(tab) {
  1952. state.fwSubTab = tab;
  1953. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1954. tabs.forEach(t => {
  1955. const panel = document.getElementById(`fw-subtab-${t}`);
  1956. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1957. if (panel) {
  1958. if (t === tab) panel.classList.remove('hidden');
  1959. else panel.classList.add('hidden');
  1960. }
  1961. if (btn) {
  1962. if (t === tab) {
  1963. 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';
  1964. } else {
  1965. 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';
  1966. }
  1967. }
  1968. });
  1969. const addBtn = document.getElementById('fw-primary-add-btn');
  1970. if (addBtn) {
  1971. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1972. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  1973. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  1974. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  1975. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  1976. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  1977. }
  1978. if (tab === 'geo') loadGeoIP();
  1979. if (tab === 'connections') loadConnections();
  1980. }
  1981. function openCurrentFWModal() {
  1982. if (state.fwSubTab === 'filter') openAddFilterModal();
  1983. else if (state.fwSubTab === 'nat') openAddNATModal();
  1984. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  1985. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  1986. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  1987. else if (state.fwSubTab === 'connections') loadConnections();
  1988. }
  1989. async function loadFirewall(populateDropdowns = true) {
  1990. try {
  1991. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  1992. fetch(`${API_BASE}/firewall/summary`),
  1993. fetch(`${API_BASE}/firewall/filter`),
  1994. fetch(`${API_BASE}/firewall/nat`),
  1995. fetch(`${API_BASE}/firewall/mangle`),
  1996. fetch(`${API_BASE}/firewall/address-lists`),
  1997. fetch(`${API_BASE}/firewall/geoip/status`),
  1998. fetch(`${API_BASE}/firewall/geoip/countries`)
  1999. ]);
  2000. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2001. if (filterRes.ok) state.filterRules = await filterRes.json();
  2002. if (natRes.ok) state.natRules = await natRes.json();
  2003. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2004. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2005. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2006. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2007. // Badges
  2008. const bFilter = document.getElementById('fw-badge-filter');
  2009. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2010. const bNat = document.getElementById('fw-badge-nat');
  2011. if (bNat) bNat.innerText = (state.natRules || []).length;
  2012. const bMangle = document.getElementById('fw-badge-mangle');
  2013. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2014. const bAddr = document.getElementById('fw-badge-addrlist');
  2015. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2016. const bGeo = document.getElementById('fw-badge-geo');
  2017. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2018. renderFilterRules();
  2019. renderNATRules();
  2020. renderMangleRules();
  2021. renderAddressLists();
  2022. renderGeoCountries();
  2023. if (state.fwSubTab === 'connections') {
  2024. loadConnections();
  2025. }
  2026. } catch (err) {
  2027. console.error('Failed to load firewall:', err);
  2028. }
  2029. }
  2030. // ----------------- Filter Rules -----------------
  2031. function renderFilterRules() {
  2032. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2033. const tbody = document.getElementById('filter-table-body');
  2034. const empty = document.getElementById('filter-empty');
  2035. if (!tbody) return;
  2036. tbody.innerHTML = '';
  2037. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2038. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2039. if (rules.length === 0) {
  2040. empty?.classList.remove('hidden');
  2041. return;
  2042. }
  2043. empty?.classList.add('hidden');
  2044. rules.forEach((r, idx) => {
  2045. const tr = document.createElement('tr');
  2046. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2047. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2048. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2049. tr.innerHTML = `
  2050. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2051. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2052. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2053. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2054. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2055. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2056. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2057. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2058. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2059. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2060. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2061. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2062. </td>
  2063. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2064. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2065. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2066. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2067. <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>
  2068. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2069. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2070. </td>
  2071. `;
  2072. tbody.appendChild(tr);
  2073. });
  2074. }
  2075. function formatTarget(addr, list, geo) {
  2076. const parts = [];
  2077. if (addr) parts.push(`<span>${addr}</span>`);
  2078. if (list) {
  2079. const inv = list.startsWith('!') ? '!' : '';
  2080. const clean = list.replace(/^!/, '');
  2081. 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>`);
  2082. }
  2083. if (geo) {
  2084. const inv = geo.startsWith('!') ? '!' : '';
  2085. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2086. 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>`);
  2087. }
  2088. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2089. return parts.join(' ');
  2090. }
  2091. function populateInterfaceSelect(selectId, currentVal = '') {
  2092. const sel = document.getElementById(selectId);
  2093. if (!sel) return;
  2094. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2095. (state.interfaces || []).forEach(i => {
  2096. const opt = document.createElement('option');
  2097. opt.value = i.name;
  2098. opt.innerText = `${i.name} (${i.role || i.type})`;
  2099. if (i.name === currentVal) opt.selected = true;
  2100. sel.appendChild(opt);
  2101. });
  2102. }
  2103. function populateAddressListSelect(selectId, currentVal = '') {
  2104. const sel = document.getElementById(selectId);
  2105. if (!sel) return;
  2106. sel.innerHTML = '<option value="">(None)</option>';
  2107. const cleanVal = (currentVal || '').replace(/^!/, '');
  2108. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2109. customNames.forEach(name => {
  2110. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2111. const opt = document.createElement('option');
  2112. opt.value = name;
  2113. opt.innerText = `${name} (${count} entries)`;
  2114. if (name === cleanVal) opt.selected = true;
  2115. sel.appendChild(opt);
  2116. });
  2117. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2118. const opt = document.createElement('option');
  2119. opt.value = cleanVal;
  2120. opt.innerText = cleanVal;
  2121. opt.selected = true;
  2122. sel.appendChild(opt);
  2123. }
  2124. }
  2125. function populateGeoIPSelect(selectId, currentVal = '') {
  2126. const sel = document.getElementById(selectId);
  2127. if (!sel) return;
  2128. sel.innerHTML = '<option value="">(None)</option>';
  2129. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2130. // Presets optgroup
  2131. const grpPresets = document.createElement('optgroup');
  2132. grpPresets.label = '⚡ Regional Presets';
  2133. const presets = [
  2134. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2135. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2136. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2137. ];
  2138. presets.forEach(p => {
  2139. const opt = document.createElement('option');
  2140. opt.value = p.code;
  2141. opt.innerText = p.label;
  2142. if (p.code === cleanVal) opt.selected = true;
  2143. grpPresets.appendChild(opt);
  2144. });
  2145. sel.appendChild(grpPresets);
  2146. // All Countries optgroup
  2147. const grpCountries = document.createElement('optgroup');
  2148. grpCountries.label = '🌍 All Countries';
  2149. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2150. countries.forEach(c => {
  2151. const opt = document.createElement('option');
  2152. opt.value = c.code;
  2153. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2154. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2155. if (c.code === cleanVal) opt.selected = true;
  2156. grpCountries.appendChild(opt);
  2157. });
  2158. sel.appendChild(grpCountries);
  2159. }
  2160. function openAddFilterModal() {
  2161. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2162. document.getElementById('filter-modal-id').value = '';
  2163. document.getElementById('filter-modal-chain').value = 'forward';
  2164. document.getElementById('filter-modal-action').value = 'accept';
  2165. document.getElementById('filter-modal-proto').value = 'all';
  2166. document.getElementById('filter-modal-src').value = '';
  2167. document.getElementById('filter-modal-dst').value = '';
  2168. document.getElementById('filter-modal-sport').value = '';
  2169. document.getElementById('filter-modal-dport').value = '';
  2170. document.getElementById('filter-modal-connmark').value = '';
  2171. document.getElementById('filter-modal-comment').value = '';
  2172. document.getElementById('filter-modal-disabled').checked = false;
  2173. document.getElementById('filter-modal-cs-established').checked = false;
  2174. document.getElementById('filter-modal-cs-related').checked = false;
  2175. document.getElementById('filter-modal-cs-new').checked = false;
  2176. document.getElementById('filter-modal-cs-invalid').checked = false;
  2177. populateInterfaceSelect('filter-modal-iniface');
  2178. populateInterfaceSelect('filter-modal-outiface');
  2179. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2180. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2181. populateAddressListSelect('filter-modal-srclist');
  2182. populateAddressListSelect('filter-modal-dstlist');
  2183. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2184. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2185. populateGeoIPSelect('filter-modal-srcgeoip');
  2186. populateGeoIPSelect('filter-modal-dstgeoip');
  2187. toggleFilterActionFields();
  2188. document.getElementById('filter-modal').classList.remove('hidden');
  2189. }
  2190. function openEditFilterModal(id) {
  2191. const r = (state.filterRules || []).find(rule => rule.id === id);
  2192. if (!r) return;
  2193. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2194. document.getElementById('filter-modal-id').value = r.id;
  2195. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2196. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2197. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2198. document.getElementById('filter-modal-src').value = r.src_address || '';
  2199. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2200. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2201. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2202. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2203. document.getElementById('filter-modal-comment').value = r.comment || '';
  2204. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2205. const states = r.connection_state || [];
  2206. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2207. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2208. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2209. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2210. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2211. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2212. const srcInv = (r.src_address_list || '').startsWith('!');
  2213. const dstInv = (r.dst_address_list || '').startsWith('!');
  2214. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2215. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2216. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2217. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2218. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2219. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2220. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2221. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2222. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2223. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2224. toggleFilterActionFields();
  2225. document.getElementById('filter-modal').classList.remove('hidden');
  2226. }
  2227. function closeFilterModal() {
  2228. document.getElementById('filter-modal').classList.add('hidden');
  2229. }
  2230. function toggleFilterActionFields() {
  2231. const act = document.getElementById('filter-modal-action').value;
  2232. const rejectBox = document.getElementById('filter-action-reject-box');
  2233. if (rejectBox) {
  2234. if (act === 'reject') rejectBox.classList.remove('hidden');
  2235. else rejectBox.classList.add('hidden');
  2236. }
  2237. }
  2238. async function submitSaveFilterRule(e) {
  2239. e.preventDefault();
  2240. const id = document.getElementById('filter-modal-id').value;
  2241. const chain = document.getElementById('filter-modal-chain').value;
  2242. const action = document.getElementById('filter-modal-action').value;
  2243. const proto = document.getElementById('filter-modal-proto').value;
  2244. const src = document.getElementById('filter-modal-src').value.trim();
  2245. const dst = document.getElementById('filter-modal-dst').value.trim();
  2246. const sport = document.getElementById('filter-modal-sport').value.trim();
  2247. const dport = document.getElementById('filter-modal-dport').value.trim();
  2248. const inIface = document.getElementById('filter-modal-iniface').value;
  2249. const outIface = document.getElementById('filter-modal-outiface').value;
  2250. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2251. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2252. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2253. srclist = '!' + srclist.replace(/^!/, '');
  2254. }
  2255. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2256. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2257. dstlist = '!' + dstlist.replace(/^!/, '');
  2258. }
  2259. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2260. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2261. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2262. }
  2263. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2264. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2265. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2266. }
  2267. const comment = document.getElementById('filter-modal-comment').value.trim();
  2268. const disabled = document.getElementById('filter-modal-disabled').checked;
  2269. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2270. const states = [];
  2271. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2272. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2273. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2274. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2275. try {
  2276. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2277. method: 'POST',
  2278. headers: { 'Content-Type': 'application/json' },
  2279. body: JSON.stringify({
  2280. id,
  2281. chain,
  2282. action,
  2283. reject_with: rejectWith,
  2284. protocol: proto,
  2285. src_address: src,
  2286. dst_address: dst,
  2287. src_port: sport,
  2288. dst_port: dport,
  2289. in_interface: inIface,
  2290. out_interface: outIface,
  2291. connection_state: states,
  2292. connection_mark: connmark,
  2293. src_address_list: srclist,
  2294. dst_address_list: dstlist,
  2295. src_geoip: srcgeoip,
  2296. dst_geoip: dstgeoip,
  2297. comment,
  2298. disabled
  2299. })
  2300. });
  2301. if (res.ok) {
  2302. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2303. closeFilterModal();
  2304. loadFirewall(false);
  2305. } else {
  2306. const err = await res.json();
  2307. showToast('Error', err.message, 'error');
  2308. }
  2309. } catch (err) {
  2310. showToast('Error', err.message, 'error');
  2311. }
  2312. }
  2313. async function moveFilterRule(id, dir) {
  2314. try {
  2315. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2316. method: 'POST',
  2317. headers: { 'Content-Type': 'application/json' },
  2318. body: JSON.stringify({ direction: dir })
  2319. });
  2320. if (res.ok) loadFirewall(false);
  2321. } catch (err) {
  2322. showToast('Error', err.message, 'error');
  2323. }
  2324. }
  2325. async function toggleFilterRuleState(id, disabled) {
  2326. try {
  2327. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2328. method: 'POST',
  2329. headers: { 'Content-Type': 'application/json' },
  2330. body: JSON.stringify({ disabled })
  2331. });
  2332. if (res.ok) loadFirewall(false);
  2333. } catch (err) {
  2334. showToast('Error', err.message, 'error');
  2335. }
  2336. }
  2337. async function deleteFilterRule(id) {
  2338. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2339. try {
  2340. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2341. if (res.ok) {
  2342. showToast('Deleted', 'Filter rule removed', 'success');
  2343. loadFirewall(false);
  2344. }
  2345. } catch (err) {
  2346. showToast('Error', err.message, 'error');
  2347. }
  2348. }
  2349. // ----------------- NAT Rules -----------------
  2350. function renderNATRules() {
  2351. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2352. const tbody = document.getElementById('nat-table-body');
  2353. const empty = document.getElementById('nat-empty');
  2354. if (!tbody) return;
  2355. tbody.innerHTML = '';
  2356. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2357. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2358. if (rules.length === 0) {
  2359. empty?.classList.remove('hidden');
  2360. return;
  2361. }
  2362. empty?.classList.add('hidden');
  2363. rules.forEach((r, idx) => {
  2364. const tr = document.createElement('tr');
  2365. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2366. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2367. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2368. tr.innerHTML = `
  2369. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2370. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2371. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2372. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2373. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2374. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2375. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2376. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2377. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2378. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2379. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2380. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2381. </td>
  2382. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2383. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2384. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2385. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2386. <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>
  2387. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2388. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2389. </td>
  2390. `;
  2391. tbody.appendChild(tr);
  2392. });
  2393. }
  2394. function openAddNATModal() {
  2395. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2396. document.getElementById('nat-modal-id').value = '';
  2397. document.getElementById('nat-modal-chain').value = 'srcnat';
  2398. document.getElementById('nat-modal-action').value = 'masquerade';
  2399. document.getElementById('nat-modal-toaddr').value = '';
  2400. document.getElementById('nat-modal-toport').value = '';
  2401. document.getElementById('nat-modal-proto').value = 'all';
  2402. document.getElementById('nat-modal-src').value = '';
  2403. document.getElementById('nat-modal-dst').value = '';
  2404. document.getElementById('nat-modal-dport').value = '';
  2405. document.getElementById('nat-modal-comment').value = '';
  2406. document.getElementById('nat-modal-disabled').checked = false;
  2407. populateInterfaceSelect('nat-modal-iniface');
  2408. populateInterfaceSelect('nat-modal-outiface');
  2409. populateAddressListSelect('nat-modal-srclist');
  2410. populateAddressListSelect('nat-modal-dstlist');
  2411. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2412. if (srcInvEl) srcInvEl.checked = false;
  2413. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2414. if (dstInvEl) dstInvEl.checked = false;
  2415. populateGeoIPSelect('nat-modal-srcgeoip');
  2416. populateGeoIPSelect('nat-modal-dstgeoip');
  2417. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2418. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2419. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2420. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2421. toggleNATActionFields();
  2422. document.getElementById('nat-modal').classList.remove('hidden');
  2423. }
  2424. function openEditNATModal(id) {
  2425. const r = (state.natRules || []).find(rule => rule.id === id);
  2426. if (!r) return;
  2427. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2428. document.getElementById('nat-modal-id').value = r.id;
  2429. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2430. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2431. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2432. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2433. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2434. document.getElementById('nat-modal-src').value = r.src_address || '';
  2435. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2436. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2437. document.getElementById('nat-modal-comment').value = r.comment || '';
  2438. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2439. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2440. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2441. const srcInv = (r.src_address_list || '').startsWith('!');
  2442. const dstInv = (r.dst_address_list || '').startsWith('!');
  2443. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2444. if (srcInvEl) srcInvEl.checked = srcInv;
  2445. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2446. if (dstInvEl) dstInvEl.checked = dstInv;
  2447. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2448. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2449. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2450. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2451. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2452. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2453. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2454. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2455. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2456. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2457. toggleNATActionFields();
  2458. document.getElementById('nat-modal').classList.remove('hidden');
  2459. }
  2460. function closeNATModal() {
  2461. document.getElementById('nat-modal').classList.add('hidden');
  2462. }
  2463. function toggleNATChainFields() {
  2464. const ch = document.getElementById('nat-modal-chain').value;
  2465. const actSel = document.getElementById('nat-modal-action');
  2466. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2467. actSel.value = 'masquerade';
  2468. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2469. actSel.value = 'dst-nat';
  2470. }
  2471. toggleNATActionFields();
  2472. }
  2473. function toggleNATActionFields() {
  2474. const act = document.getElementById('nat-modal-action').value;
  2475. const toBox = document.getElementById('nat-action-to-box');
  2476. if (toBox) {
  2477. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2478. else toBox.classList.remove('hidden');
  2479. }
  2480. }
  2481. async function submitSaveNATRule(e) {
  2482. e.preventDefault();
  2483. const id = document.getElementById('nat-modal-id').value;
  2484. const chain = document.getElementById('nat-modal-chain').value;
  2485. const action = document.getElementById('nat-modal-action').value;
  2486. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2487. const toport = document.getElementById('nat-modal-toport').value.trim();
  2488. const proto = document.getElementById('nat-modal-proto').value;
  2489. const src = document.getElementById('nat-modal-src').value.trim();
  2490. const dst = document.getElementById('nat-modal-dst').value.trim();
  2491. const dport = document.getElementById('nat-modal-dport').value.trim();
  2492. const inIface = document.getElementById('nat-modal-iniface').value;
  2493. const outIface = document.getElementById('nat-modal-outiface').value;
  2494. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2495. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2496. srclist = '!' + srclist.replace(/^!/, '');
  2497. }
  2498. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2499. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2500. dstlist = '!' + dstlist.replace(/^!/, '');
  2501. }
  2502. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2503. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2504. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2505. }
  2506. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2507. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2508. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2509. }
  2510. const comment = document.getElementById('nat-modal-comment').value.trim();
  2511. const disabled = document.getElementById('nat-modal-disabled').checked;
  2512. try {
  2513. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2514. method: 'POST',
  2515. headers: { 'Content-Type': 'application/json' },
  2516. body: JSON.stringify({
  2517. id,
  2518. chain,
  2519. action,
  2520. to_addresses: toaddr,
  2521. to_ports: toport,
  2522. protocol: proto,
  2523. src_address: src,
  2524. dst_address: dst,
  2525. dst_port: dport,
  2526. in_interface: inIface,
  2527. out_interface: outIface,
  2528. src_address_list: srclist,
  2529. dst_address_list: dstlist,
  2530. src_geoip: srcgeoip,
  2531. dst_geoip: dstgeoip,
  2532. comment,
  2533. disabled
  2534. })
  2535. });
  2536. if (res.ok) {
  2537. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2538. closeNATModal();
  2539. loadFirewall(false);
  2540. }
  2541. } catch (err) {
  2542. showToast('Error', err.message, 'error');
  2543. }
  2544. }
  2545. async function moveNATRule(id, dir) {
  2546. try {
  2547. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2548. method: 'POST',
  2549. headers: { 'Content-Type': 'application/json' },
  2550. body: JSON.stringify({ direction: dir })
  2551. });
  2552. if (res.ok) loadFirewall(false);
  2553. } catch (err) {
  2554. showToast('Error', err.message, 'error');
  2555. }
  2556. }
  2557. async function toggleNATRuleState(id, disabled) {
  2558. try {
  2559. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2560. method: 'POST',
  2561. headers: { 'Content-Type': 'application/json' },
  2562. body: JSON.stringify({ disabled })
  2563. });
  2564. if (res.ok) loadFirewall(false);
  2565. } catch (err) {
  2566. showToast('Error', err.message, 'error');
  2567. }
  2568. }
  2569. async function deleteNATRule(id) {
  2570. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2571. try {
  2572. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2573. if (res.ok) {
  2574. showToast('Deleted', 'NAT rule removed', 'success');
  2575. loadFirewall(false);
  2576. }
  2577. } catch (err) {
  2578. showToast('Error', err.message, 'error');
  2579. }
  2580. }
  2581. // ----------------- Mangle Rules -----------------
  2582. function renderMangleRules() {
  2583. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2584. const tbody = document.getElementById('mangle-table-body');
  2585. const empty = document.getElementById('mangle-empty');
  2586. if (!tbody) return;
  2587. tbody.innerHTML = '';
  2588. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2589. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2590. if (rules.length === 0) {
  2591. empty?.classList.remove('hidden');
  2592. return;
  2593. }
  2594. empty?.classList.add('hidden');
  2595. rules.forEach((r, idx) => {
  2596. const tr = document.createElement('tr');
  2597. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2598. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2599. tr.innerHTML = `
  2600. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2601. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2602. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2603. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2604. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2605. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2606. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2607. <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>
  2608. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2609. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2610. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2611. </td>
  2612. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2613. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2614. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2615. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2616. <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>
  2617. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2618. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2619. </td>
  2620. `;
  2621. tbody.appendChild(tr);
  2622. });
  2623. }
  2624. function openAddMangleModal() {
  2625. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2626. document.getElementById('mangle-modal-id').value = '';
  2627. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2628. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2629. document.getElementById('mangle-modal-newmark').value = '';
  2630. document.getElementById('mangle-modal-passthrough').checked = true;
  2631. document.getElementById('mangle-modal-src').value = '';
  2632. document.getElementById('mangle-modal-dst').value = '';
  2633. document.getElementById('mangle-modal-connmark').value = '';
  2634. document.getElementById('mangle-modal-comment').value = '';
  2635. document.getElementById('mangle-modal-disabled').checked = false;
  2636. populateInterfaceSelect('mangle-modal-iniface');
  2637. populateAddressListSelect('mangle-modal-srclist');
  2638. populateAddressListSelect('mangle-modal-dstlist');
  2639. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2640. if (srcInvEl) srcInvEl.checked = false;
  2641. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2642. if (dstInvEl) dstInvEl.checked = false;
  2643. populateGeoIPSelect('mangle-modal-srcgeoip');
  2644. populateGeoIPSelect('mangle-modal-dstgeoip');
  2645. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2646. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2647. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2648. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2649. document.getElementById('mangle-modal').classList.remove('hidden');
  2650. }
  2651. function openEditMangleModal(id) {
  2652. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2653. if (!r) return;
  2654. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2655. document.getElementById('mangle-modal-id').value = r.id;
  2656. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2657. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2658. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2659. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2660. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2661. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2662. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2663. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2664. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2665. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2666. const srcInv = (r.src_address_list || '').startsWith('!');
  2667. const dstInv = (r.dst_address_list || '').startsWith('!');
  2668. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2669. if (srcInvEl) srcInvEl.checked = srcInv;
  2670. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2671. if (dstInvEl) dstInvEl.checked = dstInv;
  2672. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2673. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2674. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2675. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2676. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2677. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2678. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2679. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2680. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2681. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2682. document.getElementById('mangle-modal').classList.remove('hidden');
  2683. }
  2684. function closeMangleModal() {
  2685. document.getElementById('mangle-modal').classList.add('hidden');
  2686. }
  2687. function toggleMangleActionFields() {
  2688. // Handled smoothly by single dynamic input
  2689. }
  2690. async function submitSaveMangleRule(e) {
  2691. e.preventDefault();
  2692. const id = document.getElementById('mangle-modal-id').value;
  2693. const chain = document.getElementById('mangle-modal-chain').value;
  2694. const action = document.getElementById('mangle-modal-action').value;
  2695. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2696. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2697. const src = document.getElementById('mangle-modal-src').value.trim();
  2698. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2699. const inIface = document.getElementById('mangle-modal-iniface').value;
  2700. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2701. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2702. srclist = '!' + srclist.replace(/^!/, '');
  2703. }
  2704. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2705. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2706. dstlist = '!' + dstlist.replace(/^!/, '');
  2707. }
  2708. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2709. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2710. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2711. }
  2712. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2713. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2714. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2715. }
  2716. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2717. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2718. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2719. const payload = {
  2720. id,
  2721. chain,
  2722. action,
  2723. passthrough,
  2724. src_address: src,
  2725. dst_address: dst,
  2726. in_interface: inIface,
  2727. src_address_list: srclist,
  2728. dst_address_list: dstlist,
  2729. src_geoip: srcgeoip,
  2730. dst_geoip: dstgeoip,
  2731. connection_mark: connmark,
  2732. comment,
  2733. disabled
  2734. };
  2735. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2736. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2737. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2738. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2739. try {
  2740. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2741. method: 'POST',
  2742. headers: { 'Content-Type': 'application/json' },
  2743. body: JSON.stringify(payload)
  2744. });
  2745. if (res.ok) {
  2746. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2747. closeMangleModal();
  2748. loadFirewall(false);
  2749. }
  2750. } catch (err) {
  2751. showToast('Error', err.message, 'error');
  2752. }
  2753. }
  2754. async function moveMangleRule(id, dir) {
  2755. try {
  2756. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2757. method: 'POST',
  2758. headers: { 'Content-Type': 'application/json' },
  2759. body: JSON.stringify({ direction: dir })
  2760. });
  2761. if (res.ok) loadFirewall(false);
  2762. } catch (err) {
  2763. showToast('Error', err.message, 'error');
  2764. }
  2765. }
  2766. async function toggleMangleRuleState(id, disabled) {
  2767. try {
  2768. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2769. method: 'POST',
  2770. headers: { 'Content-Type': 'application/json' },
  2771. body: JSON.stringify({ disabled })
  2772. });
  2773. if (res.ok) loadFirewall(false);
  2774. } catch (err) {
  2775. showToast('Error', err.message, 'error');
  2776. }
  2777. }
  2778. async function deleteMangleRule(id) {
  2779. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2780. try {
  2781. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2782. if (res.ok) {
  2783. showToast('Deleted', 'Mangle rule removed', 'success');
  2784. loadFirewall(false);
  2785. }
  2786. } catch (err) {
  2787. showToast('Error', err.message, 'error');
  2788. }
  2789. }
  2790. // ----------------- Address Lists -----------------
  2791. function renderAddressLists() {
  2792. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2793. const tbody = document.getElementById('addrlist-table-body');
  2794. const empty = document.getElementById('addrlist-empty');
  2795. if (!tbody) return;
  2796. tbody.innerHTML = '';
  2797. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2798. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2799. // Update filter select
  2800. const sel = document.getElementById('addrlist-filter-name');
  2801. if (sel) {
  2802. const cur = sel.value;
  2803. sel.innerHTML = '<option value="">All Lists</option>';
  2804. const set = new Set((state.addressLists || []).map(a => a.name));
  2805. set.forEach(n => {
  2806. const opt = document.createElement('option');
  2807. opt.value = n;
  2808. opt.innerText = n;
  2809. if (n === cur) opt.selected = true;
  2810. sel.appendChild(opt);
  2811. });
  2812. }
  2813. if (entries.length === 0) {
  2814. empty?.classList.remove('hidden');
  2815. return;
  2816. }
  2817. empty?.classList.add('hidden');
  2818. entries.forEach((e, idx) => {
  2819. const tr = document.createElement('tr');
  2820. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2821. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2822. tr.innerHTML = `
  2823. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2824. <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>
  2825. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2826. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2827. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2828. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2829. <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>
  2830. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2831. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2832. </td>
  2833. `;
  2834. tbody.appendChild(tr);
  2835. });
  2836. }
  2837. function openAddAddrListModal() {
  2838. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2839. document.getElementById('addrlist-modal-id').value = '';
  2840. document.getElementById('addrlist-modal-name').value = '';
  2841. document.getElementById('addrlist-modal-addr').value = '';
  2842. document.getElementById('addrlist-modal-comment').value = '';
  2843. document.getElementById('addrlist-modal-disabled').checked = false;
  2844. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2845. if (submitBtn) submitBtn.innerText = 'Add to List';
  2846. document.getElementById('addrlist-modal').classList.remove('hidden');
  2847. }
  2848. function openEditAddrListModal(id) {
  2849. const e = (state.addressLists || []).find(item => item.id === id);
  2850. if (!e) return;
  2851. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2852. document.getElementById('addrlist-modal-id').value = e.id;
  2853. document.getElementById('addrlist-modal-name').value = e.name;
  2854. document.getElementById('addrlist-modal-addr').value = e.address;
  2855. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2856. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2857. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2858. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2859. document.getElementById('addrlist-modal').classList.remove('hidden');
  2860. }
  2861. function closeAddrListModal() {
  2862. document.getElementById('addrlist-modal').classList.add('hidden');
  2863. }
  2864. async function submitSaveAddrList(e) {
  2865. e.preventDefault();
  2866. const id = document.getElementById('addrlist-modal-id').value;
  2867. const name = document.getElementById('addrlist-modal-name').value.trim();
  2868. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2869. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2870. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2871. try {
  2872. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2873. method: 'POST',
  2874. headers: { 'Content-Type': 'application/json' },
  2875. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2876. });
  2877. if (res.ok) {
  2878. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2879. closeAddrListModal();
  2880. loadFirewall(false);
  2881. } else {
  2882. const err = await res.json();
  2883. showToast('Error', err.message || 'Failed to save address list', 'error');
  2884. }
  2885. } catch (err) {
  2886. showToast('Error', err.message, 'error');
  2887. }
  2888. }
  2889. async function toggleAddrListState(id, disabled) {
  2890. try {
  2891. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2892. method: 'POST',
  2893. headers: { 'Content-Type': 'application/json' },
  2894. body: JSON.stringify({ disabled })
  2895. });
  2896. if (res.ok) {
  2897. loadFirewall(false);
  2898. }
  2899. } catch (err) {
  2900. showToast('Error', err.message, 'error');
  2901. }
  2902. }
  2903. async function deleteAddrList(id) {
  2904. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2905. try {
  2906. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2907. if (res.ok) {
  2908. showToast('Deleted', 'Address list item removed', 'info');
  2909. loadFirewall(false);
  2910. }
  2911. } catch (err) {
  2912. showToast('Error', err.message, 'error');
  2913. }
  2914. }
  2915. // ----------------- Geo-Location IP Management -----------------
  2916. async function loadGeoIP() {
  2917. try {
  2918. const [statusRes, countriesRes] = await Promise.all([
  2919. fetch(`${API_BASE}/firewall/geoip/status`),
  2920. fetch(`${API_BASE}/firewall/geoip/countries`)
  2921. ]);
  2922. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2923. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2924. updateGeoHeader();
  2925. renderGeoCountries();
  2926. } catch (err) {
  2927. console.error('Failed to load GeoIP:', err);
  2928. }
  2929. }
  2930. function updateGeoHeader() {
  2931. const s = state.geoStatus || {};
  2932. const statusBadge = document.getElementById('geo-status-badge');
  2933. if (statusBadge) {
  2934. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2935. statusBadge.className = s.auto_update
  2936. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2937. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2938. }
  2939. const intervalLabel = document.getElementById('geo-interval-label');
  2940. if (intervalLabel) {
  2941. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  2942. }
  2943. const activeCountEl = document.getElementById('geo-stat-active-countries');
  2944. if (activeCountEl) activeCountEl.innerText = (s.enabled_count || 0).toLocaleString();
  2945. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  2946. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  2947. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  2948. if (lastSyncEl) {
  2949. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  2950. const d = new Date(s.last_updated);
  2951. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2952. } else {
  2953. lastSyncEl.innerText = 'Never (Sync Pending)';
  2954. }
  2955. }
  2956. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  2957. if (nextSyncEl) {
  2958. if (s.next_update && !s.next_update.startsWith('0001')) {
  2959. const d = new Date(s.next_update);
  2960. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2961. } else {
  2962. nextSyncEl.innerText = '-';
  2963. }
  2964. }
  2965. const badge = document.getElementById('fw-badge-geo');
  2966. if (badge) badge.innerText = s.enabled_count || 0;
  2967. }
  2968. function renderGeoCountries() {
  2969. const tbody = document.getElementById('geo-table-body');
  2970. const empty = document.getElementById('geo-empty');
  2971. if (!tbody) return;
  2972. tbody.innerHTML = '';
  2973. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  2974. const continent = document.getElementById('geo-continent-filter')?.value || '';
  2975. const enabledOnly = document.getElementById('geo-filter-enabled-only')?.checked;
  2976. const countries = (state.geoCountries || []).filter(c => {
  2977. if (enabledOnly && !c.enabled) return false;
  2978. if (continent && c.continent !== continent) return false;
  2979. if (q) {
  2980. const matchCode = c.code.toLowerCase().includes(q);
  2981. const matchName = c.name.toLowerCase().includes(q);
  2982. if (!matchCode && !matchName) return false;
  2983. }
  2984. return true;
  2985. });
  2986. if (countries.length === 0) {
  2987. empty?.classList.remove('hidden');
  2988. return;
  2989. }
  2990. empty?.classList.add('hidden');
  2991. countries.forEach(c => {
  2992. const tr = document.createElement('tr');
  2993. tr.className = `hover:bg-slate-800/40 transition text-xs ${c.enabled ? 'bg-emerald-950/10' : ''}`;
  2994. tr.innerHTML = `
  2995. <td class="py-2.5 px-3 text-center">
  2996. <span class="px-2 py-0.5 rounded font-mono font-bold ${c.enabled ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  2997. ${c.code}
  2998. </span>
  2999. </td>
  3000. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3001. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3002. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3003. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3004. </td>
  3005. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3006. <td class="py-2.5 px-3">
  3007. ${c.enabled
  3008. ? '<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">ENABLED</span>'
  3009. : '<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-500">DISABLED</span>'}
  3010. </td>
  3011. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3012. ${c.enabled
  3013. ? `<button onclick="toggleGeoCountry('${c.code}', false)" class="text-xs text-rose-400 hover:underline font-semibold">Disable</button>`
  3014. : `<button onclick="toggleGeoCountry('${c.code}', true)" class="text-xs text-emerald-400 hover:underline font-semibold">Enable</button>`}
  3015. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300" title="Re-download latest country IP blocks">Sync</button>
  3016. <button onclick="viewGeoSubnets('${c.code}', '${c.name.replace(/'/g, "\\'")}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3017. </td>
  3018. `;
  3019. tbody.appendChild(tr);
  3020. });
  3021. }
  3022. async function toggleGeoCountry(code, enabled) {
  3023. try {
  3024. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3025. method: 'POST',
  3026. headers: { 'Content-Type': 'application/json' },
  3027. body: JSON.stringify({ enabled })
  3028. });
  3029. if (res.ok) {
  3030. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3031. loadGeoIP();
  3032. } else {
  3033. const err = await res.json();
  3034. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3035. }
  3036. } catch (err) {
  3037. showToast('Error', err.message, 'error');
  3038. }
  3039. }
  3040. async function updateGeoCountry(code) {
  3041. try {
  3042. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3043. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3044. if (res.ok) {
  3045. const data = await res.json();
  3046. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3047. loadGeoIP();
  3048. } else {
  3049. const err = await res.json();
  3050. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3051. }
  3052. } catch (err) {
  3053. showToast('Error', err.message, 'error');
  3054. }
  3055. }
  3056. async function triggerGeoUpdateNow() {
  3057. const spinner = document.getElementById('geo-update-spinner');
  3058. if (spinner) spinner.classList.remove('hidden');
  3059. try {
  3060. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3061. if (res.ok) {
  3062. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3063. setTimeout(() => {
  3064. loadGeoIP();
  3065. if (spinner) spinner.classList.add('hidden');
  3066. }, 2500);
  3067. } else {
  3068. const err = await res.json();
  3069. showToast('Notice', err.message || 'Update in progress', 'info');
  3070. if (spinner) spinner.classList.add('hidden');
  3071. }
  3072. } catch (err) {
  3073. showToast('Error', err.message, 'error');
  3074. if (spinner) spinner.classList.add('hidden');
  3075. }
  3076. }
  3077. async function applyGeoPreset(preset) {
  3078. try {
  3079. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3080. method: 'POST',
  3081. headers: { 'Content-Type': 'application/json' },
  3082. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3083. });
  3084. if (res.ok) {
  3085. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3086. loadGeoIP();
  3087. }
  3088. } catch (err) {
  3089. showToast('Error', err.message, 'error');
  3090. }
  3091. }
  3092. function openGeoIntervalModal() {
  3093. const s = state.geoStatus || {};
  3094. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3095. const sel = document.getElementById('geo-cfg-interval');
  3096. const customBox = document.getElementById('geo-cfg-custom-box');
  3097. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3098. const curHours = s.interval_hours || 24;
  3099. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3100. if (matchOption) {
  3101. sel.value = String(curHours);
  3102. customBox.classList.add('hidden');
  3103. } else {
  3104. sel.value = 'custom';
  3105. customHoursInput.value = curHours;
  3106. customBox.classList.remove('hidden');
  3107. }
  3108. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3109. }
  3110. function closeGeoIntervalModal() {
  3111. document.getElementById('geo-interval-modal').classList.add('hidden');
  3112. }
  3113. function toggleCustomGeoInterval() {
  3114. const val = document.getElementById('geo-cfg-interval').value;
  3115. const customBox = document.getElementById('geo-cfg-custom-box');
  3116. if (val === 'custom') {
  3117. customBox.classList.remove('hidden');
  3118. } else {
  3119. customBox.classList.add('hidden');
  3120. }
  3121. }
  3122. async function submitGeoIntervalSettings(e) {
  3123. e.preventDefault();
  3124. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3125. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3126. let hours = 24;
  3127. if (intervalVal === 'custom') {
  3128. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3129. } else {
  3130. hours = parseInt(intervalVal, 10) || 24;
  3131. }
  3132. try {
  3133. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3134. method: 'POST',
  3135. headers: { 'Content-Type': 'application/json' },
  3136. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3137. });
  3138. if (res.ok) {
  3139. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3140. closeGeoIntervalModal();
  3141. loadGeoIP();
  3142. } else {
  3143. const err = await res.json();
  3144. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3145. }
  3146. } catch (err) {
  3147. showToast('Error', err.message, 'error');
  3148. }
  3149. }
  3150. async function viewGeoSubnets(code, name) {
  3151. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3152. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3153. const listEl = document.getElementById('geo-subnets-list');
  3154. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3155. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3156. try {
  3157. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3158. if (res.ok) {
  3159. const data = await res.json();
  3160. const subnets = data.subnets || [];
  3161. if (subnets.length === 0) {
  3162. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3163. } else {
  3164. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3165. }
  3166. } else {
  3167. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3168. }
  3169. } catch (err) {
  3170. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3171. }
  3172. }
  3173. function closeGeoSubnetsModal() {
  3174. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3175. }
  3176. // ----------------- Active Connections Tracking -----------------
  3177. async function loadConnections() {
  3178. try {
  3179. const res = await fetch(`${API_BASE}/firewall/connections`);
  3180. const data = await res.json();
  3181. state.connections = Array.isArray(data) ? data : [];
  3182. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3183. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3184. renderConnections();
  3185. } catch (err) {
  3186. console.error('Failed to load connections:', err);
  3187. }
  3188. }
  3189. function renderConnections() {
  3190. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3191. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3192. const tbody = document.getElementById('conns-table-body');
  3193. const empty = document.getElementById('conns-empty');
  3194. if (!tbody) return;
  3195. tbody.innerHTML = '';
  3196. const conns = (state.connections || []).filter(c => {
  3197. if (protoFilter && c.protocol !== protoFilter) return false;
  3198. if (search) {
  3199. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3200. if (!line.includes(search)) return false;
  3201. }
  3202. return true;
  3203. });
  3204. if (conns.length === 0) {
  3205. empty?.classList.remove('hidden');
  3206. return;
  3207. }
  3208. empty?.classList.add('hidden');
  3209. conns.slice(0, 150).forEach(c => {
  3210. const tr = document.createElement('tr');
  3211. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3212. let stateColor = 'text-slate-400';
  3213. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3214. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3215. tr.innerHTML = `
  3216. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3217. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3218. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3219. <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>
  3220. <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>
  3221. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3222. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3223. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3224. <td class="py-2.5 px-3 text-right font-sans">
  3225. <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>
  3226. </td>
  3227. `;
  3228. tbody.appendChild(tr);
  3229. });
  3230. }
  3231. async function killConnection(protocol, src, sport, dst, dport) {
  3232. try {
  3233. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3234. method: 'POST',
  3235. headers: { 'Content-Type': 'application/json' },
  3236. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3237. });
  3238. if (res.ok) {
  3239. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3240. loadConnections();
  3241. }
  3242. } catch (err) {
  3243. showToast('Error', err.message, 'error');
  3244. }
  3245. }
  3246. async function resetFirewallCounters() {
  3247. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3248. try {
  3249. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3250. if (res.ok) {
  3251. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3252. loadFirewall(false);
  3253. }
  3254. } catch (err) {
  3255. showToast('Error', err.message, 'error');
  3256. }
  3257. }
  3258. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3259. function switchRoutesSubTab(tab) {
  3260. state.routesSubTab = tab;
  3261. const tabs = ['routes', 'rules', 'tables'];
  3262. tabs.forEach(t => {
  3263. const panel = document.getElementById(`routes-subtab-${t}`);
  3264. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3265. if (panel) {
  3266. if (t === tab) panel.classList.remove('hidden');
  3267. else panel.classList.add('hidden');
  3268. }
  3269. if (btn) {
  3270. if (t === tab) {
  3271. 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';
  3272. } else {
  3273. 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';
  3274. }
  3275. }
  3276. });
  3277. }
  3278. async function loadRoutes() {
  3279. try {
  3280. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3281. fetch(`${API_BASE}/routes`),
  3282. fetch(`${API_BASE}/routing/rules`),
  3283. fetch(`${API_BASE}/routing/tables`)
  3284. ]);
  3285. if (routesRes.ok) state.routes = await routesRes.json();
  3286. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3287. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3288. const bRoutes = document.getElementById('routes-badge-routes');
  3289. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3290. const bRules = document.getElementById('routes-badge-rules');
  3291. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3292. const bTables = document.getElementById('routes-badge-tables');
  3293. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3294. const bRoutesCount = document.getElementById('badge-routes-count');
  3295. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3296. renderRoutesList();
  3297. renderPolicyRules();
  3298. renderRoutingTables();
  3299. } catch (err) {
  3300. console.error('Failed to load routing:', err);
  3301. }
  3302. }
  3303. function renderRoutesList() {
  3304. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3305. const tbody = document.getElementById('routes-table-body');
  3306. const empty = document.getElementById('routes-empty');
  3307. if (!tbody) return;
  3308. tbody.innerHTML = '';
  3309. // Update table filter select
  3310. const sel = document.getElementById('routes-filter-table');
  3311. if (sel) {
  3312. const cur = sel.value;
  3313. sel.innerHTML = '<option value="">All Tables</option>';
  3314. (state.routingTables || []).forEach(t => {
  3315. const opt = document.createElement('option');
  3316. opt.value = t.name;
  3317. opt.innerText = t.name;
  3318. if (t.name === cur) opt.selected = true;
  3319. sel.appendChild(opt);
  3320. });
  3321. }
  3322. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3323. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3324. if (routes.length === 0) {
  3325. empty?.classList.remove('hidden');
  3326. return;
  3327. }
  3328. empty?.classList.add('hidden');
  3329. routes.forEach(r => {
  3330. const tr = document.createElement('tr');
  3331. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3332. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3333. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3334. let flags = '';
  3335. if (r.dynamic) flags += 'D';
  3336. if (r.active) flags += 'A';
  3337. if (r.connect) flags += 'C';
  3338. if (r.static) flags += 'S';
  3339. if (r.disabled) flags += 'X';
  3340. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3341. tr.innerHTML = `
  3342. <td class="py-2.5 px-3 text-center">
  3343. <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'}">
  3344. ${flags || '-'}
  3345. </span>
  3346. </td>
  3347. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3348. <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>
  3349. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3350. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3351. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3352. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3353. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3354. ${r.static ? `
  3355. <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>
  3356. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3357. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3358. ` : `
  3359. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3360. `}
  3361. </td>
  3362. `;
  3363. tbody.appendChild(tr);
  3364. });
  3365. }
  3366. function openAddRouteModal() {
  3367. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3368. document.getElementById('route-modal-id').value = '';
  3369. document.getElementById('route-modal-old-dst').value = '';
  3370. document.getElementById('route-modal-old-gw').value = '';
  3371. document.getElementById('route-modal-old-distance').value = '';
  3372. document.getElementById('route-modal-old-table').value = '';
  3373. document.getElementById('route-modal-old-iface').value = '';
  3374. const dstInput = document.getElementById('route-modal-dst');
  3375. const gwInput = document.getElementById('route-modal-gw');
  3376. const distInput = document.getElementById('route-modal-distance');
  3377. const ifaceSelect = document.getElementById('route-modal-iface');
  3378. const tableSelect = document.getElementById('route-modal-table');
  3379. const commentInput = document.getElementById('route-modal-comment');
  3380. const disCheck = document.getElementById('route-modal-disabled');
  3381. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3382. dstInput.disabled = false;
  3383. dstInput.value = '0.0.0.0/0';
  3384. gwInput.disabled = false;
  3385. gwInput.value = '';
  3386. distInput.disabled = false;
  3387. distInput.value = '1';
  3388. ifaceSelect.disabled = false;
  3389. tableSelect.disabled = false;
  3390. commentInput.disabled = false;
  3391. commentInput.value = '';
  3392. disCheck.disabled = false;
  3393. disCheck.checked = false;
  3394. if (saveBtn) saveBtn.classList.remove('hidden');
  3395. populateInterfaceSelect('route-modal-iface');
  3396. // Populate tables
  3397. tableSelect.innerHTML = '';
  3398. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3399. const opt = document.createElement('option');
  3400. opt.value = t.name;
  3401. opt.innerText = t.name;
  3402. if (t.name === 'main') opt.selected = true;
  3403. tableSelect.appendChild(opt);
  3404. });
  3405. document.getElementById('route-modal').classList.remove('hidden');
  3406. }
  3407. function openEditRouteModal(id) {
  3408. const r = (state.routes || []).find(route => route.id === id);
  3409. if (!r) return;
  3410. const isStatic = !!r.static;
  3411. document.getElementById('route-modal-title').innerText = isStatic
  3412. ? `Edit Route: ${r.dst_address}`
  3413. : `Route Properties (Read Only): ${r.dst_address}`;
  3414. document.getElementById('route-modal-id').value = r.id;
  3415. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3416. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3417. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3418. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3419. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3420. const dstInput = document.getElementById('route-modal-dst');
  3421. const gwInput = document.getElementById('route-modal-gw');
  3422. const distInput = document.getElementById('route-modal-distance');
  3423. const ifaceSelect = document.getElementById('route-modal-iface');
  3424. const tableSelect = document.getElementById('route-modal-table');
  3425. const commentInput = document.getElementById('route-modal-comment');
  3426. const disCheck = document.getElementById('route-modal-disabled');
  3427. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3428. dstInput.value = r.dst_address;
  3429. gwInput.value = r.gateway || '';
  3430. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3431. commentInput.value = r.comment || '';
  3432. disCheck.checked = !!r.disabled;
  3433. dstInput.disabled = !isStatic;
  3434. gwInput.disabled = !isStatic;
  3435. distInput.disabled = !isStatic;
  3436. ifaceSelect.disabled = !isStatic;
  3437. tableSelect.disabled = !isStatic;
  3438. commentInput.disabled = !isStatic;
  3439. disCheck.disabled = !isStatic;
  3440. if (saveBtn) {
  3441. if (isStatic) {
  3442. saveBtn.classList.remove('hidden');
  3443. } else {
  3444. saveBtn.classList.add('hidden');
  3445. }
  3446. }
  3447. populateInterfaceSelect('route-modal-iface', r.interface);
  3448. tableSelect.innerHTML = '';
  3449. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3450. const opt = document.createElement('option');
  3451. opt.value = t.name;
  3452. opt.innerText = t.name;
  3453. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3454. tableSelect.appendChild(opt);
  3455. });
  3456. document.getElementById('route-modal').classList.remove('hidden');
  3457. }
  3458. function closeRouteModal() {
  3459. document.getElementById('route-modal').classList.add('hidden');
  3460. }
  3461. async function submitSaveRoute(e) {
  3462. e.preventDefault();
  3463. const id = document.getElementById('route-modal-id').value;
  3464. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3465. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3466. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3467. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3468. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3469. const dst = document.getElementById('route-modal-dst').value.trim();
  3470. const gw = document.getElementById('route-modal-gw').value.trim();
  3471. const table = document.getElementById('route-modal-table').value;
  3472. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3473. const iface = document.getElementById('route-modal-iface').value;
  3474. const comment = document.getElementById('route-modal-comment').value.trim();
  3475. const disabled = document.getElementById('route-modal-disabled').checked;
  3476. if (!dst) {
  3477. showToast('Error', 'Destination address is required', 'error');
  3478. return;
  3479. }
  3480. if (!gw && !iface) {
  3481. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3482. return;
  3483. }
  3484. const payload = {
  3485. id,
  3486. old_dst_address: oldDst,
  3487. old_gateway: oldGw,
  3488. old_routing_table: oldTable,
  3489. old_interface: oldIface,
  3490. dst_address: dst,
  3491. gateway: gw || iface,
  3492. routing_table: table,
  3493. distance,
  3494. interface: iface,
  3495. comment,
  3496. disabled
  3497. };
  3498. if (oldDistStr !== undefined && oldDistStr !== '') {
  3499. payload.old_distance = parseInt(oldDistStr, 10);
  3500. }
  3501. try {
  3502. const res = await fetch(`${API_BASE}/routes`, {
  3503. method: 'POST',
  3504. headers: { 'Content-Type': 'application/json' },
  3505. body: JSON.stringify(payload)
  3506. });
  3507. if (res.ok) {
  3508. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3509. closeRouteModal();
  3510. loadRoutes();
  3511. } else {
  3512. const err = await res.json();
  3513. showToast('Error', err.message || 'Failed to save route', 'error');
  3514. }
  3515. } catch (err) {
  3516. showToast('Error', err.message, 'error');
  3517. }
  3518. }
  3519. async function toggleRouteState(id, disabled) {
  3520. try {
  3521. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3522. method: 'POST',
  3523. headers: { 'Content-Type': 'application/json' },
  3524. body: JSON.stringify({ disabled })
  3525. });
  3526. if (res.ok) loadRoutes();
  3527. } catch (err) {
  3528. showToast('Error', err.message, 'error');
  3529. }
  3530. }
  3531. async function deleteRoute(id) {
  3532. if (!confirm('Are you sure you want to delete this route?')) return;
  3533. try {
  3534. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3535. if (res.ok) {
  3536. showToast('Deleted', 'Route removed', 'success');
  3537. loadRoutes();
  3538. }
  3539. } catch (err) {
  3540. showToast('Error', err.message, 'error');
  3541. }
  3542. }
  3543. // ----------------- Policy Rules (/ip route rule) -----------------
  3544. function renderPolicyRules() {
  3545. const tbody = document.getElementById('rules-table-body');
  3546. const empty = document.getElementById('rules-empty');
  3547. if (!tbody) return;
  3548. tbody.innerHTML = '';
  3549. const rules = state.policyRules || [];
  3550. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3551. if (rules.length === 0) {
  3552. empty?.classList.remove('hidden');
  3553. return;
  3554. }
  3555. empty?.classList.add('hidden');
  3556. rules.forEach(pr => {
  3557. const tr = document.createElement('tr');
  3558. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3559. tr.innerHTML = `
  3560. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3561. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3562. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3563. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3564. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3565. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3566. <td class="py-2.5 px-3 text-right font-sans">
  3567. ${pr.priority < 32766 && pr.priority > 0 ? `
  3568. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3569. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3570. </td>
  3571. `;
  3572. tbody.appendChild(tr);
  3573. });
  3574. }
  3575. function openAddPolicyRuleModal() {
  3576. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3577. document.getElementById('prule-modal-mark').value = '';
  3578. document.getElementById('prule-modal-src').value = '';
  3579. document.getElementById('prule-modal-dst').value = '';
  3580. const sel = document.getElementById('prule-modal-table');
  3581. sel.innerHTML = '';
  3582. (state.routingTables || []).forEach(t => {
  3583. const opt = document.createElement('option');
  3584. opt.value = t.name;
  3585. opt.innerText = t.name;
  3586. sel.appendChild(opt);
  3587. });
  3588. document.getElementById('prule-modal').classList.remove('hidden');
  3589. }
  3590. function closePolicyRuleModal() {
  3591. document.getElementById('prule-modal').classList.add('hidden');
  3592. }
  3593. async function submitSavePolicyRule(e) {
  3594. e.preventDefault();
  3595. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3596. const mark = document.getElementById('prule-modal-mark').value.trim();
  3597. const src = document.getElementById('prule-modal-src').value.trim();
  3598. const dst = document.getElementById('prule-modal-dst').value.trim();
  3599. const table = document.getElementById('prule-modal-table').value;
  3600. const action = document.getElementById('prule-modal-action').value;
  3601. try {
  3602. const res = await fetch(`${API_BASE}/routing/rules`, {
  3603. method: 'POST',
  3604. headers: { 'Content-Type': 'application/json' },
  3605. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3606. });
  3607. if (res.ok) {
  3608. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3609. closePolicyRuleModal();
  3610. loadRoutes();
  3611. } else {
  3612. const err = await res.json();
  3613. showToast('Error', err.message, 'error');
  3614. }
  3615. } catch (err) {
  3616. showToast('Error', err.message, 'error');
  3617. }
  3618. }
  3619. async function deletePolicyRule(id) {
  3620. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3621. try {
  3622. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3623. if (res.ok) {
  3624. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3625. loadRoutes();
  3626. }
  3627. } catch (err) {
  3628. showToast('Error', err.message, 'error');
  3629. }
  3630. }
  3631. // ----------------- Routing Tables -----------------
  3632. function renderRoutingTables() {
  3633. const tbody = document.getElementById('tables-table-body');
  3634. if (!tbody) return;
  3635. tbody.innerHTML = '';
  3636. (state.routingTables || []).forEach(t => {
  3637. const tr = document.createElement('tr');
  3638. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3639. tr.innerHTML = `
  3640. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3641. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3642. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3643. `;
  3644. tbody.appendChild(tr);
  3645. });
  3646. }
  3647. function openAddTableModal() {
  3648. document.getElementById('table-modal-name').value = '';
  3649. document.getElementById('table-modal-id').value = '';
  3650. document.getElementById('table-modal-comment').value = '';
  3651. document.getElementById('table-modal').classList.remove('hidden');
  3652. }
  3653. function closeTableModal() {
  3654. document.getElementById('table-modal').classList.add('hidden');
  3655. }
  3656. async function submitSaveTable(e) {
  3657. e.preventDefault();
  3658. const name = document.getElementById('table-modal-name').value.trim();
  3659. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3660. const comment = document.getElementById('table-modal-comment').value.trim();
  3661. try {
  3662. const res = await fetch(`${API_BASE}/routing/tables`, {
  3663. method: 'POST',
  3664. headers: { 'Content-Type': 'application/json' },
  3665. body: JSON.stringify({ name, table_id: id, comment })
  3666. });
  3667. if (res.ok) {
  3668. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3669. closeTableModal();
  3670. loadRoutes();
  3671. } else {
  3672. const err = await res.json();
  3673. showToast('Error', err.message, 'error');
  3674. }
  3675. } catch (err) {
  3676. showToast('Error', err.message, 'error');
  3677. }
  3678. }
  3679. async function loadDebianConfig() {
  3680. const view = document.getElementById('debian-config-view');
  3681. view.innerText = 'Generating live configuration...';
  3682. try {
  3683. const res = await fetch(`${API_BASE}/debian/config`);
  3684. const data = await res.json();
  3685. view.innerText = data.content || '# Empty config';
  3686. } catch (err) {
  3687. view.innerText = 'Failed to generate Debian network config.';
  3688. }
  3689. }
  3690. async function saveDebianConfig() {
  3691. try {
  3692. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3693. const data = await res.json();
  3694. if (res.ok) {
  3695. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3696. loadDebianConfig();
  3697. }
  3698. } catch (err) {
  3699. showToast('Error', err.message, 'error');
  3700. }
  3701. }
  3702. function showToast(title, message, type = 'info') {
  3703. const container = document.getElementById('toast-container');
  3704. const toast = document.createElement('div');
  3705. const borderColors = {
  3706. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3707. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3708. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3709. };
  3710. 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}`;
  3711. toast.innerHTML = `
  3712. <div class="flex-1">
  3713. <div class="font-bold text-xs text-white">${title}</div>
  3714. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3715. </div>
  3716. `;
  3717. container.appendChild(toast);
  3718. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3719. setTimeout(() => {
  3720. toast.classList.add('opacity-0', 'translate-y-2');
  3721. setTimeout(() => toast.remove(), 300);
  3722. }, 4000);
  3723. }
  3724. function formatTraffic(bytesPerSec) {
  3725. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3726. const kb = bytesPerSec / 1024;
  3727. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3728. const mb = kb / 1024;
  3729. return `${mb.toFixed(2)} MB/s`;
  3730. }
  3731. function toggleSidebar() {
  3732. const sb = document.getElementById('sidebar');
  3733. sb.classList.toggle('-translate-x-full');
  3734. }
  3735. // ======================== EoIP (Ethernet over IP) ========================
  3736. async function loadEoIP(populate = true) {
  3737. try {
  3738. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3739. const data = await res.json();
  3740. state.eoipTunnels = Array.isArray(data) ? data : [];
  3741. const badge = document.getElementById('eoip-count-badge');
  3742. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3743. const sideBadge = document.getElementById('badge-eoip-count');
  3744. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3745. renderEoIPTunnels();
  3746. } catch (err) {
  3747. console.error('Failed to load EoIP:', err);
  3748. }
  3749. }
  3750. function renderEoIPTunnels() {
  3751. const tbody = document.getElementById('eoip-table-body');
  3752. const empty = document.getElementById('eoip-empty');
  3753. if (!tbody) return;
  3754. tbody.innerHTML = '';
  3755. const tunnels = state.eoipTunnels || [];
  3756. if (tunnels.length === 0) {
  3757. empty?.classList.remove('hidden');
  3758. return;
  3759. }
  3760. empty?.classList.add('hidden');
  3761. tunnels.forEach(t => {
  3762. const tr = document.createElement('tr');
  3763. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3764. tr.innerHTML = `
  3765. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3766. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3767. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3768. <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>
  3769. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3770. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3771. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3772. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3773. <td class="py-2.5 px-3 font-mono text-[11px]">
  3774. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3775. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3776. </td>
  3777. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3778. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3779. <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>
  3780. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3781. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3782. </td>
  3783. `;
  3784. tbody.appendChild(tr);
  3785. });
  3786. }
  3787. function openAddEoIPModal() {
  3788. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3789. document.getElementById('eoip-modal-id').value = '';
  3790. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3791. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3792. document.getElementById('eoip-modal-remote').value = '';
  3793. document.getElementById('eoip-modal-ip').value = '';
  3794. document.getElementById('eoip-modal-local').value = '';
  3795. document.getElementById('eoip-modal-mac').value = '';
  3796. document.getElementById('eoip-modal-mtu').value = '1500';
  3797. document.getElementById('eoip-modal-comment').value = '';
  3798. document.getElementById('eoip-modal-clampmss').checked = true;
  3799. document.getElementById('eoip-modal-disabled').checked = false;
  3800. document.getElementById('eoip-modal').classList.remove('hidden');
  3801. }
  3802. function openEditEoIPModal(id) {
  3803. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3804. if (!t) return;
  3805. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3806. document.getElementById('eoip-modal-id').value = t.id;
  3807. document.getElementById('eoip-modal-name').value = t.name;
  3808. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3809. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3810. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3811. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3812. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3813. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3814. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3815. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3816. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3817. document.getElementById('eoip-modal').classList.remove('hidden');
  3818. }
  3819. function closeEoIPModal() {
  3820. document.getElementById('eoip-modal').classList.add('hidden');
  3821. }
  3822. async function submitSaveEoIP(e) {
  3823. e.preventDefault();
  3824. const id = document.getElementById('eoip-modal-id').value;
  3825. const name = document.getElementById('eoip-modal-name').value.trim();
  3826. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3827. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3828. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3829. const local = document.getElementById('eoip-modal-local').value.trim();
  3830. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3831. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3832. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3833. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3834. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3835. try {
  3836. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3837. method: 'POST',
  3838. headers: { 'Content-Type': 'application/json' },
  3839. body: JSON.stringify({
  3840. id,
  3841. name,
  3842. tunnel_id: tunnelId,
  3843. remote_address: remote,
  3844. ip_address: ipAddress,
  3845. local_address: local,
  3846. mac_address: mac,
  3847. mtu,
  3848. clamp_mss: clampMss,
  3849. comment,
  3850. disabled
  3851. })
  3852. });
  3853. if (res.ok) {
  3854. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3855. closeEoIPModal();
  3856. loadEoIP(false);
  3857. fetchData(false);
  3858. } else {
  3859. const err = await res.json();
  3860. showToast('Error', err.message, 'error');
  3861. }
  3862. } catch (err) {
  3863. showToast('Error', err.message, 'error');
  3864. }
  3865. }
  3866. async function toggleEoIPState(id, disabled) {
  3867. try {
  3868. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3869. method: 'POST',
  3870. headers: { 'Content-Type': 'application/json' },
  3871. body: JSON.stringify({ disabled })
  3872. });
  3873. if (res.ok) {
  3874. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3875. loadEoIP(false);
  3876. fetchData(false);
  3877. }
  3878. } catch (err) {
  3879. showToast('Error', err.message, 'error');
  3880. }
  3881. }
  3882. async function deleteEoIP(id) {
  3883. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3884. try {
  3885. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3886. if (res.ok) {
  3887. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3888. loadEoIP(false);
  3889. fetchData(false);
  3890. }
  3891. } catch (err) {
  3892. showToast('Error', err.message, 'error');
  3893. }
  3894. }
  3895. // ======================== PPP Central Hub & Servers ========================
  3896. function switchPPPSubTab(tab) {
  3897. state.pppSubTab = tab;
  3898. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3899. tabs.forEach(t => {
  3900. const panel = document.getElementById(`ppp-subtab-${t}`);
  3901. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3902. if (panel) {
  3903. if (t === tab) panel.classList.remove('hidden');
  3904. else panel.classList.add('hidden');
  3905. }
  3906. if (btn) {
  3907. if (t === tab) {
  3908. 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';
  3909. } else {
  3910. 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';
  3911. }
  3912. }
  3913. });
  3914. const addBtn = document.getElementById('ppp-primary-add-btn');
  3915. if (addBtn) {
  3916. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3917. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3918. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3919. else addBtn.innerHTML = '<span>Save Config</span>';
  3920. }
  3921. if (tab === 'active') loadPPPSessions();
  3922. }
  3923. function openCurrentPPPModal() {
  3924. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  3925. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  3926. else if (state.pppSubTab === 'active') loadPPPSessions();
  3927. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  3928. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  3929. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  3930. }
  3931. async function loadPPP(populateDropdowns = true) {
  3932. await Promise.all([
  3933. loadPPPSecrets(),
  3934. loadPPPProfiles(),
  3935. loadPPPServers(),
  3936. loadPPPSessions()
  3937. ]);
  3938. }
  3939. async function loadPPPSecrets() {
  3940. try {
  3941. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  3942. const data = await res.json();
  3943. state.pppSecrets = Array.isArray(data) ? data : [];
  3944. const b = document.getElementById('ppp-badge-secrets');
  3945. if (b) b.innerText = state.pppSecrets.length;
  3946. const b2 = document.getElementById('secrets-count-badge');
  3947. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  3948. renderPPPSecrets();
  3949. } catch (err) {
  3950. console.error('Failed to load PPP secrets:', err);
  3951. }
  3952. }
  3953. function renderPPPSecrets() {
  3954. const tbody = document.getElementById('secrets-table-body');
  3955. const empty = document.getElementById('secrets-empty');
  3956. if (!tbody) return;
  3957. tbody.innerHTML = '';
  3958. const secrets = state.pppSecrets || [];
  3959. if (secrets.length === 0) {
  3960. empty?.classList.remove('hidden');
  3961. return;
  3962. }
  3963. empty?.classList.add('hidden');
  3964. secrets.forEach(s => {
  3965. const tr = document.createElement('tr');
  3966. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  3967. tr.innerHTML = `
  3968. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  3969. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  3970. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  3971. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  3972. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  3973. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  3974. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  3975. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3976. <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>
  3977. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3978. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3979. </td>
  3980. `;
  3981. tbody.appendChild(tr);
  3982. });
  3983. }
  3984. async function loadPPPProfiles() {
  3985. try {
  3986. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  3987. const data = await res.json();
  3988. state.pppProfiles = Array.isArray(data) ? data : [];
  3989. const b = document.getElementById('ppp-badge-profiles');
  3990. if (b) b.innerText = state.pppProfiles.length;
  3991. const b2 = document.getElementById('profiles-count-badge');
  3992. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  3993. // Populate profile selects across modals
  3994. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  3995. selects.forEach(sid => {
  3996. const el = document.getElementById(sid);
  3997. if (!el) return;
  3998. const cur = el.value;
  3999. el.innerHTML = '';
  4000. state.pppProfiles.forEach(p => {
  4001. const opt = document.createElement('option');
  4002. opt.value = p.name;
  4003. opt.innerText = `${p.name} (${p.remote_address})`;
  4004. if (p.name === cur) opt.selected = true;
  4005. el.appendChild(opt);
  4006. });
  4007. });
  4008. renderPPPProfiles();
  4009. } catch (err) {
  4010. console.error('Failed to load PPP profiles:', err);
  4011. }
  4012. }
  4013. function renderPPPProfiles() {
  4014. const tbody = document.getElementById('profiles-table-body');
  4015. if (!tbody) return;
  4016. tbody.innerHTML = '';
  4017. (state.pppProfiles || []).forEach(p => {
  4018. const isDefault = p.name.startsWith('default');
  4019. const tr = document.createElement('tr');
  4020. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4021. tr.innerHTML = `
  4022. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4023. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4024. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4025. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4026. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4027. <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>
  4028. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4029. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4030. ${!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>`}
  4031. </td>
  4032. `;
  4033. tbody.appendChild(tr);
  4034. });
  4035. }
  4036. async function loadPPPServers() {
  4037. try {
  4038. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4039. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4040. fetch(`${API_BASE}/vpn/servers/pptp`),
  4041. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4042. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4043. ]);
  4044. if (pppoeRes.ok) {
  4045. state.pppoeServer = await pppoeRes.json();
  4046. const s = state.pppoeServer;
  4047. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4048. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4049. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4050. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4051. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4052. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4053. const pill = document.getElementById('pppoe-server-status-pill');
  4054. if (pill) {
  4055. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4056. 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';
  4057. }
  4058. setDotBadge('ppp-badge-pppoe-state', s.running);
  4059. }
  4060. if (pptpRes.ok) {
  4061. state.pptpServer = await pptpRes.json();
  4062. const s = state.pptpServer;
  4063. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4064. document.getElementById('pptp-server-port').value = s.port || 1723;
  4065. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4066. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4067. const pill = document.getElementById('pptp-server-status-pill');
  4068. if (pill) {
  4069. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4070. 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';
  4071. }
  4072. setDotBadge('ppp-badge-pptp-state', s.running);
  4073. }
  4074. if (l2tpRes.ok) {
  4075. state.l2tpServer = await l2tpRes.json();
  4076. const s = state.l2tpServer;
  4077. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4078. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4079. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4080. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4081. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4082. const pill = document.getElementById('l2tp-server-status-pill');
  4083. if (pill) {
  4084. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4085. 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';
  4086. }
  4087. setDotBadge('ppp-badge-l2tp-state', s.running);
  4088. }
  4089. if (ipsecRes.ok) {
  4090. state.ipsecServer = await ipsecRes.json();
  4091. const s = state.ipsecServer;
  4092. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4093. if (modalEn) modalEn.checked = !!s.enabled;
  4094. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4095. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4096. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4097. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4098. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4099. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4100. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4101. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4102. const pill = document.getElementById('modal-ipsec-server-status');
  4103. if (pill) {
  4104. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4105. 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';
  4106. }
  4107. }
  4108. } catch (err) {
  4109. console.error('Failed to load VPN servers:', err);
  4110. }
  4111. }
  4112. async function loadPPPSessions() {
  4113. try {
  4114. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4115. const data = await res.json();
  4116. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4117. const b = document.getElementById('ppp-badge-active');
  4118. if (b) b.innerText = state.pppActiveSessions.length;
  4119. const sideB = document.getElementById('badge-ppp-sessions');
  4120. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4121. renderPPPSessions();
  4122. } catch (err) {
  4123. console.error('Failed to load active PPP sessions:', err);
  4124. }
  4125. }
  4126. function renderPPPSessions() {
  4127. const tbody = document.getElementById('active-ppp-table-body');
  4128. const empty = document.getElementById('active-ppp-empty');
  4129. if (!tbody) return;
  4130. tbody.innerHTML = '';
  4131. const list = state.pppActiveSessions || [];
  4132. if (list.length === 0) {
  4133. empty?.classList.remove('hidden');
  4134. return;
  4135. }
  4136. empty?.classList.add('hidden');
  4137. list.forEach(s => {
  4138. const tr = document.createElement('tr');
  4139. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4140. tr.innerHTML = `
  4141. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4142. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4143. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4144. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4145. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4146. <td class="py-2.5 px-3 text-[11px]">
  4147. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4148. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4149. </td>
  4150. <td class="py-2.5 px-3 text-right font-sans">
  4151. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4152. </td>
  4153. `;
  4154. tbody.appendChild(tr);
  4155. });
  4156. }
  4157. async function disconnectPPPSession(iface) {
  4158. if (!confirm(`Disconnect session ${iface}?`)) return;
  4159. try {
  4160. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4161. if (res.ok) {
  4162. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4163. loadPPPSessions();
  4164. }
  4165. } catch (err) {
  4166. showToast('Error', err.message, 'error');
  4167. }
  4168. }
  4169. // PPP Secret Modal handlers
  4170. function openAddPPPSecretModal() {
  4171. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4172. document.getElementById('secret-modal-id').value = '';
  4173. document.getElementById('secret-modal-name').value = '';
  4174. document.getElementById('secret-modal-password').value = '';
  4175. document.getElementById('secret-modal-service').value = 'any';
  4176. document.getElementById('secret-modal-profile').value = 'default';
  4177. document.getElementById('secret-modal-local').value = '';
  4178. document.getElementById('secret-modal-remote').value = '';
  4179. document.getElementById('secret-modal-comment').value = '';
  4180. document.getElementById('secret-modal-disabled').checked = false;
  4181. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4182. }
  4183. function openEditPPPSecretModal(id) {
  4184. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4185. if (!s) return;
  4186. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4187. document.getElementById('secret-modal-id').value = s.id;
  4188. document.getElementById('secret-modal-name').value = s.name;
  4189. document.getElementById('secret-modal-password').value = s.password;
  4190. document.getElementById('secret-modal-service').value = s.service || 'any';
  4191. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4192. document.getElementById('secret-modal-local').value = s.local_address || '';
  4193. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4194. document.getElementById('secret-modal-comment').value = s.comment || '';
  4195. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4196. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4197. }
  4198. function closePPPSecretModal() {
  4199. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4200. }
  4201. async function submitSavePPPSecret(e) {
  4202. e.preventDefault();
  4203. const id = document.getElementById('secret-modal-id').value;
  4204. const name = document.getElementById('secret-modal-name').value.trim();
  4205. const password = document.getElementById('secret-modal-password').value.trim();
  4206. const service = document.getElementById('secret-modal-service').value;
  4207. const profile = document.getElementById('secret-modal-profile').value;
  4208. const local = document.getElementById('secret-modal-local').value.trim();
  4209. const remote = document.getElementById('secret-modal-remote').value.trim();
  4210. const comment = document.getElementById('secret-modal-comment').value.trim();
  4211. const disabled = document.getElementById('secret-modal-disabled').checked;
  4212. try {
  4213. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4214. method: 'POST',
  4215. headers: { 'Content-Type': 'application/json' },
  4216. body: JSON.stringify({
  4217. id,
  4218. name,
  4219. password,
  4220. service,
  4221. profile,
  4222. local_address: local,
  4223. remote_address: remote,
  4224. comment,
  4225. disabled
  4226. })
  4227. });
  4228. if (res.ok) {
  4229. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4230. closePPPSecretModal();
  4231. loadPPPSecrets();
  4232. } else {
  4233. const err = await res.json();
  4234. showToast('Error', err.message, 'error');
  4235. }
  4236. } catch (err) {
  4237. showToast('Error', err.message, 'error');
  4238. }
  4239. }
  4240. async function togglePPPSecretState(id, disabled) {
  4241. try {
  4242. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4243. method: 'POST',
  4244. headers: { 'Content-Type': 'application/json' },
  4245. body: JSON.stringify({ disabled })
  4246. });
  4247. if (res.ok) {
  4248. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4249. loadPPPSecrets();
  4250. }
  4251. } catch (err) {
  4252. showToast('Error', err.message, 'error');
  4253. }
  4254. }
  4255. async function deletePPPSecret(id) {
  4256. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4257. try {
  4258. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4259. if (res.ok) {
  4260. showToast('Deleted', 'Secret account removed', 'success');
  4261. loadPPPSecrets();
  4262. }
  4263. } catch (err) {
  4264. showToast('Error', err.message, 'error');
  4265. }
  4266. }
  4267. // PPP Profile Modal handlers
  4268. function openAddPPPProfileModal() {
  4269. document.getElementById('profile-modal-name').value = '';
  4270. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4271. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4272. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4273. document.getElementById('profile-modal-encryption').value = 'required';
  4274. document.getElementById('profile-modal-onlyone').checked = true;
  4275. document.getElementById('profile-modal-comment').value = '';
  4276. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4277. }
  4278. function closePPPProfileModal() {
  4279. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4280. }
  4281. async function submitSavePPPProfile(e) {
  4282. e.preventDefault();
  4283. const name = document.getElementById('profile-modal-name').value.trim();
  4284. const local = document.getElementById('profile-modal-local').value.trim();
  4285. const remote = document.getElementById('profile-modal-remote').value.trim();
  4286. const dns = document.getElementById('profile-modal-dns').value.trim();
  4287. const enc = document.getElementById('profile-modal-encryption').value;
  4288. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4289. const comment = document.getElementById('profile-modal-comment').value.trim();
  4290. try {
  4291. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4292. method: 'POST',
  4293. headers: { 'Content-Type': 'application/json' },
  4294. body: JSON.stringify({
  4295. id: name,
  4296. name,
  4297. local_address: local,
  4298. remote_address: remote,
  4299. dns_servers: dns,
  4300. use_encryption: enc,
  4301. only_one: onlyone,
  4302. comment
  4303. })
  4304. });
  4305. if (res.ok) {
  4306. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4307. closePPPProfileModal();
  4308. loadPPPProfiles();
  4309. } else {
  4310. const err = await res.json();
  4311. showToast('Error', err.message, 'error');
  4312. }
  4313. } catch (err) {
  4314. showToast('Error', err.message, 'error');
  4315. }
  4316. }
  4317. async function deletePPPProfile(name) {
  4318. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4319. try {
  4320. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4321. if (res.ok) {
  4322. showToast('Deleted', 'Profile removed', 'success');
  4323. loadPPPProfiles();
  4324. } else {
  4325. const err = await res.json();
  4326. showToast('Error', err.message, 'error');
  4327. }
  4328. } catch (err) {
  4329. showToast('Error', err.message, 'error');
  4330. }
  4331. }
  4332. // Server Config submissions
  4333. async function savePPPoEServerConfig(e) {
  4334. e.preventDefault();
  4335. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4336. const name = document.getElementById('pppoe-server-name').value.trim();
  4337. const iface = document.getElementById('pppoe-server-iface').value;
  4338. const profile = document.getElementById('pppoe-server-profile').value;
  4339. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4340. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4341. try {
  4342. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4343. method: 'POST',
  4344. headers: { 'Content-Type': 'application/json' },
  4345. body: JSON.stringify({
  4346. enabled,
  4347. service_name: name,
  4348. interface: iface,
  4349. default_profile: profile,
  4350. max_mtu: mtu,
  4351. max_mru: mtu,
  4352. one_session_per_host: onesession
  4353. })
  4354. });
  4355. if (res.ok) {
  4356. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4357. loadPPPServers();
  4358. fetchData(false);
  4359. } else {
  4360. const err = await res.json();
  4361. showToast('Error', err.message, 'error');
  4362. }
  4363. } catch (err) {
  4364. showToast('Error', err.message, 'error');
  4365. }
  4366. }
  4367. async function savePPTPServerConfig(e) {
  4368. e.preventDefault();
  4369. const enabled = document.getElementById('pptp-server-enabled').checked;
  4370. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4371. const profile = document.getElementById('pptp-server-profile').value;
  4372. const mppe = document.getElementById('pptp-server-mppe').checked;
  4373. try {
  4374. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4375. method: 'POST',
  4376. headers: { 'Content-Type': 'application/json' },
  4377. body: JSON.stringify({
  4378. enabled,
  4379. port,
  4380. default_profile: profile,
  4381. require_mppe: mppe
  4382. })
  4383. });
  4384. if (res.ok) {
  4385. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4386. loadPPPServers();
  4387. fetchData(false);
  4388. } else {
  4389. const err = await res.json();
  4390. showToast('Error', err.message, 'error');
  4391. }
  4392. } catch (err) {
  4393. showToast('Error', err.message, 'error');
  4394. }
  4395. }
  4396. async function saveL2TPServerConfig(e) {
  4397. e.preventDefault();
  4398. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4399. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4400. const profile = document.getElementById('l2tp-server-profile').value;
  4401. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4402. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4403. try {
  4404. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4405. method: 'POST',
  4406. headers: { 'Content-Type': 'application/json' },
  4407. body: JSON.stringify({
  4408. enabled,
  4409. port,
  4410. default_profile: profile,
  4411. use_ipsec: useipsec,
  4412. ipsec_secret: psk
  4413. })
  4414. });
  4415. if (res.ok) {
  4416. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4417. loadPPPServers();
  4418. fetchData(false);
  4419. } else {
  4420. const err = await res.json();
  4421. showToast('Error', err.message, 'error');
  4422. }
  4423. } catch (err) {
  4424. showToast('Error', err.message, 'error');
  4425. }
  4426. }
  4427. // IPSec Server Modal
  4428. function openIPSecServerModal() {
  4429. loadPPPServers();
  4430. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4431. }
  4432. function closeIPSecServerModal() {
  4433. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4434. }
  4435. async function submitSaveIPSecServer(e) {
  4436. e.preventDefault();
  4437. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4438. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4439. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4440. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4441. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4442. try {
  4443. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4444. method: 'POST',
  4445. headers: { 'Content-Type': 'application/json' },
  4446. body: JSON.stringify({
  4447. enabled,
  4448. preshared_key: psk,
  4449. pool_address: pool,
  4450. dns_servers: dns,
  4451. local_subnet: subnet
  4452. })
  4453. });
  4454. if (res.ok) {
  4455. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4456. closeIPSecServerModal();
  4457. loadPPPServers();
  4458. fetchData(false);
  4459. } else {
  4460. const err = await res.json();
  4461. showToast('Error', err.message, 'error');
  4462. }
  4463. } catch (err) {
  4464. showToast('Error', err.message, 'error');
  4465. }
  4466. }
  4467. // WireGuard Client Config Viewer
  4468. let currentWGClientConf = '';
  4469. async function openWGClientConfModal(iface, clientIP) {
  4470. try {
  4471. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4472. method: 'POST',
  4473. headers: { 'Content-Type': 'application/json' },
  4474. body: JSON.stringify({
  4475. interface: iface,
  4476. address: clientIP || '10.10.0.2/32',
  4477. dns: '1.1.1.1, 8.8.8.8'
  4478. })
  4479. });
  4480. if (res.ok) {
  4481. const data = await res.json();
  4482. currentWGClientConf = data.config;
  4483. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4484. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4485. } else {
  4486. const err = await res.json();
  4487. showToast('Error', err.message, 'error');
  4488. }
  4489. } catch (err) {
  4490. showToast('Error', err.message, 'error');
  4491. }
  4492. }
  4493. function closeWGClientConfModal() {
  4494. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4495. }
  4496. function copyWGClientConf() {
  4497. if (!currentWGClientConf) return;
  4498. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4499. }
  4500. function downloadWGClientConf() {
  4501. if (!currentWGClientConf) return;
  4502. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4503. const a = document.createElement('a');
  4504. a.href = URL.createObjectURL(blob);
  4505. a.download = 'wireguard-client.conf';
  4506. document.body.appendChild(a);
  4507. a.click();
  4508. document.body.removeChild(a);
  4509. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4510. }
  4511. // =========================================================================
  4512. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4513. // =========================================================================
  4514. state.activeDynSubTab = 'bgp-peers';
  4515. state.bgpInstance = null;
  4516. state.bgpPeers = [];
  4517. state.bgpNets = [];
  4518. state.bgpRoutes = [];
  4519. state.ospfInstance = null;
  4520. state.ospfInterfaces = [];
  4521. state.ospfAreas = [];
  4522. state.ospfNeighbors = [];
  4523. state.ospfRoutes = [];
  4524. function switchDynSubTab(subTab) {
  4525. state.activeDynSubTab = subTab;
  4526. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes', 'ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4527. tabs.forEach(t => {
  4528. const el = document.getElementById(`dyn-subtab-${t}`);
  4529. const btn = document.getElementById(`dyn-subtab-btn-${t}`);
  4530. if (el) el.classList.toggle('hidden', t !== subTab);
  4531. if (btn) {
  4532. if (t === subTab) {
  4533. btn.className = `px-4 py-2.5 text-xs font-bold border-b-2 ${t.startsWith('bgp') ? 'border-purple-500' : 'border-indigo-500'} text-white transition flex items-center gap-2 whitespace-nowrap`;
  4534. } else {
  4535. 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';
  4536. }
  4537. }
  4538. });
  4539. }
  4540. async function loadDynamicRouting(showToastMsg = true) {
  4541. try {
  4542. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4543. fetch(`${API_BASE}/routing/dynamic/summary`),
  4544. fetch(`${API_BASE}/routing/bgp/instance`),
  4545. fetch(`${API_BASE}/routing/bgp/peers`),
  4546. fetch(`${API_BASE}/routing/bgp/networks`),
  4547. fetch(`${API_BASE}/routing/bgp/routes`),
  4548. fetch(`${API_BASE}/routing/ospf/instance`),
  4549. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4550. fetch(`${API_BASE}/routing/ospf/areas`),
  4551. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4552. fetch(`${API_BASE}/routing/ospf/routes`)
  4553. ]);
  4554. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4555. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4556. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4557. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4558. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4559. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4560. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4561. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4562. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4563. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4564. renderBgpStatusPill();
  4565. renderBgpPeers();
  4566. renderBgpNetworks();
  4567. renderBgpRoutes();
  4568. renderOspfStatusPill();
  4569. renderOspfInterfaces();
  4570. renderOspfAreas();
  4571. renderOspfNeighbors();
  4572. renderOspfRoutes();
  4573. updateBadges();
  4574. } catch (err) {
  4575. console.error('Failed to load dynamic routing:', err);
  4576. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4577. }
  4578. }
  4579. function renderBgpStatusPill() {
  4580. const pill = document.getElementById('bgp-live-status-pill');
  4581. if (!pill) return;
  4582. const inst = state.bgpInstance;
  4583. if (!inst || !inst.enabled) {
  4584. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4585. pill.innerText = 'BGP DISABLED';
  4586. } else if (inst.running) {
  4587. 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';
  4588. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4589. } else {
  4590. 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';
  4591. pill.innerText = 'BGP STARTING...';
  4592. }
  4593. }
  4594. function renderBgpPeers() {
  4595. const tbody = document.getElementById('bgp-peers-table-body');
  4596. const empty = document.getElementById('bgp-peers-empty');
  4597. const countBadge = document.getElementById('bgp-peers-count-badge');
  4598. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4599. const peers = state.bgpPeers || [];
  4600. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4601. if (navBadge) navBadge.innerText = peers.length;
  4602. if (peers.length === 0) {
  4603. tbody.innerHTML = '';
  4604. empty.classList.remove('hidden');
  4605. return;
  4606. }
  4607. empty.classList.add('hidden');
  4608. tbody.innerHTML = peers.map(p => {
  4609. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4610. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4611. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4612. let stateBadge = '';
  4613. if (p.disabled) {
  4614. 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>';
  4615. } else if (p.state === 'Established') {
  4616. 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>';
  4617. } else if (p.state === 'Connect' || p.state === 'Active') {
  4618. 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>`;
  4619. } else {
  4620. 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>`;
  4621. }
  4622. return `
  4623. <tr class="hover:bg-slate-800/40 transition">
  4624. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4625. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4626. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4627. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4628. <td class="py-2.5 px-3">${stateBadge}</td>
  4629. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4630. <td class="py-2.5 px-3 text-slate-300">
  4631. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4632. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4633. </td>
  4634. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4635. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4636. <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'}">
  4637. ${p.disabled ? 'Enable' : 'Disable'}
  4638. </button>
  4639. <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">
  4640. Edit
  4641. </button>
  4642. <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">
  4643. Delete
  4644. </button>
  4645. </td>
  4646. </tr>
  4647. `;
  4648. }).join('');
  4649. }
  4650. function renderBgpNetworks() {
  4651. const tbody = document.getElementById('bgp-nets-table-body');
  4652. const empty = document.getElementById('bgp-nets-empty');
  4653. const countBadge = document.getElementById('bgp-nets-count-badge');
  4654. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4655. const nets = state.bgpNets || [];
  4656. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4657. if (navBadge) navBadge.innerText = nets.length;
  4658. if (nets.length === 0) {
  4659. tbody.innerHTML = '';
  4660. empty.classList.remove('hidden');
  4661. return;
  4662. }
  4663. empty.classList.add('hidden');
  4664. tbody.innerHTML = nets.map(n => `
  4665. <tr class="hover:bg-slate-800/40 transition">
  4666. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4667. <td class="py-2.5 px-3">
  4668. ${n.disabled
  4669. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4670. : '<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>'}
  4671. </td>
  4672. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4673. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4674. <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">
  4675. Delete
  4676. </button>
  4677. </td>
  4678. </tr>
  4679. `).join('');
  4680. }
  4681. function renderBgpRoutes() {
  4682. const tbody = document.getElementById('bgp-routes-table-body');
  4683. const empty = document.getElementById('bgp-routes-empty');
  4684. const countBadge = document.getElementById('bgp-routes-count-badge');
  4685. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4686. const routes = state.bgpRoutes || [];
  4687. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4688. if (navBadge) navBadge.innerText = routes.length;
  4689. if (routes.length === 0) {
  4690. tbody.innerHTML = '';
  4691. empty.classList.remove('hidden');
  4692. return;
  4693. }
  4694. empty.classList.add('hidden');
  4695. tbody.innerHTML = routes.map(r => `
  4696. <tr class="hover:bg-slate-800/40 transition">
  4697. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4698. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4699. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4700. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4701. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4702. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4703. </tr>
  4704. `).join('');
  4705. }
  4706. function renderOspfStatusPill() {
  4707. const pill = document.getElementById('ospf-live-status-pill');
  4708. if (!pill) return;
  4709. const inst = state.ospfInstance;
  4710. if (!inst || !inst.enabled) {
  4711. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4712. pill.innerText = 'OSPF DISABLED';
  4713. } else if (inst.running) {
  4714. 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';
  4715. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4716. } else {
  4717. 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';
  4718. pill.innerText = 'OSPF STARTING...';
  4719. }
  4720. }
  4721. function renderOspfInterfaces() {
  4722. const tbody = document.getElementById('ospf-ifaces-table-body');
  4723. const empty = document.getElementById('ospf-ifaces-empty');
  4724. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4725. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4726. const ifaces = state.ospfInterfaces || [];
  4727. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4728. if (navBadge) navBadge.innerText = ifaces.length;
  4729. if (ifaces.length === 0) {
  4730. tbody.innerHTML = '';
  4731. empty.classList.remove('hidden');
  4732. return;
  4733. }
  4734. empty.classList.add('hidden');
  4735. tbody.innerHTML = ifaces.map(i => {
  4736. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4737. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4738. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4739. return `
  4740. <tr class="hover:bg-slate-800/40 transition">
  4741. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4742. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4743. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4744. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4745. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4746. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4747. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4748. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4749. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4750. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4751. <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'}">
  4752. ${i.disabled ? 'Enable' : 'Disable'}
  4753. </button>
  4754. <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">
  4755. Edit
  4756. </button>
  4757. <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">
  4758. Delete
  4759. </button>
  4760. </td>
  4761. </tr>
  4762. `;
  4763. }).join('');
  4764. }
  4765. function renderOspfAreas() {
  4766. const tbody = document.getElementById('ospf-areas-table-body');
  4767. const countBadge = document.getElementById('ospf-areas-count-badge');
  4768. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4769. const areas = state.ospfAreas || [];
  4770. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4771. if (navBadge) navBadge.innerText = areas.length;
  4772. tbody.innerHTML = areas.map(a => `
  4773. <tr class="hover:bg-slate-800/40 transition">
  4774. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4775. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4776. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4777. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4778. <td class="py-2.5 px-3 text-right font-sans">
  4779. <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">
  4780. Delete
  4781. </button>
  4782. </td>
  4783. </tr>
  4784. `).join('');
  4785. }
  4786. function renderOspfNeighbors() {
  4787. const tbody = document.getElementById('ospf-nbrs-table-body');
  4788. const empty = document.getElementById('ospf-nbrs-empty');
  4789. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4790. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4791. const nbrs = state.ospfNeighbors || [];
  4792. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4793. if (navBadge) navBadge.innerText = nbrs.length;
  4794. if (nbrs.length === 0) {
  4795. tbody.innerHTML = '';
  4796. empty.classList.remove('hidden');
  4797. return;
  4798. }
  4799. empty.classList.add('hidden');
  4800. tbody.innerHTML = nbrs.map(n => {
  4801. let stateBadge = '';
  4802. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4803. 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>`;
  4804. } else {
  4805. 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>`;
  4806. }
  4807. return `
  4808. <tr class="hover:bg-slate-800/40 transition">
  4809. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4810. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4811. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4812. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4813. <td class="py-2.5 px-3">${stateBadge}</td>
  4814. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4815. </tr>
  4816. `;
  4817. }).join('');
  4818. }
  4819. function renderOspfRoutes() {
  4820. const tbody = document.getElementById('ospf-routes-table-body');
  4821. const empty = document.getElementById('ospf-routes-empty');
  4822. const countBadge = document.getElementById('ospf-routes-count-badge');
  4823. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4824. const routes = state.ospfRoutes || [];
  4825. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4826. if (navBadge) navBadge.innerText = routes.length;
  4827. if (routes.length === 0) {
  4828. tbody.innerHTML = '';
  4829. empty.classList.remove('hidden');
  4830. return;
  4831. }
  4832. empty.classList.add('hidden');
  4833. tbody.innerHTML = routes.map(r => `
  4834. <tr class="hover:bg-slate-800/40 transition">
  4835. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4836. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4837. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4838. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4839. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4840. </tr>
  4841. `).join('');
  4842. }
  4843. // BGP Modals & Actions
  4844. function openBgpInstanceModal() {
  4845. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4846. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4847. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4848. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4849. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4850. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4851. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4852. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4853. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4854. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4855. }
  4856. function closeBgpInstanceModal() {
  4857. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4858. }
  4859. async function submitBgpInstance(e) {
  4860. e.preventDefault();
  4861. const payload = {
  4862. enabled: document.getElementById('modal-bgp-enabled').checked,
  4863. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4864. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4865. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4866. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4867. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4868. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4869. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4870. };
  4871. try {
  4872. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4873. method: 'POST',
  4874. headers: { 'Content-Type': 'application/json' },
  4875. body: JSON.stringify(payload)
  4876. });
  4877. if (res.ok) {
  4878. closeBgpInstanceModal();
  4879. showToast('Success', 'BGP instance configuration updated', 'success');
  4880. loadDynamicRouting();
  4881. } else {
  4882. const err = await res.json();
  4883. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4884. }
  4885. } catch (err) {
  4886. showToast('Error', err.message, 'error');
  4887. }
  4888. }
  4889. function openAddBgpPeerModal() {
  4890. document.getElementById('bgp-peer-form').reset();
  4891. document.getElementById('modal-bgp-peer-id').value = '';
  4892. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  4893. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  4894. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4895. }
  4896. function openEditBgpPeerModal(id) {
  4897. const p = (state.bgpPeers || []).find(item => item.id === id);
  4898. if (!p) return;
  4899. document.getElementById('modal-bgp-peer-id').value = p.id;
  4900. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  4901. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  4902. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  4903. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  4904. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  4905. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  4906. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  4907. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  4908. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  4909. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  4910. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  4911. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  4912. }
  4913. function closeBgpPeerModal() {
  4914. document.getElementById('bgp-peer-modal').classList.add('hidden');
  4915. }
  4916. async function submitBgpPeer(e) {
  4917. e.preventDefault();
  4918. const payload = {
  4919. id: document.getElementById('modal-bgp-peer-id').value,
  4920. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  4921. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  4922. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  4923. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  4924. password: document.getElementById('modal-bgp-peer-password').value,
  4925. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  4926. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  4927. passive: document.getElementById('modal-bgp-peer-passive').checked,
  4928. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  4929. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  4930. };
  4931. try {
  4932. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  4933. method: 'POST',
  4934. headers: { 'Content-Type': 'application/json' },
  4935. body: JSON.stringify(payload)
  4936. });
  4937. if (res.ok) {
  4938. closeBgpPeerModal();
  4939. showToast('Success', 'BGP Peer saved', 'success');
  4940. loadDynamicRouting();
  4941. } else {
  4942. const err = await res.json();
  4943. showToast('Error', err.error || 'Failed to save peer', 'error');
  4944. }
  4945. } catch (err) {
  4946. showToast('Error', err.message, 'error');
  4947. }
  4948. }
  4949. async function deleteBgpPeer(id) {
  4950. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  4951. try {
  4952. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4953. if (res.ok) {
  4954. showToast('Deleted', 'BGP peer removed', 'success');
  4955. loadDynamicRouting();
  4956. }
  4957. } catch (err) {
  4958. showToast('Error', err.message, 'error');
  4959. }
  4960. }
  4961. async function toggleBgpPeerState(id, disabled) {
  4962. try {
  4963. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  4964. method: 'POST',
  4965. headers: { 'Content-Type': 'application/json' },
  4966. body: JSON.stringify({ disabled })
  4967. });
  4968. if (res.ok) {
  4969. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  4970. loadDynamicRouting();
  4971. }
  4972. } catch (err) {
  4973. showToast('Error', err.message, 'error');
  4974. }
  4975. }
  4976. function openAddBgpNetworkModal() {
  4977. document.getElementById('bgp-network-form').reset();
  4978. document.getElementById('modal-bgp-net-id').value = '';
  4979. document.getElementById('bgp-network-modal').classList.remove('hidden');
  4980. }
  4981. function closeBgpNetworkModal() {
  4982. document.getElementById('bgp-network-modal').classList.add('hidden');
  4983. }
  4984. async function submitBgpNetwork(e) {
  4985. e.preventDefault();
  4986. const payload = {
  4987. id: document.getElementById('modal-bgp-net-id').value,
  4988. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  4989. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  4990. disabled: document.getElementById('modal-bgp-net-disabled').checked
  4991. };
  4992. try {
  4993. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  4994. method: 'POST',
  4995. headers: { 'Content-Type': 'application/json' },
  4996. body: JSON.stringify(payload)
  4997. });
  4998. if (res.ok) {
  4999. closeBgpNetworkModal();
  5000. showToast('Success', 'BGP network advertisement saved', 'success');
  5001. loadDynamicRouting();
  5002. } else {
  5003. const err = await res.json();
  5004. showToast('Error', err.error || 'Failed to save network', 'error');
  5005. }
  5006. } catch (err) {
  5007. showToast('Error', err.message, 'error');
  5008. }
  5009. }
  5010. async function deleteBgpNetwork(id) {
  5011. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5012. try {
  5013. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5014. if (res.ok) {
  5015. showToast('Deleted', 'Network advertisement removed', 'success');
  5016. loadDynamicRouting();
  5017. }
  5018. } catch (err) {
  5019. showToast('Error', err.message, 'error');
  5020. }
  5021. }
  5022. // OSPF Modals & Actions
  5023. function openOspfInstanceModal() {
  5024. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5025. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5026. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5027. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5028. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5029. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5030. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5031. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5032. }
  5033. function closeOspfInstanceModal() {
  5034. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5035. }
  5036. async function submitOspfInstance(e) {
  5037. e.preventDefault();
  5038. const payload = {
  5039. enabled: document.getElementById('modal-ospf-enabled').checked,
  5040. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5041. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5042. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5043. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5044. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5045. };
  5046. try {
  5047. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5048. method: 'POST',
  5049. headers: { 'Content-Type': 'application/json' },
  5050. body: JSON.stringify(payload)
  5051. });
  5052. if (res.ok) {
  5053. closeOspfInstanceModal();
  5054. showToast('Success', 'OSPF instance configuration updated', 'success');
  5055. loadDynamicRouting();
  5056. } else {
  5057. const err = await res.json();
  5058. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5059. }
  5060. } catch (err) {
  5061. showToast('Error', err.message, 'error');
  5062. }
  5063. }
  5064. function openAddOspfAreaModal() {
  5065. document.getElementById('ospf-area-form').reset();
  5066. document.getElementById('modal-ospf-area-id').value = '';
  5067. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5068. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5069. }
  5070. function closeOspfAreaModal() {
  5071. document.getElementById('ospf-area-modal').classList.add('hidden');
  5072. }
  5073. async function submitOspfArea(e) {
  5074. e.preventDefault();
  5075. const payload = {
  5076. id: document.getElementById('modal-ospf-area-id').value,
  5077. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5078. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5079. area_type: document.getElementById('modal-ospf-area-type').value,
  5080. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5081. };
  5082. try {
  5083. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5084. method: 'POST',
  5085. headers: { 'Content-Type': 'application/json' },
  5086. body: JSON.stringify(payload)
  5087. });
  5088. if (res.ok) {
  5089. closeOspfAreaModal();
  5090. showToast('Success', 'OSPF area saved', 'success');
  5091. loadDynamicRouting();
  5092. } else {
  5093. const err = await res.json();
  5094. showToast('Error', err.error || 'Failed to save area', 'error');
  5095. }
  5096. } catch (err) {
  5097. showToast('Error', err.message, 'error');
  5098. }
  5099. }
  5100. async function deleteOspfArea(id) {
  5101. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5102. try {
  5103. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5104. if (res.ok) {
  5105. showToast('Deleted', 'OSPF area removed', 'success');
  5106. loadDynamicRouting();
  5107. }
  5108. } catch (err) {
  5109. showToast('Error', err.message, 'error');
  5110. }
  5111. }
  5112. function populateOspfInterfaceDevices() {
  5113. const select = document.getElementById('modal-ospf-iface-device');
  5114. if (!select) return;
  5115. const current = select.value;
  5116. select.innerHTML = '<option value="">Any matching interface</option>';
  5117. (state.interfaces || []).forEach(iface => {
  5118. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5119. });
  5120. if (current) select.value = current;
  5121. }
  5122. function openAddOspfInterfaceModal() {
  5123. document.getElementById('ospf-interface-form').reset();
  5124. document.getElementById('modal-ospf-iface-id').value = '';
  5125. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5126. document.getElementById('modal-ospf-iface-cost').value = '10';
  5127. document.getElementById('modal-ospf-iface-priority').value = '1';
  5128. document.getElementById('modal-ospf-iface-hello').value = '10';
  5129. document.getElementById('modal-ospf-iface-dead').value = '40';
  5130. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5131. populateOspfInterfaceDevices();
  5132. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5133. }
  5134. function openEditOspfInterfaceModal(id) {
  5135. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5136. if (!item) return;
  5137. populateOspfInterfaceDevices();
  5138. document.getElementById('modal-ospf-iface-id').value = item.id;
  5139. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5140. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5141. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5142. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5143. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5144. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5145. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5146. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5147. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5148. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5149. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5150. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5151. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5152. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5153. }
  5154. function closeOspfInterfaceModal() {
  5155. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5156. }
  5157. async function submitOspfInterface(e) {
  5158. e.preventDefault();
  5159. const payload = {
  5160. id: document.getElementById('modal-ospf-iface-id').value,
  5161. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5162. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5163. interface: document.getElementById('modal-ospf-iface-device').value,
  5164. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5165. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5166. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5167. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5168. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5169. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5170. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5171. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5172. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5173. };
  5174. try {
  5175. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5176. method: 'POST',
  5177. headers: { 'Content-Type': 'application/json' },
  5178. body: JSON.stringify(payload)
  5179. });
  5180. if (res.ok) {
  5181. closeOspfInterfaceModal();
  5182. showToast('Success', 'OSPF interface template saved', 'success');
  5183. loadDynamicRouting();
  5184. } else {
  5185. const err = await res.json();
  5186. showToast('Error', err.error || 'Failed to save interface', 'error');
  5187. }
  5188. } catch (err) {
  5189. showToast('Error', err.message, 'error');
  5190. }
  5191. }
  5192. async function deleteOspfInterface(id) {
  5193. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5194. try {
  5195. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5196. if (res.ok) {
  5197. showToast('Deleted', 'OSPF interface removed', 'success');
  5198. loadDynamicRouting();
  5199. }
  5200. } catch (err) {
  5201. showToast('Error', err.message, 'error');
  5202. }
  5203. }
  5204. async function toggleOspfInterfaceState(id, disabled) {
  5205. try {
  5206. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5207. method: 'POST',
  5208. headers: { 'Content-Type': 'application/json' },
  5209. body: JSON.stringify({ disabled })
  5210. });
  5211. if (res.ok) {
  5212. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5213. loadDynamicRouting();
  5214. }
  5215. } catch (err) {
  5216. showToast('Error', err.message, 'error');
  5217. }
  5218. }
  5219. // ============================================================================
  5220. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5221. // ============================================================================
  5222. function switchBridgeSubTab(tab) {
  5223. state.bridgeSubTab = tab;
  5224. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5225. tabs.forEach(t => {
  5226. const panel = document.getElementById(`bridge-subtab-${t}`);
  5227. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5228. if (panel) {
  5229. if (t === tab) panel.classList.remove('hidden');
  5230. else panel.classList.add('hidden');
  5231. }
  5232. if (btn) {
  5233. if (t === tab) {
  5234. 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';
  5235. } else {
  5236. 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';
  5237. }
  5238. }
  5239. });
  5240. const addBtn = document.getElementById('bridge-top-action-btn');
  5241. if (addBtn) {
  5242. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5243. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5244. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5245. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5246. }
  5247. if (tab === 'hosts') loadBridgeHosts();
  5248. }
  5249. function openCurrentBridgeModal() {
  5250. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5251. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5252. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5253. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5254. }
  5255. async function loadBridge() {
  5256. try {
  5257. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5258. fetch(`${API_BASE}/bridge/bridges`),
  5259. fetch(`${API_BASE}/bridge/ports`),
  5260. fetch(`${API_BASE}/bridge/vlans`),
  5261. fetch(`${API_BASE}/bridge/summary`),
  5262. fetch(`${API_BASE}/vpn/eoip`),
  5263. fetch(`${API_BASE}/vlans`)
  5264. ]);
  5265. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5266. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5267. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5268. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5269. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5270. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5271. // Badges & Stats
  5272. const bBridges = document.getElementById('bridge-badge-bridges');
  5273. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5274. const bPorts = document.getElementById('bridge-badge-ports');
  5275. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5276. const bVlans = document.getElementById('bridge-badge-vlans');
  5277. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5278. const bHosts = document.getElementById('bridge-badge-hosts');
  5279. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5280. const sBr = document.getElementById('bridge-stat-bridges');
  5281. if (sBr) sBr.innerText = (state.bridges || []).length;
  5282. const sPorts = document.getElementById('bridge-stat-ports');
  5283. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5284. const sHosts = document.getElementById('bridge-stat-hosts');
  5285. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5286. renderBridges();
  5287. renderBridgePorts();
  5288. renderBridgeVLANs();
  5289. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5290. } catch (err) {
  5291. console.error('Failed to load bridge subsystem:', err);
  5292. }
  5293. }
  5294. // ----------------- Bridges -----------------
  5295. function renderBridges() {
  5296. const tbody = document.getElementById('bridge-table-body');
  5297. const empty = document.getElementById('bridge-empty-bridges');
  5298. const countBadge = document.getElementById('bridge-count-badge');
  5299. if (!tbody) return;
  5300. tbody.innerHTML = '';
  5301. const bridges = state.bridges || [];
  5302. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5303. if (bridges.length === 0) {
  5304. empty?.classList.remove('hidden');
  5305. return;
  5306. }
  5307. empty?.classList.add('hidden');
  5308. bridges.forEach((b, idx) => {
  5309. const tr = document.createElement('tr');
  5310. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5311. // Format IP addresses pill list
  5312. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5313. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5314. ipsHtml = b.ip_addresses.map(ip => `
  5315. <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">
  5316. <span>${ip}</span>
  5317. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5318. </span>
  5319. `).join(' ');
  5320. }
  5321. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5322. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5323. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5324. tr.innerHTML = `
  5325. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5326. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5327. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5328. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5329. </td>
  5330. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5331. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5332. <td class="py-2.5 px-3">
  5333. <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>
  5334. </td>
  5335. <td class="py-2.5 px-3 text-center">
  5336. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5337. </td>
  5338. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5339. <td class="py-2.5 px-3">
  5340. <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>
  5341. </td>
  5342. <td class="py-2.5 px-3">
  5343. <div class="flex items-center gap-1.5 flex-wrap">
  5344. ${ipsHtml}
  5345. <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>
  5346. </div>
  5347. </td>
  5348. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5349. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5350. </td>
  5351. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5352. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5353. <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>
  5354. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5355. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5356. </td>
  5357. `;
  5358. tbody.appendChild(tr);
  5359. });
  5360. }
  5361. function openAddBridgeModal() {
  5362. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5363. document.getElementById('bridge-modal-id').value = '';
  5364. document.getElementById('bridge-modal-name').value = 'bridge1';
  5365. document.getElementById('bridge-modal-name').disabled = false;
  5366. document.getElementById('bridge-modal-mtu').value = '1500';
  5367. document.getElementById('bridge-modal-mac').value = '';
  5368. document.getElementById('bridge-modal-stp').value = 'rstp';
  5369. document.getElementById('bridge-modal-priority').value = '32768';
  5370. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5371. document.getElementById('bridge-modal-pvid').value = '1';
  5372. document.getElementById('bridge-modal-fastforward').checked = true;
  5373. document.getElementById('bridge-modal-comment').value = '';
  5374. document.getElementById('bridge-modal-disabled').checked = false;
  5375. toggleBridgeModalVlanFiltering();
  5376. document.getElementById('bridge-modal').classList.remove('hidden');
  5377. }
  5378. function openEditBridgeModal(id) {
  5379. const b = (state.bridges || []).find(x => x.id === id);
  5380. if (!b) return;
  5381. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5382. document.getElementById('bridge-modal-id').value = b.id;
  5383. document.getElementById('bridge-modal-name').value = b.name;
  5384. document.getElementById('bridge-modal-name').disabled = true;
  5385. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5386. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5387. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5388. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5389. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5390. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5391. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5392. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5393. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5394. toggleBridgeModalVlanFiltering();
  5395. document.getElementById('bridge-modal').classList.remove('hidden');
  5396. }
  5397. function closeBridgeModal() {
  5398. document.getElementById('bridge-modal').classList.add('hidden');
  5399. }
  5400. function toggleBridgeModalVlanFiltering() {
  5401. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5402. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5403. if (pvidBox) {
  5404. if (chk) pvidBox.classList.remove('opacity-40');
  5405. else pvidBox.classList.add('opacity-40');
  5406. }
  5407. }
  5408. async function submitSaveBridge(e) {
  5409. e.preventDefault();
  5410. const id = document.getElementById('bridge-modal-id').value;
  5411. const name = document.getElementById('bridge-modal-name').value.trim();
  5412. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5413. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5414. const stp = document.getElementById('bridge-modal-stp').value;
  5415. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5416. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5417. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5418. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5419. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5420. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5421. try {
  5422. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5423. method: 'POST',
  5424. headers: { 'Content-Type': 'application/json' },
  5425. body: JSON.stringify({
  5426. id,
  5427. name,
  5428. mtu,
  5429. mac_address: mac,
  5430. stp,
  5431. priority,
  5432. vlan_filtering: vlanFiltering,
  5433. pvid,
  5434. fast_forward: fastForward,
  5435. comment,
  5436. disabled
  5437. })
  5438. });
  5439. if (res.ok) {
  5440. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5441. closeBridgeModal();
  5442. loadBridge();
  5443. fetchData(false);
  5444. } else {
  5445. const err = await res.json();
  5446. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5447. }
  5448. } catch (err) {
  5449. showToast('Error', err.message, 'error');
  5450. }
  5451. }
  5452. async function toggleBridgeState(id, disabled) {
  5453. try {
  5454. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5455. method: 'POST',
  5456. headers: { 'Content-Type': 'application/json' },
  5457. body: JSON.stringify({ disabled })
  5458. });
  5459. if (res.ok) {
  5460. loadBridge();
  5461. fetchData(false);
  5462. }
  5463. } catch (err) {
  5464. showToast('Error', err.message, 'error');
  5465. }
  5466. }
  5467. async function deleteBridge(id) {
  5468. const b = (state.bridges || []).find(x => x.id === id);
  5469. const name = b ? b.name : id;
  5470. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5471. try {
  5472. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5473. if (res.ok) {
  5474. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5475. loadBridge();
  5476. fetchData(false);
  5477. } else {
  5478. const err = await res.json();
  5479. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5480. }
  5481. } catch (err) {
  5482. showToast('Error', err.message, 'error');
  5483. }
  5484. }
  5485. // ----------------- Bridge IP Assignments -----------------
  5486. function openAddBridgeIPModal(id, name) {
  5487. document.getElementById('bridge-ip-modal-id').value = id;
  5488. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5489. document.getElementById('bridge-ip-modal-cidr').value = '';
  5490. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5491. }
  5492. function closeBridgeIPModal() {
  5493. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5494. }
  5495. async function submitAddBridgeIP(e) {
  5496. e.preventDefault();
  5497. const id = document.getElementById('bridge-ip-modal-id').value;
  5498. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5499. try {
  5500. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5501. method: 'POST',
  5502. headers: { 'Content-Type': 'application/json' },
  5503. body: JSON.stringify({ ip })
  5504. });
  5505. if (res.ok) {
  5506. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5507. closeBridgeIPModal();
  5508. loadBridge();
  5509. fetchData(false);
  5510. } else {
  5511. const err = await res.json();
  5512. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5513. }
  5514. } catch (err) {
  5515. showToast('Error', err.message, 'error');
  5516. }
  5517. }
  5518. async function deleteBridgeIP(id, ip) {
  5519. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5520. try {
  5521. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5522. method: 'DELETE',
  5523. headers: { 'Content-Type': 'application/json' },
  5524. body: JSON.stringify({ ip })
  5525. });
  5526. if (res.ok) {
  5527. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5528. loadBridge();
  5529. fetchData(false);
  5530. }
  5531. } catch (err) {
  5532. showToast('Error', err.message, 'error');
  5533. }
  5534. }
  5535. // ----------------- Bridge Ports -----------------
  5536. function renderBridgePorts() {
  5537. const tbody = document.getElementById('bridge-ports-table-body');
  5538. const empty = document.getElementById('bridge-empty-ports');
  5539. const countBadge = document.getElementById('bridge-ports-count-badge');
  5540. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5541. if (!tbody) return;
  5542. tbody.innerHTML = '';
  5543. // Update filter select
  5544. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5545. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5546. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5547. if (ports.length === 0) {
  5548. empty?.classList.remove('hidden');
  5549. return;
  5550. }
  5551. empty?.classList.add('hidden');
  5552. ports.forEach((p, idx) => {
  5553. const tr = document.createElement('tr');
  5554. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5555. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5556. tr.innerHTML = `
  5557. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5558. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5559. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5560. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5561. </td>
  5562. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5563. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5564. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5565. <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>
  5566. <td class="py-2.5 px-3">
  5567. ${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>'}
  5568. </td>
  5569. <td class="py-2.5 px-3">
  5570. <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>
  5571. </td>
  5572. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5573. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5574. <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>
  5575. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5576. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5577. </td>
  5578. `;
  5579. tbody.appendChild(tr);
  5580. });
  5581. }
  5582. function openAddBridgePortModal() {
  5583. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5584. document.getElementById('bridge-port-modal-id').value = '';
  5585. populateBridgeSelect('bridge-port-modal-bridge');
  5586. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5587. document.getElementById('bridge-port-modal-pvid').value = '1';
  5588. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5589. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5590. document.getElementById('bridge-port-modal-horizon').value = '0';
  5591. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5592. document.getElementById('bridge-port-modal-priority').value = '128';
  5593. document.getElementById('bridge-port-modal-learn').checked = true;
  5594. document.getElementById('bridge-port-modal-comment').value = '';
  5595. document.getElementById('bridge-port-modal-disabled').checked = false;
  5596. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5597. }
  5598. function openEditBridgePortModal(id) {
  5599. const p = (state.bridgePorts || []).find(x => x.id === id);
  5600. if (!p) return;
  5601. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5602. document.getElementById('bridge-port-modal-id').value = p.id;
  5603. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5604. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5605. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5606. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5607. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5608. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5609. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5610. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5611. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5612. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5613. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5614. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5615. }
  5616. function closeBridgePortModal() {
  5617. document.getElementById('bridge-port-modal').classList.add('hidden');
  5618. }
  5619. async function submitSaveBridgePort(e) {
  5620. e.preventDefault();
  5621. const id = document.getElementById('bridge-port-modal-id').value;
  5622. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5623. const iface = document.getElementById('bridge-port-modal-interface').value;
  5624. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5625. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5626. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5627. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5628. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5629. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5630. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5631. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5632. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5633. try {
  5634. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5635. method: 'POST',
  5636. headers: { 'Content-Type': 'application/json' },
  5637. body: JSON.stringify({
  5638. id,
  5639. bridge,
  5640. interface: iface,
  5641. pvid,
  5642. frame_types: frameTypes,
  5643. ingress_filtering: ingressFiltering,
  5644. horizon,
  5645. path_cost: pathCost,
  5646. priority,
  5647. learn,
  5648. comment,
  5649. disabled
  5650. })
  5651. });
  5652. if (res.ok) {
  5653. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5654. closeBridgePortModal();
  5655. loadBridge();
  5656. fetchData(false);
  5657. } else {
  5658. const err = await res.json();
  5659. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5660. }
  5661. } catch (err) {
  5662. showToast('Error', err.message, 'error');
  5663. }
  5664. }
  5665. async function toggleBridgePortState(id, disabled) {
  5666. try {
  5667. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5668. method: 'POST',
  5669. headers: { 'Content-Type': 'application/json' },
  5670. body: JSON.stringify({ disabled })
  5671. });
  5672. if (res.ok) {
  5673. loadBridge();
  5674. fetchData(false);
  5675. }
  5676. } catch (err) {
  5677. showToast('Error', err.message, 'error');
  5678. }
  5679. }
  5680. async function deleteBridgePort(id) {
  5681. const p = (state.bridgePorts || []).find(x => x.id === id);
  5682. const iface = p ? p.interface : id;
  5683. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5684. try {
  5685. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5686. if (res.ok) {
  5687. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5688. loadBridge();
  5689. fetchData(false);
  5690. }
  5691. } catch (err) {
  5692. showToast('Error', err.message, 'error');
  5693. }
  5694. }
  5695. // ----------------- Bridge VLANs -----------------
  5696. function renderBridgeVLANs() {
  5697. const tbody = document.getElementById('bridge-vlans-table-body');
  5698. const empty = document.getElementById('bridge-empty-vlans');
  5699. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5700. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5701. if (!tbody) return;
  5702. tbody.innerHTML = '';
  5703. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5704. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5705. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5706. if (vlans.length === 0) {
  5707. empty?.classList.remove('hidden');
  5708. return;
  5709. }
  5710. empty?.classList.add('hidden');
  5711. vlans.forEach((v, idx) => {
  5712. const tr = document.createElement('tr');
  5713. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5714. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5715. ? 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(' ')
  5716. : '<span class="text-slate-600">none</span>';
  5717. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5718. ? 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(' ')
  5719. : '<span class="text-slate-600">none</span>';
  5720. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5721. tr.innerHTML = `
  5722. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5723. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5724. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5725. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5726. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5727. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5728. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5729. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5730. <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>
  5731. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5732. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5733. </td>
  5734. `;
  5735. tbody.appendChild(tr);
  5736. });
  5737. }
  5738. function openAddBridgeVLANModal() {
  5739. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5740. document.getElementById('bridge-vlan-modal-id').value = '';
  5741. populateBridgeSelect('bridge-vlan-modal-bridge');
  5742. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5743. document.getElementById('bridge-vlan-modal-comment').value = '';
  5744. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5745. updateBridgeVlanPortCheckboxes();
  5746. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5747. }
  5748. function openEditBridgeVLANModal(id) {
  5749. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5750. if (!v) return;
  5751. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5752. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5753. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5754. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5755. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5756. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5757. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5758. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5759. }
  5760. function closeBridgeVlanModal() {
  5761. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5762. }
  5763. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5764. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5765. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5766. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5767. if (!taggedBox || !untaggedBox) return;
  5768. // Ports belonging to the selected bridge
  5769. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5770. if (memberPorts.length === 0) {
  5771. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5772. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5773. return;
  5774. }
  5775. taggedBox.innerHTML = memberPorts.map(p => `
  5776. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5777. <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">
  5778. <span>${p.interface}</span>
  5779. </label>
  5780. `).join('');
  5781. untaggedBox.innerHTML = memberPorts.map(p => `
  5782. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5783. <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">
  5784. <span>${p.interface}</span>
  5785. </label>
  5786. `).join('');
  5787. }
  5788. async function submitSaveBridgeVLAN(e) {
  5789. e.preventDefault();
  5790. const id = document.getElementById('bridge-vlan-modal-id').value;
  5791. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5792. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5793. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5794. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5795. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5796. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5797. try {
  5798. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5799. method: 'POST',
  5800. headers: { 'Content-Type': 'application/json' },
  5801. body: JSON.stringify({
  5802. id,
  5803. bridge,
  5804. vlan_ids: vlanIDs,
  5805. tagged,
  5806. untagged,
  5807. comment,
  5808. disabled
  5809. })
  5810. });
  5811. if (res.ok) {
  5812. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5813. closeBridgeVlanModal();
  5814. loadBridge();
  5815. } else {
  5816. const err = await res.json();
  5817. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5818. }
  5819. } catch (err) {
  5820. showToast('Error', err.message, 'error');
  5821. }
  5822. }
  5823. async function toggleBridgeVLANState(id, disabled) {
  5824. try {
  5825. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5826. method: 'POST',
  5827. headers: { 'Content-Type': 'application/json' },
  5828. body: JSON.stringify({ disabled })
  5829. });
  5830. if (res.ok) loadBridge();
  5831. } catch (err) {
  5832. showToast('Error', err.message, 'error');
  5833. }
  5834. }
  5835. async function deleteBridgeVLAN(id) {
  5836. if (!confirm('Delete this bridge VLAN entry?')) return;
  5837. try {
  5838. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5839. if (res.ok) {
  5840. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5841. loadBridge();
  5842. }
  5843. } catch (err) {
  5844. showToast('Error', err.message, 'error');
  5845. }
  5846. }
  5847. // ----------------- Hosts / MAC Table -----------------
  5848. async function loadBridgeHosts() {
  5849. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5850. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5851. try {
  5852. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5853. const res = await fetch(url);
  5854. if (res.ok) {
  5855. state.bridgeHosts = await res.json();
  5856. renderBridgeHosts();
  5857. }
  5858. } catch (err) {
  5859. console.error('Failed to load bridge hosts:', err);
  5860. }
  5861. }
  5862. function renderBridgeHosts() {
  5863. const tbody = document.getElementById('bridge-hosts-table-body');
  5864. const empty = document.getElementById('bridge-empty-hosts');
  5865. const countBadge = document.getElementById('bridge-hosts-count-badge');
  5866. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  5867. if (!tbody) return;
  5868. tbody.innerHTML = '';
  5869. const hosts = (state.bridgeHosts || []).filter(h => {
  5870. if (!search) return true;
  5871. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  5872. });
  5873. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  5874. if (hosts.length === 0) {
  5875. empty?.classList.remove('hidden');
  5876. return;
  5877. }
  5878. empty?.classList.add('hidden');
  5879. hosts.forEach(h => {
  5880. const tr = document.createElement('tr');
  5881. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5882. let flagBadges = '';
  5883. 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>';
  5884. 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>';
  5885. 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>';
  5886. tr.innerHTML = `
  5887. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  5888. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  5889. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  5890. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  5891. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  5892. <td class="py-2.5 px-3">${flagBadges}</td>
  5893. `;
  5894. tbody.appendChild(tr);
  5895. });
  5896. }
  5897. async function flushBridgeHosts() {
  5898. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  5899. if (!selBridge) {
  5900. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  5901. return;
  5902. }
  5903. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  5904. try {
  5905. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  5906. method: 'POST',
  5907. headers: { 'Content-Type': 'application/json' },
  5908. body: JSON.stringify({ bridge: selBridge })
  5909. });
  5910. if (res.ok) {
  5911. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  5912. loadBridgeHosts();
  5913. }
  5914. } catch (err) {
  5915. showToast('Error', err.message, 'error');
  5916. }
  5917. }
  5918. // ----------------- Helpers -----------------
  5919. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  5920. const sel = document.getElementById(selectId);
  5921. if (!sel) return;
  5922. const prevVal = currentVal || sel.value;
  5923. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  5924. (state.bridges || []).forEach(b => {
  5925. const opt = document.createElement('option');
  5926. opt.value = b.name;
  5927. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  5928. if (b.name === prevVal) opt.selected = true;
  5929. sel.appendChild(opt);
  5930. });
  5931. }
  5932. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  5933. const sel = document.getElementById(selectId);
  5934. if (!sel) return;
  5935. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  5936. // 1. Physical Interfaces
  5937. const grpPhys = document.createElement('optgroup');
  5938. grpPhys.label = 'Physical Interfaces';
  5939. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  5940. const opt = document.createElement('option');
  5941. opt.value = i.name;
  5942. opt.innerText = `${i.name} (${i.role || i.type})`;
  5943. if (i.name === currentVal) opt.selected = true;
  5944. grpPhys.appendChild(opt);
  5945. });
  5946. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  5947. // 2. VLAN Sub-interfaces
  5948. const grpVlans = document.createElement('optgroup');
  5949. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  5950. (state.vlans || []).forEach(v => {
  5951. const opt = document.createElement('option');
  5952. opt.value = v.name;
  5953. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  5954. if (v.name === currentVal) opt.selected = true;
  5955. grpVlans.appendChild(opt);
  5956. });
  5957. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  5958. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  5959. const grpEoip = document.createElement('optgroup');
  5960. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  5961. (state.eoipTunnels || []).forEach(t => {
  5962. const opt = document.createElement('option');
  5963. opt.value = t.name;
  5964. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  5965. if (t.name === currentVal) opt.selected = true;
  5966. grpEoip.appendChild(opt);
  5967. });
  5968. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  5969. }