app.js 359 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. fetchData();
  64. // Live polling every 2.5 seconds
  65. setInterval(() => {
  66. if (state.isPolling) {
  67. fetchData(false);
  68. }
  69. }, 2500);
  70. });
  71. // Navigation Handler
  72. function navigate(tabName) {
  73. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  74. navigate('bgp');
  75. return;
  76. }
  77. if (tabName === 'vlans') {
  78. navigate('interfaces');
  79. return;
  80. }
  81. state.activeTab = tabName;
  82. window.location.hash = tabName;
  83. // Update nav links styling
  84. document.querySelectorAll('.nav-link').forEach(link => {
  85. 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';
  86. });
  87. const activeNav = document.getElementById(`nav-${tabName}`);
  88. if (activeNav) {
  89. 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';
  90. }
  91. // Update page headers
  92. const titles = {
  93. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  94. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  95. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  96. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  97. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  98. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  99. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  100. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  101. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  102. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'MikroTik-style route filter chains, prefix matching, BGP attributes & policy maps' },
  103. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  104. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  105. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  106. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  107. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  108. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  109. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  110. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  111. tools: { title: 'Troubleshoot & Diagnostic Tools (/tool)', sub: 'RouterOS-style Ping, Traceroute, MTR Telemetry, DNS resolution, and TCP Port probing' },
  112. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  113. };
  114. const header = titles[tabName] || titles.dashboard;
  115. const pTitle = document.getElementById('page-title');
  116. if (pTitle) pTitle.innerText = header.title;
  117. const pSub = document.getElementById('page-subtitle');
  118. if (pSub) pSub.innerText = header.sub;
  119. // Toggle sections dynamically for all section elements
  120. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  121. if (el.id === `section-${tabName}`) {
  122. el.classList.remove('hidden');
  123. } else {
  124. el.classList.add('hidden');
  125. }
  126. });
  127. if (tabName === 'bridge') loadBridge();
  128. if (tabName === 'firewall') loadFirewall();
  129. if (tabName === 'routes') loadRoutes();
  130. if (tabName === 'bgp') {
  131. loadDynamicRouting();
  132. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  133. }
  134. if (tabName === 'ospf') {
  135. loadDynamicRouting();
  136. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  137. }
  138. if (tabName === 'routing-filters') loadDynamicRouting();
  139. if (tabName === 'dynamic-routing') loadDynamicRouting();
  140. if (tabName === 'ppp') loadPPP();
  141. if (tabName === 'eoip') loadEoIP();
  142. if (tabName === 'persistence') loadDebianConfig();
  143. if (tabName === 'pppoe') loadPPPoE();
  144. if (tabName === 'wireguard') loadWireGuard();
  145. if (tabName === 'ipsec') loadIPSec();
  146. if (tabName === 'l2tp') loadL2TP();
  147. if (tabName === 'pptp') loadPPTP();
  148. if (tabName === 'tools') loadToolsView();
  149. if (tabName === 'dhcp-client') loadDHCPClients();
  150. }
  151. // Fetch all core system, network and VPN telemetry
  152. async function fetchData(isManual = false) {
  153. const spinner = document.getElementById('refresh-spinner');
  154. if (isManual && spinner) spinner.classList.add('animate-spin');
  155. try {
  156. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  157. fetch(`${API_BASE}/system/status`),
  158. fetch(`${API_BASE}/interfaces`),
  159. fetch(`${API_BASE}/vlans`),
  160. fetch(`${API_BASE}/vpn/status`),
  161. fetch(`${API_BASE}/firewall/summary`),
  162. fetch(`${API_BASE}/routing/dynamic/summary`),
  163. fetch(`${API_BASE}/bridge/summary`),
  164. fetch(`${API_BASE}/dhcp/clients/summary`),
  165. fetch(`${API_BASE}/dhcp/clients`)
  166. ]);
  167. if (dhcpSumRes && dhcpSumRes.ok) {
  168. state.dhcpSummary = await dhcpSumRes.json();
  169. const bDhcp = document.getElementById('badge-dhcp-client-count');
  170. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  171. }
  172. if (dhcpClientsRes && dhcpClientsRes.ok) {
  173. state.dhcpClients = await dhcpClientsRes.json();
  174. }
  175. if (brSummaryRes.ok) {
  176. state.bridgeSummary = await brSummaryRes.json();
  177. const bBridge = document.getElementById('badge-bridge-count');
  178. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  179. const sBr = document.getElementById('bridge-stat-bridges');
  180. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sPorts = document.getElementById('bridge-stat-ports');
  182. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  183. const sHosts = document.getElementById('bridge-stat-hosts');
  184. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  185. }
  186. if (statusRes.ok) state.systemStatus = await statusRes.json();
  187. if (ifacesRes.ok) {
  188. const ifacesData = await ifacesRes.json();
  189. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  190. state.interfaces = rawIfaces.filter(i => {
  191. if (!i.name) return false;
  192. if (i.name.startsWith('ep_')) return false;
  193. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  194. });
  195. try { populateToolsInterfaces(); } catch (e) {}
  196. }
  197. if (vlansRes.ok) {
  198. const vlansData = await vlansRes.json();
  199. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  200. }
  201. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  202. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  203. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  204. updateSystemMetrics();
  205. updateBadges();
  206. if (state.activeTab === 'dashboard') renderDashboard();
  207. if (state.activeTab === 'interfaces') renderInterfacesList();
  208. if (state.activeTab === 'vlans') renderVlansList();
  209. if (state.activeTab === 'firewall') loadFirewall(false);
  210. if (state.activeTab === 'routes') loadRoutes(false);
  211. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  212. if (state.activeTab === 'ppp') loadPPP(false);
  213. if (state.activeTab === 'eoip') loadEoIP(false);
  214. if (state.activeTab === 'pppoe') loadPPPoE(false);
  215. if (state.activeTab === 'wireguard') loadWireGuard(false);
  216. if (state.activeTab === 'ipsec') loadIPSec(false);
  217. if (state.activeTab === 'l2tp') loadL2TP(false);
  218. if (state.activeTab === 'pptp') loadPPTP(false);
  219. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  220. } catch (err) {
  221. console.error('Failed to fetch router state:', err);
  222. } finally {
  223. if (isManual && spinner) {
  224. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  225. }
  226. }
  227. }
  228. // Update Top KPI and Sidebar Telemetry
  229. function updateSystemMetrics() {
  230. const s = state.systemStatus;
  231. const v = state.vpnStatus;
  232. if (!s) return;
  233. // Sidebar Host & Uptime
  234. const sideHost = document.getElementById('side-hostname');
  235. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  236. const sideUp = document.getElementById('side-uptime');
  237. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  238. const sideGw = document.getElementById('side-gateway-ip');
  239. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  240. // Compute CPU Metrics
  241. let cpuPct = 0;
  242. if (s.cpu_pct !== undefined) {
  243. cpuPct = s.cpu_pct;
  244. } else if (s.cpu_load && s.cpu_load.length > 0) {
  245. const cores = s.cpu_cores || 1;
  246. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  247. }
  248. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  249. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  250. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  251. // Sidebar CPU
  252. const sideCpuVal = document.getElementById('side-cpu-val');
  253. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  254. const sideCpuBar = document.getElementById('side-cpu-bar');
  255. if (sideCpuBar) {
  256. sideCpuBar.style.width = cpuWidth;
  257. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  258. }
  259. // Dashboard CPU Card
  260. const dashCpuVal = document.getElementById('dash-cpu-val');
  261. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  262. const dashCpuBar = document.getElementById('dash-cpu-bar');
  263. if (dashCpuBar) {
  264. dashCpuBar.style.width = cpuWidth;
  265. if (cpuPct > 85) {
  266. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  267. } else if (cpuPct > 65) {
  268. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  269. } else {
  270. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  271. }
  272. }
  273. const dashCpuCores = document.getElementById('dash-cpu-cores');
  274. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  275. const dashCpuLoad = document.getElementById('dash-cpu-load');
  276. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  277. const dashCpuStatus = document.getElementById('dash-cpu-status');
  278. if (dashCpuStatus) {
  279. if (cpuPct > 85) {
  280. dashCpuStatus.innerText = 'High';
  281. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  282. } else if (cpuPct > 65) {
  283. dashCpuStatus.innerText = 'Heavy';
  284. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  285. } else {
  286. dashCpuStatus.innerText = 'Normal';
  287. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  288. }
  289. }
  290. // Compute RAM Metrics
  291. const memPct = Math.round(s.mem_usage_pct || 0);
  292. const memPctStr = `${memPct}%`;
  293. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  294. const usedMB = s.mem_used_mb || 0;
  295. const totalMB = s.mem_total_mb || 0;
  296. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  297. function fmtMemMB(mb) {
  298. if (mb >= 1024) {
  299. return `${(mb / 1024).toFixed(1)} GB`;
  300. }
  301. return `${mb} MB`;
  302. }
  303. // Sidebar RAM
  304. const sideRamVal = document.getElementById('side-ram-val');
  305. if (sideRamVal) sideRamVal.innerText = memPctStr;
  306. const sideRamBar = document.getElementById('side-ram-bar');
  307. if (sideRamBar) sideRamBar.style.width = memWidth;
  308. // Dashboard RAM Card
  309. const dashRamVal = document.getElementById('dash-ram-val');
  310. if (dashRamVal) dashRamVal.innerText = memPctStr;
  311. const dashRamBar = document.getElementById('dash-ram-bar');
  312. if (dashRamBar) {
  313. dashRamBar.style.width = memWidth;
  314. if (memPct > 85) {
  315. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  316. } else if (memPct > 70) {
  317. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  318. } else {
  319. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  320. }
  321. }
  322. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  323. if (dashRamUsedTotal) {
  324. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  325. }
  326. const dashRamFree = document.getElementById('dash-ram-free');
  327. if (dashRamFree) {
  328. dashRamFree.innerText = fmtMemMB(freeMB);
  329. }
  330. const dashRamStatus = document.getElementById('dash-ram-status');
  331. if (dashRamStatus) {
  332. if (memPct > 85) {
  333. dashRamStatus.innerText = 'High';
  334. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  335. } else {
  336. dashRamStatus.innerText = 'Active';
  337. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  338. }
  339. }
  340. // Legacy Dashboard Stats (Safe checks)
  341. const elIfacesUp = document.getElementById('stat-ifaces-up');
  342. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  343. const elIfacesTot = document.getElementById('stat-ifaces-total');
  344. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  345. const elIfacesDown = document.getElementById('stat-ifaces-down');
  346. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  347. const elVlans = document.getElementById('stat-vlans-count');
  348. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  349. // VPN Status Indicators
  350. if (v) {
  351. const totalActive = v.total_active_tunnels || 0;
  352. const statVpnActive = document.getElementById('stat-vpn-active');
  353. if (statVpnActive) statVpnActive.innerText = totalActive;
  354. const tunnelsDot = document.getElementById('tunnels-dot');
  355. const tunnelsLabel = document.getElementById('tunnels-label');
  356. if (tunnelsDot && tunnelsLabel) {
  357. if (totalActive > 0) {
  358. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  359. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  360. } else {
  361. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  362. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  363. }
  364. }
  365. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  366. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  367. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  368. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  369. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  370. }
  371. // Total Live Bandwidth Rate
  372. let totalRx = 0;
  373. let totalTx = 0;
  374. (state.interfaces || []).forEach(i => {
  375. if (i.rate) {
  376. totalRx += i.rate.rx_bytes_sec || 0;
  377. totalTx += i.rate.tx_bytes_sec || 0;
  378. }
  379. });
  380. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  381. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  382. }
  383. function setDotBadge(id, active) {
  384. const el = document.getElementById(id);
  385. if (!el) return;
  386. if (active) {
  387. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  388. } else {
  389. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  390. }
  391. }
  392. function updateBadges() {
  393. const bIfaces = document.getElementById('badge-ifaces-count');
  394. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  395. const bVlans = document.getElementById('badge-vlans-count');
  396. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  397. if (state.fwSummary) {
  398. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  399. const badgeFw = document.getElementById('badge-firewall-count');
  400. if (badgeFw) badgeFw.innerText = totalFwRules;
  401. }
  402. if (state.vpnStatus) {
  403. const v = state.vpnStatus;
  404. const bEoIP = document.getElementById('badge-eoip-count');
  405. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  406. const bPPPSess = document.getElementById('badge-ppp-sessions');
  407. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  408. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  409. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  410. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  411. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  412. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  413. }
  414. if (state.dynSummary) {
  415. const d = state.dynSummary;
  416. setDotBadge('badge-bgp-dot', d.bgp_running);
  417. setDotBadge('badge-ospf-dot', d.ospf_running);
  418. const bBgp = document.getElementById('badge-bgp-count');
  419. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  420. const bOspf = document.getElementById('badge-ospf-count');
  421. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  422. const bFilters = document.getElementById('badge-filters-count');
  423. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  424. }
  425. }
  426. // Render Dashboard View
  427. function renderDashboard() {
  428. const matrix = document.getElementById('port-matrix');
  429. matrix.innerHTML = '';
  430. (state.interfaces || []).forEach(iface => {
  431. const isUp = iface.state === 'UP';
  432. const isVlan = iface.is_vlan;
  433. const portCard = document.createElement('div');
  434. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  435. isUp
  436. ? (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')
  437. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  438. }`;
  439. portCard.onclick = () => openIfaceModal(iface.name);
  440. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  441. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  442. portCard.innerHTML = `
  443. <div class="flex items-center justify-between mb-2">
  444. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  445. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  446. </div>
  447. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  448. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  449. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  450. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  451. </div>
  452. `;
  453. matrix.appendChild(portCard);
  454. });
  455. const ifaceTbody = document.getElementById('quick-interfaces-table');
  456. if (ifaceTbody) {
  457. ifaceTbody.innerHTML = '';
  458. (state.interfaces || []).forEach(i => {
  459. const isUp = i.state === 'UP';
  460. const tr = document.createElement('tr');
  461. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  462. tr.onclick = () => openIfaceModal(i.name);
  463. const rxStr = i.rate?.rx_human || '0 B/s';
  464. const txStr = i.rate?.tx_human || '0 B/s';
  465. tr.innerHTML = `
  466. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  467. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  468. <span>${i.name}</span>
  469. </td>
  470. <td class="py-2.5 text-slate-300 font-sans">
  471. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  472. </td>
  473. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  474. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  475. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  476. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  477. </td>
  478. <td class="py-2.5 text-right font-sans font-semibold">
  479. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  480. </td>
  481. `;
  482. ifaceTbody.appendChild(tr);
  483. });
  484. }
  485. const vlanTbody = document.getElementById('quick-vlans-table');
  486. if (vlanTbody) {
  487. vlanTbody.innerHTML = '';
  488. }
  489. }
  490. // Expand / Collapse Handlers
  491. function toggleExpand(parentName) {
  492. if (state.expandedParents.has(parentName)) {
  493. state.expandedParents.delete(parentName);
  494. } else {
  495. state.expandedParents.add(parentName);
  496. }
  497. renderInterfacesList();
  498. }
  499. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  500. function supportsVLAN(iface) {
  501. if (!iface) return false;
  502. if (iface.is_vlan) return false;
  503. const name = (iface.name || '').toLowerCase();
  504. const type = (iface.type || '').toLowerCase();
  505. const role = (iface.role || '').toLowerCase();
  506. // Exclude loopback
  507. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  508. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  509. if (type === 'wireguard' || name.startsWith('wg')) return false;
  510. // Exclude PPP / PPPoE
  511. if (type === 'ppp' || name.startsWith('ppp')) return false;
  512. // Exclude other Layer 3 tunnels and dummy devices
  513. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  514. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  515. return false;
  516. }
  517. // If name already contains a dot, it's already a sub-interface
  518. if (name.includes('.')) return false;
  519. return true;
  520. }
  521. // Expand / Collapse Handlers
  522. function toggleExpand(parentName) {
  523. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  524. if (childVlans.length === 0) {
  525. // Cannot expand an interface with no VLANs
  526. state.expandedParents.delete(parentName);
  527. return;
  528. }
  529. if (state.expandedParents.has(parentName)) {
  530. state.expandedParents.delete(parentName);
  531. } else {
  532. state.expandedParents.add(parentName);
  533. }
  534. renderInterfacesList();
  535. }
  536. function expandAllIfaces(expand) {
  537. if (expand) {
  538. (state.interfaces || []).forEach(i => {
  539. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  540. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  541. });
  542. } else {
  543. state.expandedParents.clear();
  544. }
  545. renderInterfacesList();
  546. }
  547. // Filter and Render Hierarchical Interfaces List
  548. function filterIfaces(filter) {
  549. state.ifaceFilter = filter || 'all';
  550. renderInterfacesList();
  551. }
  552. function renderInterfacesList() {
  553. const tbody = document.getElementById('interfaces-tree-tbody');
  554. const emptyState = document.getElementById('interfaces-empty-state');
  555. const summary = document.getElementById('ifaces-list-summary');
  556. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  557. tbody.innerHTML = '';
  558. const allIfaces = state.interfaces || [];
  559. const allVlans = state.vlans || [];
  560. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  561. const filteredParents = parentIfaces.filter(parent => {
  562. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  563. if (query) {
  564. const matchName = parent.name.toLowerCase().includes(query);
  565. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  566. const matchRole = (parent.role || '').toLowerCase().includes(query);
  567. const matchType = (parent.type || '').toLowerCase().includes(query);
  568. const matchVlan = childVlans.some(v =>
  569. v.name.toLowerCase().includes(query) ||
  570. String(v.vlan_id).includes(query) ||
  571. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  572. (v.description || '').toLowerCase().includes(query)
  573. );
  574. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  575. }
  576. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  577. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  578. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  579. return true;
  580. });
  581. if (summary) {
  582. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  583. }
  584. if (filteredParents.length === 0) {
  585. emptyState?.classList.remove('hidden');
  586. return;
  587. }
  588. emptyState?.classList.add('hidden');
  589. filteredParents.forEach(parent => {
  590. const isUp = parent.state === 'UP';
  591. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  592. const hasVlans = childVlans.length > 0;
  593. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  594. const canHaveVlan = supportsVLAN(parent);
  595. const parentRow = document.createElement('tr');
  596. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  597. parentRow.innerHTML = `
  598. <td class="py-3 px-3 text-center">
  599. ${hasVlans ? `
  600. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  601. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  602. <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">
  603. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  604. </svg>
  605. </button>
  606. ` : `
  607. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  608. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  609. </div>
  610. `}
  611. </td>
  612. <td class="py-3 px-4">
  613. <div class="flex items-center space-x-2.5">
  614. <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">
  615. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  616. </div>
  617. <div>
  618. <div class="flex items-center gap-2">
  619. ${hasVlans ? `
  620. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  621. <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>
  622. ` : `
  623. <span class="font-bold text-white text-sm">${parent.name}</span>
  624. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  625. `}
  626. </div>
  627. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  628. </div>
  629. </div>
  630. </td>
  631. <td class="py-3 px-4 font-sans">
  632. <div class="flex items-center gap-1.5">
  633. <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>
  634. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  635. </div>
  636. </td>
  637. <td class="py-3 px-4">
  638. ${parent.ipv4 && parent.ipv4.length > 0
  639. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  640. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  641. }
  642. ${(() => {
  643. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  644. if (!c) return '';
  645. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  646. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  647. })()}
  648. </td>
  649. <td class="py-3 px-4 text-slate-400 text-[11px]">
  650. <div>${parent.mac || 'N/A'}</div>
  651. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  652. </td>
  653. <td class="py-3 px-4 text-[11px]">
  654. <div class="flex items-center space-x-2">
  655. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  656. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  657. </div>
  658. </td>
  659. <td class="py-3 px-4 font-sans">
  660. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  661. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  662. 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'
  663. }" title="Click to toggle link status">
  664. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  665. <span>${parent.state}</span>
  666. </button>
  667. </td>
  668. <td class="py-3 px-4 text-right space-x-2 font-sans">
  669. ${(() => {
  670. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  671. if (c) {
  672. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  673. }
  674. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  675. })()}
  676. ${canHaveVlan ? `
  677. <button onclick="openVlanModal('${parent.name}')"
  678. 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">
  679. + Add VLAN
  680. </button>
  681. ` : ''}
  682. <button onclick="openIfaceModal('${parent.name}')"
  683. 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">
  684. Configure
  685. </button>
  686. </td>
  687. `;
  688. tbody.appendChild(parentRow);
  689. if (isExpanded) {
  690. const drawerRow = document.createElement('tr');
  691. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  692. const drawerCell = document.createElement('td');
  693. drawerCell.colSpan = 8;
  694. drawerCell.className = 'p-0';
  695. drawerCell.innerHTML = `
  696. <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">
  697. <div class="flex items-center justify-between mb-3">
  698. <div class="flex items-center space-x-3">
  699. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  700. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  701. </span>
  702. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  703. ${childVlans.length} Attached
  704. </span>
  705. </div>
  706. <button onclick="openVlanModal('${parent.name}')"
  707. 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">
  708. <span>+ Create VLAN on ${parent.name}</span>
  709. </button>
  710. </div>
  711. ${childVlans.length === 0 ? `
  712. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  713. <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>
  714. <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">
  715. <span>+ Create Your First VLAN on ${parent.name}</span>
  716. </button>
  717. </div>
  718. ` : `
  719. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  720. <table class="w-full text-left text-xs font-mono">
  721. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  722. <tr>
  723. <th class="py-2.5 px-4">VLAN ID</th>
  724. <th class="py-2.5 px-4">Interface Device</th>
  725. <th class="py-2.5 px-4">Subnet Gateway</th>
  726. <th class="py-2.5 px-4">Role / Alias</th>
  727. <th class="py-2.5 px-4">MTU</th>
  728. <th class="py-2.5 px-4">Throughput</th>
  729. <th class="py-2.5 px-4">Status</th>
  730. <th class="py-2.5 px-4 text-right">Actions</th>
  731. </tr>
  732. </thead>
  733. <tbody class="divide-y divide-slate-800/70">
  734. ${childVlans.map(v => {
  735. const isVlanUp = v.state === 'UP';
  736. return `
  737. <tr class="hover:bg-slate-800/40 transition">
  738. <td class="py-2.5 px-4">
  739. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  740. VLAN ${v.vlan_id}
  741. </span>
  742. </td>
  743. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  744. <span class="text-cyan-500">└─</span>
  745. <span>${v.name}</span>
  746. </td>
  747. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  748. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  749. ${(() => {
  750. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  751. if (!c) return '';
  752. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  753. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  754. })()}
  755. </td>
  756. <td class="py-2.5 px-4 font-sans text-slate-300">
  757. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  758. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  759. </td>
  760. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  761. <td class="py-2.5 px-4 text-[11px]">
  762. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  763. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  764. </td>
  765. <td class="py-2.5 px-4 font-sans">
  766. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  767. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  768. 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'
  769. }">
  770. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  771. <span>${v.state}</span>
  772. </button>
  773. </td>
  774. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  775. ${(() => {
  776. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  777. if (c) {
  778. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  779. }
  780. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  781. })()}
  782. <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>
  783. <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>
  784. </td>
  785. </tr>
  786. `;
  787. }).join('')}
  788. </tbody>
  789. </table>
  790. </div>
  791. `}
  792. </div>
  793. `;
  794. drawerRow.appendChild(drawerCell);
  795. tbody.appendChild(drawerRow);
  796. }
  797. });
  798. }
  799. // Render VLANs Dedicated View
  800. function renderVlansList() {
  801. const tbody = document.getElementById('vlans-table-body');
  802. if (!tbody) return;
  803. const emptyState = document.getElementById('vlans-empty-state');
  804. const countBadge = document.getElementById('vlans-table-count');
  805. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  806. tbody.innerHTML = '';
  807. const allVlans = state.vlans || [];
  808. if (countBadge) countBadge.innerText = allVlans.length;
  809. const filtered = allVlans.filter(v => {
  810. if (!query) return true;
  811. return v.name.toLowerCase().includes(query) ||
  812. String(v.vlan_id).includes(query) ||
  813. (v.description || '').toLowerCase().includes(query) ||
  814. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  815. });
  816. if (allVlans.length === 0) {
  817. emptyState.classList.remove('hidden');
  818. return;
  819. }
  820. emptyState.classList.add('hidden');
  821. filtered.forEach(v => {
  822. const isUp = v.state === 'UP';
  823. const tr = document.createElement('tr');
  824. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  825. tr.innerHTML = `
  826. <td class="py-3 px-4">
  827. <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">
  828. VLAN ${v.vlan_id}
  829. </span>
  830. </td>
  831. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  832. <td class="py-3 px-4 text-slate-300">
  833. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  834. </td>
  835. <td class="py-3 px-4 text-emerald-400 font-medium">
  836. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  837. </td>
  838. <td class="py-3 px-4 text-slate-300 font-sans">
  839. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  840. </td>
  841. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  842. <td class="py-3 px-4 font-sans">
  843. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  844. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  845. 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'
  846. }">
  847. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  848. <span>${v.state}</span>
  849. </button>
  850. </td>
  851. <td class="py-3 px-4 text-right space-x-2 font-sans">
  852. <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>
  853. <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>
  854. </td>
  855. `;
  856. tbody.appendChild(tr);
  857. });
  858. }
  859. // Toggle interface UP / DOWN
  860. async function toggleInterfaceState(name, newState) {
  861. try {
  862. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  863. method: 'POST',
  864. headers: { 'Content-Type': 'application/json' },
  865. body: JSON.stringify({ state: newState })
  866. });
  867. const data = await res.json();
  868. if (res.ok) {
  869. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  870. fetchData(false);
  871. } else {
  872. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  873. }
  874. } catch (err) {
  875. showToast('Error', err.message, 'error');
  876. }
  877. }
  878. // ---------------- MikroTik Flag & Utilities ----------------
  879. function renderMikroTikFlag(running, disabled) {
  880. if (running) {
  881. 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>`;
  882. }
  883. if (disabled) {
  884. 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>`;
  885. }
  886. 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>`;
  887. }
  888. function copyToClipboard(text, label = 'Text') {
  889. navigator.clipboard.writeText(text).then(() => {
  890. showToast('Copied', `${label} copied to clipboard`, 'success');
  891. }).catch(() => {
  892. prompt('Copy value:', text);
  893. });
  894. }
  895. // ======================== PPPoE Multi-Instance ========================
  896. async function loadPPPoE(populateInputs = true) {
  897. try {
  898. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  899. const list = await res.json();
  900. state.pppoeList = Array.isArray(list) ? list : [];
  901. const badge = document.getElementById('pppoe-count-badge');
  902. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  903. const tbody = document.getElementById('pppoe-table-body');
  904. const empty = document.getElementById('pppoe-empty');
  905. if (!tbody) return;
  906. tbody.innerHTML = '';
  907. if (state.pppoeList.length === 0) {
  908. if (empty) empty.classList.remove('hidden');
  909. } else {
  910. if (empty) empty.classList.add('hidden');
  911. state.pppoeList.forEach(inst => {
  912. const tr = document.createElement('tr');
  913. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  914. tr.innerHTML = `
  915. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  916. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  917. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  918. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  919. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  920. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  921. <td class="py-2.5 px-3 text-center">
  922. <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'}">
  923. ${inst.default_route ? 'Yes' : 'No'}
  924. </span>
  925. </td>
  926. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  927. ${inst.running ? `
  928. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  929. ` : `
  930. <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>
  931. `}
  932. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  933. ${inst.disabled ? 'Enable' : 'Disable'}
  934. </button>
  935. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  936. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  937. </td>
  938. `;
  939. tbody.appendChild(tr);
  940. });
  941. }
  942. } catch (err) {
  943. console.error('Failed to load PPPoE:', err);
  944. }
  945. }
  946. function openAddPPPoEModal() {
  947. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  948. document.getElementById('pppoe-modal-edit-orig').value = '';
  949. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  950. document.getElementById('pppoe-modal-name').readOnly = false;
  951. document.getElementById('pppoe-modal-user').value = '';
  952. document.getElementById('pppoe-modal-pass').value = '';
  953. document.getElementById('pppoe-modal-service').value = '';
  954. document.getElementById('pppoe-modal-mtu').value = '1492';
  955. document.getElementById('pppoe-modal-defroute').checked = true;
  956. document.getElementById('pppoe-modal-reconnect').checked = true;
  957. document.getElementById('pppoe-modal-disabled').checked = false;
  958. // Populate interfaces
  959. const sel = document.getElementById('pppoe-modal-iface');
  960. sel.innerHTML = '';
  961. (state.interfaces || []).forEach(i => {
  962. if (i.name === 'lo') return;
  963. const opt = document.createElement('option');
  964. opt.value = i.name;
  965. opt.innerText = `${i.name} (${i.role || i.type})`;
  966. sel.appendChild(opt);
  967. });
  968. document.getElementById('pppoe-modal').classList.remove('hidden');
  969. }
  970. function openEditPPPoEModal(name) {
  971. const inst = (state.pppoeList || []).find(i => i.name === name);
  972. if (!inst) return;
  973. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  974. document.getElementById('pppoe-modal-edit-orig').value = name;
  975. document.getElementById('pppoe-modal-name').value = inst.name;
  976. document.getElementById('pppoe-modal-name').readOnly = true;
  977. document.getElementById('pppoe-modal-user').value = inst.username || '';
  978. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  979. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  980. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  981. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  982. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  983. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  984. const sel = document.getElementById('pppoe-modal-iface');
  985. sel.innerHTML = '';
  986. (state.interfaces || []).forEach(i => {
  987. if (i.name === 'lo') return;
  988. const opt = document.createElement('option');
  989. opt.value = i.name;
  990. opt.innerText = `${i.name} (${i.role || i.type})`;
  991. if (i.name === inst.interface) opt.selected = true;
  992. sel.appendChild(opt);
  993. });
  994. document.getElementById('pppoe-modal').classList.remove('hidden');
  995. }
  996. function closePPPoEModal() {
  997. document.getElementById('pppoe-modal').classList.add('hidden');
  998. }
  999. async function submitSavePPPoE(e) {
  1000. e.preventDefault();
  1001. const name = document.getElementById('pppoe-modal-name').value.trim();
  1002. const iface = document.getElementById('pppoe-modal-iface').value;
  1003. const user = document.getElementById('pppoe-modal-user').value.trim();
  1004. const pass = document.getElementById('pppoe-modal-pass').value;
  1005. const service = document.getElementById('pppoe-modal-service').value.trim();
  1006. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1007. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1008. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1009. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1010. try {
  1011. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1012. method: 'POST',
  1013. headers: { 'Content-Type': 'application/json' },
  1014. body: JSON.stringify({
  1015. name,
  1016. interface: iface,
  1017. username: user,
  1018. password: pass,
  1019. service_name: service,
  1020. mtu,
  1021. default_route: defRoute,
  1022. auto_reconnect: reconnect,
  1023. disabled
  1024. })
  1025. });
  1026. if (res.ok) {
  1027. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1028. closePPPoEModal();
  1029. loadPPPoE(false);
  1030. fetchData(false);
  1031. } else {
  1032. const err = await res.json();
  1033. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1034. }
  1035. } catch (err) {
  1036. showToast('Error', err.message, 'error');
  1037. }
  1038. }
  1039. async function connectPPPoEInstance(name) {
  1040. try {
  1041. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1042. if (res.ok) {
  1043. showToast('Connecting', `Dialing ${name}...`, 'info');
  1044. setTimeout(() => loadPPPoE(false), 2000);
  1045. }
  1046. } catch (err) {
  1047. showToast('Error', err.message, 'error');
  1048. }
  1049. }
  1050. async function disconnectPPPoEInstance(name) {
  1051. try {
  1052. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1053. if (res.ok) {
  1054. showToast('Disconnected', `${name} session terminated`, 'info');
  1055. setTimeout(() => loadPPPoE(false), 1000);
  1056. }
  1057. } catch (err) {
  1058. showToast('Error', err.message, 'error');
  1059. }
  1060. }
  1061. async function togglePPPoEState(name, enable) {
  1062. try {
  1063. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1064. method: 'POST',
  1065. headers: { 'Content-Type': 'application/json' },
  1066. body: JSON.stringify({ enabled: enable })
  1067. });
  1068. if (res.ok) {
  1069. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1070. loadPPPoE(false);
  1071. }
  1072. } catch (err) {
  1073. showToast('Error', err.message, 'error');
  1074. }
  1075. }
  1076. async function deletePPPoEInstance(name) {
  1077. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1078. try {
  1079. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1080. if (res.ok) {
  1081. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1082. loadPPPoE(false);
  1083. fetchData(false);
  1084. }
  1085. } catch (err) {
  1086. showToast('Error', err.message, 'error');
  1087. }
  1088. }
  1089. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1090. state.wgSubTab = 'ifaces';
  1091. function switchWGSubTab(tab) {
  1092. state.wgSubTab = tab;
  1093. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1094. const peersPanel = document.getElementById('wg-subtab-peers');
  1095. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1096. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1097. if (tab === 'ifaces') {
  1098. ifacesPanel?.classList.remove('hidden');
  1099. peersPanel?.classList.add('hidden');
  1100. 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';
  1101. 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';
  1102. } else {
  1103. ifacesPanel?.classList.add('hidden');
  1104. peersPanel?.classList.remove('hidden');
  1105. 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';
  1106. 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';
  1107. renderWGPeers();
  1108. }
  1109. }
  1110. async function loadWireGuard(populateInputs = true) {
  1111. try {
  1112. const [ifacesRes, peersRes] = await Promise.all([
  1113. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1114. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1115. ]);
  1116. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1117. const peers = peersRes.ok ? await peersRes.json() : [];
  1118. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1119. state.wgPeers = Array.isArray(peers) ? peers : [];
  1120. // Badges
  1121. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1122. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1123. const peersCountBadge = document.getElementById('wg-peers-count');
  1124. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1125. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1126. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1127. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1128. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1129. // Render Interfaces
  1130. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1131. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1132. if (ifacesTbody) {
  1133. ifacesTbody.innerHTML = '';
  1134. if (state.wgInterfaces.length === 0) {
  1135. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1136. } else {
  1137. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1138. state.wgInterfaces.forEach(iface => {
  1139. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1140. const tr = document.createElement('tr');
  1141. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1142. tr.innerHTML = `
  1143. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1144. <td class="py-2.5 px-3">
  1145. <div class="flex items-center gap-1.5">
  1146. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1147. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1148. </div>
  1149. </td>
  1150. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1151. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1152. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1153. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1154. ${(iface.public_key || '').substring(0, 10)}... 📋
  1155. </span>
  1156. </td>
  1157. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1158. <td class="py-2.5 px-3 text-center">
  1159. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1160. </td>
  1161. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1162. ${iface.running ? `
  1163. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1164. ` : `
  1165. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1166. `}
  1167. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1168. ${iface.disabled ? 'Enable' : 'Disable'}
  1169. </button>
  1170. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1171. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1172. </td>
  1173. `;
  1174. ifacesTbody.appendChild(tr);
  1175. });
  1176. }
  1177. }
  1178. // Populate filter dropdown in peers tab
  1179. const filterSel = document.getElementById('wg-peers-filter-iface');
  1180. if (filterSel) {
  1181. const currentVal = filterSel.value;
  1182. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1183. state.wgInterfaces.forEach(i => {
  1184. const opt = document.createElement('option');
  1185. opt.value = i.name;
  1186. opt.innerText = i.name;
  1187. if (i.name === currentVal) opt.selected = true;
  1188. filterSel.appendChild(opt);
  1189. });
  1190. }
  1191. renderWGPeers();
  1192. } catch (err) {
  1193. console.error('Failed to load WireGuard:', err);
  1194. }
  1195. }
  1196. function renderWGPeers() {
  1197. const filterSel = document.getElementById('wg-peers-filter-iface');
  1198. const selectedIface = filterSel ? filterSel.value : '';
  1199. const tbody = document.getElementById('wg-peers-table-body');
  1200. const empty = document.getElementById('wg-peers-empty');
  1201. if (!tbody) return;
  1202. tbody.innerHTML = '';
  1203. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1204. if (filtered.length === 0) {
  1205. if (empty) empty.classList.remove('hidden');
  1206. } else {
  1207. if (empty) empty.classList.add('hidden');
  1208. filtered.forEach(p => {
  1209. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1210. const tr = document.createElement('tr');
  1211. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1212. tr.innerHTML = `
  1213. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1214. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1215. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1216. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1217. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1218. ${(p.public_key || '').substring(0, 10)}... 📋
  1219. </span>
  1220. </td>
  1221. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1222. <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>
  1223. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1224. <td class="py-2.5 px-3 font-mono text-[11px]">
  1225. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1226. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1227. </td>
  1228. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1229. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1230. ${p.disabled ? 'Enable' : 'Disable'}
  1231. </button>
  1232. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1233. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1234. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1235. </td>
  1236. `;
  1237. tbody.appendChild(tr);
  1238. });
  1239. }
  1240. }
  1241. function openAddWGInterfaceModal() {
  1242. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1243. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1244. const nameEl = document.getElementById('wg-iface-modal-name');
  1245. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1246. nameEl.readOnly = false;
  1247. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1248. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1249. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1250. document.getElementById('wg-iface-modal-comment').value = '';
  1251. document.getElementById('wg-iface-modal-pubkey').value = '';
  1252. document.getElementById('wg-iface-modal-privkey').value = '';
  1253. document.getElementById('wg-iface-modal-disabled').checked = false;
  1254. generateWGInterfaceKeys();
  1255. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1256. }
  1257. function openEditWGInterfaceModal(name) {
  1258. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1259. if (!iface) return;
  1260. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1261. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1262. const nameEl = document.getElementById('wg-iface-modal-name');
  1263. nameEl.value = iface.name;
  1264. nameEl.readOnly = false; // ALLOW RENAMING
  1265. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1266. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1267. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1268. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1269. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1270. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1271. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1272. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1273. }
  1274. function closeAddWGInterfaceModal() {
  1275. document.getElementById('wg-iface-modal').classList.add('hidden');
  1276. }
  1277. async function generateWGInterfaceKeys() {
  1278. try {
  1279. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1280. const keys = await res.json();
  1281. if (res.ok) {
  1282. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1283. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1284. }
  1285. } catch (err) {
  1286. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1287. }
  1288. }
  1289. async function onWGInterfacePrivKeyInput() {
  1290. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1291. if (!privKey) return;
  1292. try {
  1293. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1294. method: 'POST',
  1295. headers: { 'Content-Type': 'application/json' },
  1296. body: JSON.stringify({ private_key: privKey })
  1297. });
  1298. if (res.ok) {
  1299. const data = await res.json();
  1300. if (data.public_key) {
  1301. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1302. }
  1303. }
  1304. } catch (err) {
  1305. // Ignore while typing
  1306. }
  1307. }
  1308. function toggleWGPrivKeyVisibility() {
  1309. const el = document.getElementById('wg-iface-modal-privkey');
  1310. const btn = document.getElementById('btn-toggle-wg-privkey');
  1311. if (el.type === 'password') {
  1312. el.type = 'text';
  1313. btn.innerText = '🙈 Hide';
  1314. } else {
  1315. el.type = 'password';
  1316. btn.innerText = '👁️ Show';
  1317. }
  1318. }
  1319. function copyWGInterfacePubKey() {
  1320. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1321. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1322. }
  1323. async function submitSaveWGInterface(e) {
  1324. e.preventDefault();
  1325. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1326. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1327. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1328. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1329. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1330. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1331. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1332. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1333. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1334. try {
  1335. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1336. method: 'POST',
  1337. headers: { 'Content-Type': 'application/json' },
  1338. body: JSON.stringify({
  1339. orig_name: origName,
  1340. name,
  1341. listen_port: port,
  1342. address: addr,
  1343. mtu,
  1344. comment,
  1345. public_key: pub,
  1346. private_key: priv,
  1347. disabled
  1348. })
  1349. });
  1350. const data = await res.json();
  1351. if (res.ok) {
  1352. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1353. closeAddWGInterfaceModal();
  1354. loadWireGuard(false);
  1355. fetchData(false);
  1356. } else {
  1357. showToast('Error', data.error || 'Failed to save interface', 'error');
  1358. }
  1359. } catch (err) {
  1360. showToast('Error', err.message, 'error');
  1361. }
  1362. }
  1363. async function startWGInterface(name) {
  1364. try {
  1365. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1366. if (res.ok) {
  1367. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1368. loadWireGuard(false);
  1369. fetchData(false);
  1370. }
  1371. } catch (err) {
  1372. showToast('Error', err.message, 'error');
  1373. }
  1374. }
  1375. async function stopWGInterface(name) {
  1376. try {
  1377. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1378. if (res.ok) {
  1379. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1380. loadWireGuard(false);
  1381. fetchData(false);
  1382. }
  1383. } catch (err) {
  1384. showToast('Error', err.message, 'error');
  1385. }
  1386. }
  1387. async function toggleWGInterfaceState(name, enable) {
  1388. try {
  1389. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1390. method: 'POST',
  1391. headers: { 'Content-Type': 'application/json' },
  1392. body: JSON.stringify({ enabled: enable })
  1393. });
  1394. if (res.ok) {
  1395. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1396. loadWireGuard(false);
  1397. fetchData(false);
  1398. }
  1399. } catch (err) {
  1400. showToast('Error', err.message, 'error');
  1401. }
  1402. }
  1403. async function deleteWGInterface(name) {
  1404. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1405. try {
  1406. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1407. if (res.ok) {
  1408. showToast('Deleted', `Interface ${name} removed`, 'success');
  1409. loadWireGuard(false);
  1410. fetchData(false);
  1411. }
  1412. } catch (err) {
  1413. showToast('Error', err.message, 'error');
  1414. }
  1415. }
  1416. function populateWGPeerIfaceSelect(selectedIface = '') {
  1417. const sel = document.getElementById('wg-peer-modal-iface');
  1418. if (!sel) return;
  1419. sel.innerHTML = '';
  1420. (state.wgInterfaces || []).forEach(i => {
  1421. const opt = document.createElement('option');
  1422. opt.value = i.name;
  1423. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1424. if (i.name === selectedIface) opt.selected = true;
  1425. sel.appendChild(opt);
  1426. });
  1427. }
  1428. function openAddWGPeerModal() {
  1429. if ((state.wgInterfaces || []).length === 0) {
  1430. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1431. openAddWGInterfaceModal();
  1432. return;
  1433. }
  1434. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1435. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1436. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1437. populateWGPeerIfaceSelect();
  1438. document.getElementById('wg-peer-modal-name').value = '';
  1439. document.getElementById('wg-peer-modal-pubkey').value = '';
  1440. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1441. document.getElementById('wg-peer-modal-endpoint').value = '';
  1442. document.getElementById('wg-peer-modal-port').value = '';
  1443. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1444. document.getElementById('wg-peer-modal-preshared').value = '';
  1445. document.getElementById('wg-peer-modal-disabled').checked = false;
  1446. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1447. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1448. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1449. }
  1450. function openEditWGPeerModal(ifaceName, pubKey) {
  1451. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1452. if (!peer) {
  1453. showToast('Not Found', 'Peer not found', 'warning');
  1454. return;
  1455. }
  1456. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1457. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1458. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1459. populateWGPeerIfaceSelect(peer.interface);
  1460. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1461. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1462. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1463. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1464. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1465. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1466. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1467. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1468. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1469. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1470. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1471. }
  1472. function closeAddWGPeerModal() {
  1473. document.getElementById('wg-peer-modal').classList.add('hidden');
  1474. }
  1475. async function generatePeerKeypairHelper() {
  1476. try {
  1477. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1478. const keys = await res.json();
  1479. if (res.ok) {
  1480. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1481. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1482. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1483. checkWGPeerKeyValidity();
  1484. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1485. }
  1486. } catch (err) {
  1487. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1488. }
  1489. }
  1490. function copyGeneratedPeerPrivKey() {
  1491. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1492. if (priv) copyToClipboard(priv, 'Client Private Key');
  1493. }
  1494. async function generatePeerPSK() {
  1495. try {
  1496. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1497. const keys = await res.json();
  1498. if (res.ok && keys.private_key) {
  1499. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1500. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1501. }
  1502. } catch (err) {
  1503. showToast('Error', err.message, 'error');
  1504. }
  1505. }
  1506. function checkWGPeerKeyValidity() {
  1507. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1508. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1509. const warningEl = document.getElementById('wg-peer-key-warning');
  1510. if (!warningEl) return;
  1511. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1512. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1513. warningEl.classList.remove('hidden');
  1514. } else {
  1515. warningEl.classList.add('hidden');
  1516. }
  1517. }
  1518. async function submitSaveWGPeer(e) {
  1519. e.preventDefault();
  1520. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1521. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1522. const iface = document.getElementById('wg-peer-modal-iface').value;
  1523. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1524. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1525. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1526. .split(',')
  1527. .map(s => s.trim())
  1528. .filter(s => s.length > 0);
  1529. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1530. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1531. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1532. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1533. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1534. // Validation
  1535. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1536. if (targetIface && targetIface.public_key === pub) {
  1537. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1538. return;
  1539. }
  1540. try {
  1541. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1542. method: 'POST',
  1543. headers: { 'Content-Type': 'application/json' },
  1544. body: JSON.stringify({
  1545. orig_interface: origIface,
  1546. orig_public_key: origPubKey,
  1547. interface: iface,
  1548. name,
  1549. public_key: pub,
  1550. allowed_ips: allowed,
  1551. endpoint_address: epHost,
  1552. endpoint_port: epPort,
  1553. persistent_keepalive: keepalive,
  1554. preshared_key: psk,
  1555. disabled
  1556. })
  1557. });
  1558. const data = await res.json();
  1559. if (res.ok) {
  1560. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1561. closeAddWGPeerModal();
  1562. loadWireGuard(false);
  1563. } else {
  1564. showToast('Error', data.error || 'Failed to save peer', 'error');
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function toggleWGPeerState(iface, pubkey, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1576. });
  1577. const data = await res.json();
  1578. if (res.ok) {
  1579. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1580. loadWireGuard(false);
  1581. } else {
  1582. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1583. }
  1584. } catch (err) {
  1585. showToast('Error', err.message, 'error');
  1586. }
  1587. }
  1588. async function deleteWGPeer(iface, pubkey) {
  1589. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1590. try {
  1591. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1592. method: 'POST',
  1593. headers: { 'Content-Type': 'application/json' },
  1594. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1595. });
  1596. const data = await res.json();
  1597. if (res.ok) {
  1598. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1599. loadWireGuard(false);
  1600. } else {
  1601. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1602. }
  1603. } catch (err) {
  1604. showToast('Error', err.message, 'error');
  1605. }
  1606. }
  1607. // ======================== IPSec Multi-Tunnel ========================
  1608. async function loadIPSec(populateInputs = true) {
  1609. try {
  1610. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1611. const list = await res.json();
  1612. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1613. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1614. const badge = document.getElementById('ipsec-sas-badge');
  1615. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1616. const tbody = document.getElementById('ipsec-table-body');
  1617. const empty = document.getElementById('ipsec-empty');
  1618. if (!tbody) return;
  1619. tbody.innerHTML = '';
  1620. if (state.ipsecTunnels.length === 0) {
  1621. if (empty) empty.classList.remove('hidden');
  1622. } else {
  1623. if (empty) empty.classList.add('hidden');
  1624. state.ipsecTunnels.forEach(c => {
  1625. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1626. const tr = document.createElement('tr');
  1627. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1628. tr.innerHTML = `
  1629. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1630. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1631. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1632. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1633. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 font-sans">
  1635. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1636. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1637. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1638. </td>
  1639. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1640. ${isEstablished ? `
  1641. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1642. ` : `
  1643. <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>
  1644. `}
  1645. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1646. ${c.disabled ? 'Enable' : 'Disable'}
  1647. </button>
  1648. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1649. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1650. </td>
  1651. `;
  1652. tbody.appendChild(tr);
  1653. });
  1654. }
  1655. } catch (err) {
  1656. console.error('Failed to load IPSec:', err);
  1657. }
  1658. }
  1659. function openAddIPSecModal() {
  1660. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1661. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1662. document.getElementById('ipsec-modal-name').readOnly = false;
  1663. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1664. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1665. document.getElementById('ipsec-modal-remotegw').value = '';
  1666. document.getElementById('ipsec-modal-psk').value = '';
  1667. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1668. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1669. document.getElementById('ipsec-modal-autostart').checked = true;
  1670. document.getElementById('ipsec-modal-disabled').checked = false;
  1671. document.getElementById('ipsec-modal').classList.remove('hidden');
  1672. }
  1673. function openEditIPSecModal(name) {
  1674. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1675. if (!conn) return;
  1676. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1677. document.getElementById('ipsec-modal-name').value = conn.name;
  1678. document.getElementById('ipsec-modal-name').readOnly = true;
  1679. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1680. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1681. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1682. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1683. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1684. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1685. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1686. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1687. document.getElementById('ipsec-modal').classList.remove('hidden');
  1688. }
  1689. function closeAddIPSecModal() {
  1690. document.getElementById('ipsec-modal').classList.add('hidden');
  1691. }
  1692. async function submitSaveIPSec(e) {
  1693. e.preventDefault();
  1694. const name = document.getElementById('ipsec-modal-name').value.trim();
  1695. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1696. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1697. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1698. const psk = document.getElementById('ipsec-modal-psk').value;
  1699. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1700. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1701. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1702. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1703. try {
  1704. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1705. method: 'POST',
  1706. headers: { 'Content-Type': 'application/json' },
  1707. body: JSON.stringify({
  1708. name,
  1709. local_addrs: '%any',
  1710. remote_addrs: remotegw,
  1711. local_subnet: localts,
  1712. remote_subnet: remotets,
  1713. preshared_key: psk,
  1714. ike_proposals: ike,
  1715. esp_proposals: esp,
  1716. auto_start: autostart,
  1717. disabled
  1718. })
  1719. });
  1720. if (res.ok) {
  1721. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1722. closeAddIPSecModal();
  1723. loadIPSec(false);
  1724. fetchData(false);
  1725. }
  1726. } catch (err) {
  1727. showToast('Error', err.message, 'error');
  1728. }
  1729. }
  1730. async function startIPSecTunnel(name) {
  1731. try {
  1732. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1733. if (res.ok) {
  1734. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1735. setTimeout(() => loadIPSec(false), 2000);
  1736. }
  1737. } catch (err) {
  1738. showToast('Error', err.message, 'error');
  1739. }
  1740. }
  1741. async function stopIPSecTunnel(name) {
  1742. try {
  1743. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1744. if (res.ok) {
  1745. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1746. loadIPSec(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function toggleIPSecState(name, enable) {
  1753. try {
  1754. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1755. method: 'POST',
  1756. headers: { 'Content-Type': 'application/json' },
  1757. body: JSON.stringify({ enabled: enable })
  1758. });
  1759. if (res.ok) {
  1760. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1761. loadIPSec(false);
  1762. }
  1763. } catch (err) {
  1764. showToast('Error', err.message, 'error');
  1765. }
  1766. }
  1767. async function deleteIPSecConn(name) {
  1768. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1769. try {
  1770. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1771. if (res.ok) {
  1772. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1773. loadIPSec(false);
  1774. fetchData(false);
  1775. }
  1776. } catch (err) {
  1777. showToast('Error', err.message, 'error');
  1778. }
  1779. }
  1780. // ======================== L2TP Multi-Instance ========================
  1781. async function loadL2TP(populateInputs = true) {
  1782. try {
  1783. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1784. const list = await res.json();
  1785. state.l2tpList = Array.isArray(list) ? list : [];
  1786. const badge = document.getElementById('l2tp-count-badge');
  1787. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1788. const tbody = document.getElementById('l2tp-table-body');
  1789. const empty = document.getElementById('l2tp-empty');
  1790. if (!tbody) return;
  1791. tbody.innerHTML = '';
  1792. if (state.l2tpList.length === 0) {
  1793. if (empty) empty.classList.remove('hidden');
  1794. } else {
  1795. if (empty) empty.classList.add('hidden');
  1796. state.l2tpList.forEach(inst => {
  1797. const tr = document.createElement('tr');
  1798. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1799. tr.innerHTML = `
  1800. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1801. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1802. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1803. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1804. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1805. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1806. <td class="py-2.5 px-3 text-center">
  1807. <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'}">
  1808. ${inst.default_route ? 'Yes' : 'No'}
  1809. </span>
  1810. </td>
  1811. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1812. ${inst.running ? `
  1813. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1814. ` : `
  1815. <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>
  1816. `}
  1817. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1818. ${inst.disabled ? 'Enable' : 'Disable'}
  1819. </button>
  1820. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1821. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1822. </td>
  1823. `;
  1824. tbody.appendChild(tr);
  1825. });
  1826. }
  1827. } catch (err) {
  1828. console.error('Failed to load L2TP:', err);
  1829. }
  1830. }
  1831. function openAddL2TPModal() {
  1832. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1833. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1834. document.getElementById('l2tp-modal-name').readOnly = false;
  1835. document.getElementById('l2tp-modal-server').value = '';
  1836. document.getElementById('l2tp-modal-user').value = '';
  1837. document.getElementById('l2tp-modal-pass').value = '';
  1838. document.getElementById('l2tp-modal-ipsec').value = '';
  1839. document.getElementById('l2tp-modal-defroute').checked = true;
  1840. document.getElementById('l2tp-modal-disabled').checked = false;
  1841. document.getElementById('l2tp-modal').classList.remove('hidden');
  1842. }
  1843. function openEditL2TPModal(name) {
  1844. const inst = (state.l2tpList || []).find(i => i.name === name);
  1845. if (!inst) return;
  1846. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1847. document.getElementById('l2tp-modal-name').value = inst.name;
  1848. document.getElementById('l2tp-modal-name').readOnly = true;
  1849. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1850. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1851. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1852. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1853. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1854. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1855. document.getElementById('l2tp-modal').classList.remove('hidden');
  1856. }
  1857. function closeL2TPModal() {
  1858. document.getElementById('l2tp-modal').classList.add('hidden');
  1859. }
  1860. async function submitSaveL2TP(e) {
  1861. e.preventDefault();
  1862. const name = document.getElementById('l2tp-modal-name').value.trim();
  1863. const server = document.getElementById('l2tp-modal-server').value.trim();
  1864. const user = document.getElementById('l2tp-modal-user').value.trim();
  1865. const pass = document.getElementById('l2tp-modal-pass').value;
  1866. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1867. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1868. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1869. try {
  1870. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1871. method: 'POST',
  1872. headers: { 'Content-Type': 'application/json' },
  1873. body: JSON.stringify({
  1874. name,
  1875. connect_to: server,
  1876. username: user,
  1877. password: pass,
  1878. ipsec_secret: ipsec,
  1879. default_route: defRoute,
  1880. disabled
  1881. })
  1882. });
  1883. if (res.ok) {
  1884. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1885. closeL2TPModal();
  1886. loadL2TP(false);
  1887. fetchData(false);
  1888. }
  1889. } catch (err) {
  1890. showToast('Error', err.message, 'error');
  1891. }
  1892. }
  1893. async function connectL2TPInstance(name) {
  1894. try {
  1895. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1896. if (res.ok) {
  1897. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1898. setTimeout(() => loadL2TP(false), 2000);
  1899. }
  1900. } catch (err) {
  1901. showToast('Error', err.message, 'error');
  1902. }
  1903. }
  1904. async function disconnectL2TPInstance(name) {
  1905. try {
  1906. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1907. if (res.ok) {
  1908. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1909. loadL2TP(false);
  1910. }
  1911. } catch (err) {
  1912. showToast('Error', err.message, 'error');
  1913. }
  1914. }
  1915. async function toggleL2TPState(name, enable) {
  1916. try {
  1917. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1918. method: 'POST',
  1919. headers: { 'Content-Type': 'application/json' },
  1920. body: JSON.stringify({ enabled: enable })
  1921. });
  1922. if (res.ok) {
  1923. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1924. loadL2TP(false);
  1925. }
  1926. } catch (err) {
  1927. showToast('Error', err.message, 'error');
  1928. }
  1929. }
  1930. async function deleteL2TPInstance(name) {
  1931. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1932. try {
  1933. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1934. if (res.ok) {
  1935. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1936. loadL2TP(false);
  1937. fetchData(false);
  1938. }
  1939. } catch (err) {
  1940. showToast('Error', err.message, 'error');
  1941. }
  1942. }
  1943. // ======================== PPTP Multi-Instance ========================
  1944. async function loadPPTP(populateInputs = true) {
  1945. try {
  1946. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1947. const list = await res.json();
  1948. state.pptpList = Array.isArray(list) ? list : [];
  1949. const badge = document.getElementById('pptp-count-badge');
  1950. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1951. const tbody = document.getElementById('pptp-table-body');
  1952. const empty = document.getElementById('pptp-empty');
  1953. if (!tbody) return;
  1954. tbody.innerHTML = '';
  1955. if (state.pptpList.length === 0) {
  1956. if (empty) empty.classList.remove('hidden');
  1957. } else {
  1958. if (empty) empty.classList.add('hidden');
  1959. state.pptpList.forEach(inst => {
  1960. const tr = document.createElement('tr');
  1961. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1962. tr.innerHTML = `
  1963. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1964. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1965. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1966. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1967. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1968. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1969. <td class="py-2.5 px-3 text-center">
  1970. <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'}">
  1971. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1972. </span>
  1973. </td>
  1974. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1975. ${inst.running ? `
  1976. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1977. ` : `
  1978. <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>
  1979. `}
  1980. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1981. ${inst.disabled ? 'Enable' : 'Disable'}
  1982. </button>
  1983. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1984. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1985. </td>
  1986. `;
  1987. tbody.appendChild(tr);
  1988. });
  1989. }
  1990. } catch (err) {
  1991. console.error('Failed to load PPTP:', err);
  1992. }
  1993. }
  1994. function openAddPPTPModal() {
  1995. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1996. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1997. document.getElementById('pptp-modal-name').readOnly = false;
  1998. document.getElementById('pptp-modal-server').value = '';
  1999. document.getElementById('pptp-modal-user').value = '';
  2000. document.getElementById('pptp-modal-pass').value = '';
  2001. document.getElementById('pptp-modal-mppe').checked = true;
  2002. document.getElementById('pptp-modal-defroute').checked = true;
  2003. document.getElementById('pptp-modal-disabled').checked = false;
  2004. document.getElementById('pptp-modal').classList.remove('hidden');
  2005. }
  2006. function openEditPPTPModal(name) {
  2007. const inst = (state.pptpList || []).find(i => i.name === name);
  2008. if (!inst) return;
  2009. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2010. document.getElementById('pptp-modal-name').value = inst.name;
  2011. document.getElementById('pptp-modal-name').readOnly = true;
  2012. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2013. document.getElementById('pptp-modal-user').value = inst.username || '';
  2014. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2015. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2016. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2017. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2018. document.getElementById('pptp-modal').classList.remove('hidden');
  2019. }
  2020. function closePPTPModal() {
  2021. document.getElementById('pptp-modal').classList.add('hidden');
  2022. }
  2023. async function submitSavePPTP(e) {
  2024. e.preventDefault();
  2025. const name = document.getElementById('pptp-modal-name').value.trim();
  2026. const server = document.getElementById('pptp-modal-server').value.trim();
  2027. const user = document.getElementById('pptp-modal-user').value.trim();
  2028. const pass = document.getElementById('pptp-modal-pass').value;
  2029. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2030. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2031. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2034. method: 'POST',
  2035. headers: { 'Content-Type': 'application/json' },
  2036. body: JSON.stringify({
  2037. name,
  2038. connect_to: server,
  2039. username: user,
  2040. password: pass,
  2041. require_mppe: mppe,
  2042. default_route: defRoute,
  2043. auto_reconnect: true,
  2044. disabled
  2045. })
  2046. });
  2047. if (res.ok) {
  2048. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2049. closePPTPModal();
  2050. loadPPTP(false);
  2051. fetchData(false);
  2052. }
  2053. } catch (err) {
  2054. showToast('Error', err.message, 'error');
  2055. }
  2056. }
  2057. async function connectPPTPInstance(name) {
  2058. try {
  2059. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2060. if (res.ok) {
  2061. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2062. setTimeout(() => loadPPTP(false), 2000);
  2063. }
  2064. } catch (err) {
  2065. showToast('Error', err.message, 'error');
  2066. }
  2067. }
  2068. async function disconnectPPTPInstance(name) {
  2069. try {
  2070. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2071. if (res.ok) {
  2072. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2073. loadPPTP(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function togglePPTPState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadPPTP(false);
  2089. }
  2090. } catch (err) {
  2091. showToast('Error', err.message, 'error');
  2092. }
  2093. }
  2094. async function deletePPTPInstance(name) {
  2095. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2096. try {
  2097. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2098. if (res.ok) {
  2099. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2100. loadPPTP(false);
  2101. fetchData(false);
  2102. }
  2103. } catch (err) {
  2104. showToast('Error', err.message, 'error');
  2105. }
  2106. }
  2107. // ---------------- Modal & Helper Functions ----------------
  2108. function openVlanModal(defaultParent = '') {
  2109. const select = document.getElementById('vlan-parent');
  2110. select.innerHTML = '';
  2111. const allIfaces = state.interfaces || [];
  2112. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2113. if (eligible.length === 0) {
  2114. const opt = document.createElement('option');
  2115. opt.value = '';
  2116. opt.innerText = 'No VLAN-capable interfaces available';
  2117. select.appendChild(opt);
  2118. } else {
  2119. eligible.forEach(i => {
  2120. const opt = document.createElement('option');
  2121. opt.value = i.name;
  2122. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2123. if (i.name === defaultParent) opt.selected = true;
  2124. select.appendChild(opt);
  2125. });
  2126. }
  2127. document.getElementById('vlan-id').value = '';
  2128. document.getElementById('vlan-name').value = '';
  2129. document.getElementById('vlan-ip').value = '';
  2130. document.getElementById('vlan-desc').value = '';
  2131. autoSuggestVlanName();
  2132. document.getElementById('vlan-modal').classList.remove('hidden');
  2133. }
  2134. function closeVlanModal() {
  2135. document.getElementById('vlan-modal').classList.add('hidden');
  2136. }
  2137. function autoSuggestVlanName() {
  2138. const parent = document.getElementById('vlan-parent').value;
  2139. if (!parent) return;
  2140. const id = document.getElementById('vlan-id').value;
  2141. const nameInput = document.getElementById('vlan-name');
  2142. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2143. }
  2144. function setSubnetPreset(cidr) {
  2145. const ipInput = document.getElementById('vlan-ip');
  2146. const id = document.getElementById('vlan-id').value || '10';
  2147. ipInput.value = `192.168.${id}.1${cidr}`;
  2148. }
  2149. async function submitCreateVlan(e) {
  2150. e.preventDefault();
  2151. const btn = document.getElementById('vlan-submit-btn');
  2152. btn.disabled = true;
  2153. btn.innerText = 'Creating...';
  2154. const parent = document.getElementById('vlan-parent').value;
  2155. if (!parent) {
  2156. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2157. btn.disabled = false;
  2158. btn.innerText = 'Create VLAN';
  2159. return;
  2160. }
  2161. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2162. const name = document.getElementById('vlan-name').value.trim();
  2163. const ip = document.getElementById('vlan-ip').value.trim();
  2164. const role = document.getElementById('vlan-role').value;
  2165. const desc = document.getElementById('vlan-desc').value.trim();
  2166. try {
  2167. const res = await fetch(`${API_BASE}/vlans`, {
  2168. method: 'POST',
  2169. headers: { 'Content-Type': 'application/json' },
  2170. body: JSON.stringify({
  2171. parent_name: parent,
  2172. vlan_id: id,
  2173. name: name,
  2174. ip_address: ip,
  2175. role: role,
  2176. description: desc,
  2177. mtu: 1500,
  2178. auto_up: true
  2179. })
  2180. });
  2181. const data = await res.json();
  2182. if (res.ok) {
  2183. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2184. state.expandedParents.add(parent);
  2185. closeVlanModal();
  2186. await fetchData(true);
  2187. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2188. } else {
  2189. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2190. }
  2191. } catch (err) {
  2192. showToast('Error', err.message, 'error');
  2193. } finally {
  2194. btn.disabled = false;
  2195. btn.innerText = 'Create VLAN';
  2196. }
  2197. }
  2198. async function confirmDeleteVlan(name) {
  2199. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2200. try {
  2201. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2202. if (res.ok) {
  2203. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2204. closeIfaceModal();
  2205. fetchData(true);
  2206. }
  2207. } catch (err) {
  2208. showToast('Error', err.message, 'error');
  2209. }
  2210. }
  2211. function openIfaceModal(name) {
  2212. const iface = (state.interfaces || []).find(i => i.name === name);
  2213. if (!iface) return;
  2214. state.currentModalIface = iface.name;
  2215. document.getElementById('modal-iface-name').innerText = iface.name;
  2216. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2217. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2218. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2219. document.getElementById('modal-iface-desc').value = iface.description || '';
  2220. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2221. if (iface.is_vlan) {
  2222. delBtn.classList.remove('hidden');
  2223. } else {
  2224. delBtn.classList.add('hidden');
  2225. }
  2226. renderModalIPs(iface);
  2227. document.getElementById('iface-modal').classList.remove('hidden');
  2228. }
  2229. function renderModalIPs(iface) {
  2230. const container = document.getElementById('modal-ip-list');
  2231. container.innerHTML = '';
  2232. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2233. if (addrs.length === 0) {
  2234. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2235. return;
  2236. }
  2237. addrs.forEach(addr => {
  2238. const row = document.createElement('div');
  2239. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2240. row.innerHTML = `
  2241. <span class="text-white">${addr}</span>
  2242. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2243. `;
  2244. container.appendChild(row);
  2245. });
  2246. }
  2247. function closeIfaceModal() {
  2248. document.getElementById('iface-modal').classList.add('hidden');
  2249. state.currentModalIface = null;
  2250. }
  2251. async function setIfaceState(name, newState) {
  2252. await toggleInterfaceState(name, newState);
  2253. const updated = (state.interfaces || []).find(i => i.name === name);
  2254. if (updated) openIfaceModal(name);
  2255. }
  2256. async function applyMTU() {
  2257. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2258. try {
  2259. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2260. method: 'POST',
  2261. headers: { 'Content-Type': 'application/json' },
  2262. body: JSON.stringify({ mtu })
  2263. });
  2264. if (res.ok) {
  2265. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2266. fetchData(false);
  2267. }
  2268. } catch (err) {
  2269. showToast('Error', err.message, 'error');
  2270. }
  2271. }
  2272. async function addInterfaceIP() {
  2273. const ip = document.getElementById('modal-new-ip').value.trim();
  2274. if (!ip) return;
  2275. try {
  2276. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2277. method: 'POST',
  2278. headers: { 'Content-Type': 'application/json' },
  2279. body: JSON.stringify({ ip })
  2280. });
  2281. if (res.ok) {
  2282. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2283. document.getElementById('modal-new-ip').value = '';
  2284. await fetchData(false);
  2285. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2286. if (iface) renderModalIPs(iface);
  2287. } else {
  2288. const err = await res.json();
  2289. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2290. }
  2291. } catch (err) {
  2292. showToast('Error', err.message, 'error');
  2293. }
  2294. }
  2295. async function removeInterfaceIP(ip) {
  2296. if (!confirm(`Remove IP ${ip}?`)) return;
  2297. try {
  2298. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2299. method: 'DELETE',
  2300. headers: { 'Content-Type': 'application/json' },
  2301. body: JSON.stringify({ ip })
  2302. });
  2303. if (res.ok) {
  2304. showToast('IP Removed', `Removed ${ip}`, 'success');
  2305. await fetchData(false);
  2306. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2307. if (iface) renderModalIPs(iface);
  2308. }
  2309. } catch (err) {
  2310. showToast('Error', err.message, 'error');
  2311. }
  2312. }
  2313. async function saveInterfaceMetadata() {
  2314. const role = document.getElementById('modal-iface-role').value;
  2315. const desc = document.getElementById('modal-iface-desc').value.trim();
  2316. try {
  2317. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2318. method: 'POST',
  2319. headers: { 'Content-Type': 'application/json' },
  2320. body: JSON.stringify({ role, description: desc })
  2321. });
  2322. if (res.ok) {
  2323. showToast('Saved', 'Metadata updated', 'success');
  2324. closeIfaceModal();
  2325. fetchData(false);
  2326. }
  2327. } catch (err) {
  2328. showToast('Error', err.message, 'error');
  2329. }
  2330. }
  2331. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2332. state.fwSubTab = 'filter';
  2333. state.routesSubTab = 'routes';
  2334. function renderRuleFlag(disabled, hasComment) {
  2335. let flags = '';
  2336. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2337. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2338. return flags || '<span class="text-slate-600">-</span>';
  2339. }
  2340. function renderActionBadge(action) {
  2341. const act = (action || '').toLowerCase();
  2342. let color = 'bg-slate-800 text-slate-300';
  2343. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2344. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2345. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2346. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2347. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2348. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2349. }
  2350. function switchFWSubTab(tab) {
  2351. state.fwSubTab = tab;
  2352. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2353. tabs.forEach(t => {
  2354. const panel = document.getElementById(`fw-subtab-${t}`);
  2355. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2356. if (panel) {
  2357. if (t === tab) panel.classList.remove('hidden');
  2358. else panel.classList.add('hidden');
  2359. }
  2360. if (btn) {
  2361. if (t === tab) {
  2362. 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';
  2363. } else {
  2364. 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';
  2365. }
  2366. }
  2367. });
  2368. const addBtn = document.getElementById('fw-primary-add-btn');
  2369. if (addBtn) {
  2370. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2371. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2372. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2373. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2374. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2375. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2376. }
  2377. if (tab === 'geo') loadGeoIP();
  2378. if (tab === 'connections') loadConnections();
  2379. }
  2380. function openCurrentFWModal() {
  2381. if (state.fwSubTab === 'filter') openAddFilterModal();
  2382. else if (state.fwSubTab === 'nat') openAddNATModal();
  2383. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2384. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2385. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2386. else if (state.fwSubTab === 'connections') loadConnections();
  2387. }
  2388. async function loadFirewall(populateDropdowns = true) {
  2389. try {
  2390. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2391. fetch(`${API_BASE}/firewall/summary`),
  2392. fetch(`${API_BASE}/firewall/filter`),
  2393. fetch(`${API_BASE}/firewall/nat`),
  2394. fetch(`${API_BASE}/firewall/mangle`),
  2395. fetch(`${API_BASE}/firewall/address-lists`),
  2396. fetch(`${API_BASE}/firewall/geoip/status`),
  2397. fetch(`${API_BASE}/firewall/geoip/countries`)
  2398. ]);
  2399. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2400. if (filterRes.ok) state.filterRules = await filterRes.json();
  2401. if (natRes.ok) state.natRules = await natRes.json();
  2402. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2403. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2404. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2405. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2406. // Badges
  2407. const bFilter = document.getElementById('fw-badge-filter');
  2408. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2409. const bNat = document.getElementById('fw-badge-nat');
  2410. if (bNat) bNat.innerText = (state.natRules || []).length;
  2411. const bMangle = document.getElementById('fw-badge-mangle');
  2412. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2413. const bAddr = document.getElementById('fw-badge-addrlist');
  2414. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2415. const bGeo = document.getElementById('fw-badge-geo');
  2416. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2417. renderFilterRules();
  2418. renderNATRules();
  2419. renderMangleRules();
  2420. renderAddressLists();
  2421. renderGeoCountries();
  2422. if (state.fwSubTab === 'connections') {
  2423. loadConnections();
  2424. }
  2425. } catch (err) {
  2426. console.error('Failed to load firewall:', err);
  2427. }
  2428. }
  2429. // ----------------- Filter Rules -----------------
  2430. function renderFilterRules() {
  2431. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2432. const tbody = document.getElementById('filter-table-body');
  2433. const empty = document.getElementById('filter-empty');
  2434. if (!tbody) return;
  2435. tbody.innerHTML = '';
  2436. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2437. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2438. if (rules.length === 0) {
  2439. empty?.classList.remove('hidden');
  2440. return;
  2441. }
  2442. empty?.classList.add('hidden');
  2443. rules.forEach((r, idx) => {
  2444. const tr = document.createElement('tr');
  2445. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2446. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2447. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2448. tr.innerHTML = `
  2449. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2450. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2451. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2452. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2453. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2454. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2455. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2456. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2457. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2458. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2459. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2460. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2461. </td>
  2462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2463. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2464. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2465. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2466. <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>
  2467. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2468. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2469. </td>
  2470. `;
  2471. tbody.appendChild(tr);
  2472. });
  2473. }
  2474. function formatTarget(addr, list, geo) {
  2475. const parts = [];
  2476. if (addr) parts.push(`<span>${addr}</span>`);
  2477. if (list) {
  2478. const inv = list.startsWith('!') ? '!' : '';
  2479. const clean = list.replace(/^!/, '');
  2480. 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>`);
  2481. }
  2482. if (geo) {
  2483. const inv = geo.startsWith('!') ? '!' : '';
  2484. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2485. 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>`);
  2486. }
  2487. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2488. return parts.join(' ');
  2489. }
  2490. function populateInterfaceSelect(selectId, currentVal = '') {
  2491. const sel = document.getElementById(selectId);
  2492. if (!sel) return;
  2493. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2494. (state.interfaces || []).forEach(i => {
  2495. const opt = document.createElement('option');
  2496. opt.value = i.name;
  2497. opt.innerText = `${i.name} (${i.role || i.type})`;
  2498. if (i.name === currentVal) opt.selected = true;
  2499. sel.appendChild(opt);
  2500. });
  2501. }
  2502. function populateAddressListSelect(selectId, currentVal = '') {
  2503. const sel = document.getElementById(selectId);
  2504. if (!sel) return;
  2505. sel.innerHTML = '<option value="">(None)</option>';
  2506. const cleanVal = (currentVal || '').replace(/^!/, '');
  2507. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2508. customNames.forEach(name => {
  2509. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2510. const opt = document.createElement('option');
  2511. opt.value = name;
  2512. opt.innerText = `${name} (${count} entries)`;
  2513. if (name === cleanVal) opt.selected = true;
  2514. sel.appendChild(opt);
  2515. });
  2516. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2517. const opt = document.createElement('option');
  2518. opt.value = cleanVal;
  2519. opt.innerText = cleanVal;
  2520. opt.selected = true;
  2521. sel.appendChild(opt);
  2522. }
  2523. }
  2524. function populateGeoIPSelect(selectId, currentVal = '') {
  2525. const sel = document.getElementById(selectId);
  2526. if (!sel) return;
  2527. sel.innerHTML = '<option value="">(None)</option>';
  2528. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2529. // Presets optgroup
  2530. const grpPresets = document.createElement('optgroup');
  2531. grpPresets.label = '⚡ Regional Presets';
  2532. const presets = [
  2533. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2534. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2535. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2536. ];
  2537. presets.forEach(p => {
  2538. const opt = document.createElement('option');
  2539. opt.value = p.code;
  2540. opt.innerText = p.label;
  2541. if (p.code === cleanVal) opt.selected = true;
  2542. grpPresets.appendChild(opt);
  2543. });
  2544. sel.appendChild(grpPresets);
  2545. // All Countries optgroup
  2546. const grpCountries = document.createElement('optgroup');
  2547. grpCountries.label = '🌍 All Countries';
  2548. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2549. countries.forEach(c => {
  2550. const opt = document.createElement('option');
  2551. opt.value = c.code;
  2552. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2553. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2554. if (c.code === cleanVal) opt.selected = true;
  2555. grpCountries.appendChild(opt);
  2556. });
  2557. sel.appendChild(grpCountries);
  2558. }
  2559. function openAddFilterModal() {
  2560. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2561. document.getElementById('filter-modal-id').value = '';
  2562. document.getElementById('filter-modal-chain').value = 'forward';
  2563. document.getElementById('filter-modal-action').value = 'accept';
  2564. document.getElementById('filter-modal-proto').value = 'all';
  2565. document.getElementById('filter-modal-src').value = '';
  2566. document.getElementById('filter-modal-dst').value = '';
  2567. document.getElementById('filter-modal-sport').value = '';
  2568. document.getElementById('filter-modal-dport').value = '';
  2569. document.getElementById('filter-modal-connmark').value = '';
  2570. document.getElementById('filter-modal-comment').value = '';
  2571. document.getElementById('filter-modal-disabled').checked = false;
  2572. document.getElementById('filter-modal-cs-established').checked = false;
  2573. document.getElementById('filter-modal-cs-related').checked = false;
  2574. document.getElementById('filter-modal-cs-new').checked = false;
  2575. document.getElementById('filter-modal-cs-invalid').checked = false;
  2576. populateInterfaceSelect('filter-modal-iniface');
  2577. populateInterfaceSelect('filter-modal-outiface');
  2578. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2579. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2580. populateAddressListSelect('filter-modal-srclist');
  2581. populateAddressListSelect('filter-modal-dstlist');
  2582. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2583. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2584. populateGeoIPSelect('filter-modal-srcgeoip');
  2585. populateGeoIPSelect('filter-modal-dstgeoip');
  2586. toggleFilterActionFields();
  2587. document.getElementById('filter-modal').classList.remove('hidden');
  2588. }
  2589. function openEditFilterModal(id) {
  2590. const r = (state.filterRules || []).find(rule => rule.id === id);
  2591. if (!r) return;
  2592. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2593. document.getElementById('filter-modal-id').value = r.id;
  2594. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2595. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2596. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2597. document.getElementById('filter-modal-src').value = r.src_address || '';
  2598. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2599. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2600. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2601. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2602. document.getElementById('filter-modal-comment').value = r.comment || '';
  2603. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2604. const states = r.connection_state || [];
  2605. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2606. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2607. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2608. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2609. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2610. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2611. const srcInv = (r.src_address_list || '').startsWith('!');
  2612. const dstInv = (r.dst_address_list || '').startsWith('!');
  2613. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2614. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2615. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2616. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2617. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2618. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2619. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2620. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2621. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2622. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2623. toggleFilterActionFields();
  2624. document.getElementById('filter-modal').classList.remove('hidden');
  2625. }
  2626. function closeFilterModal() {
  2627. document.getElementById('filter-modal').classList.add('hidden');
  2628. }
  2629. function toggleFilterActionFields() {
  2630. const act = document.getElementById('filter-modal-action').value;
  2631. const rejectBox = document.getElementById('filter-action-reject-box');
  2632. if (rejectBox) {
  2633. if (act === 'reject') rejectBox.classList.remove('hidden');
  2634. else rejectBox.classList.add('hidden');
  2635. }
  2636. }
  2637. async function submitSaveFilterRule(e) {
  2638. e.preventDefault();
  2639. const id = document.getElementById('filter-modal-id').value;
  2640. const chain = document.getElementById('filter-modal-chain').value;
  2641. const action = document.getElementById('filter-modal-action').value;
  2642. const proto = document.getElementById('filter-modal-proto').value;
  2643. const src = document.getElementById('filter-modal-src').value.trim();
  2644. const dst = document.getElementById('filter-modal-dst').value.trim();
  2645. const sport = document.getElementById('filter-modal-sport').value.trim();
  2646. const dport = document.getElementById('filter-modal-dport').value.trim();
  2647. const inIface = document.getElementById('filter-modal-iniface').value;
  2648. const outIface = document.getElementById('filter-modal-outiface').value;
  2649. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2650. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2651. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2652. srclist = '!' + srclist.replace(/^!/, '');
  2653. }
  2654. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2655. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2656. dstlist = '!' + dstlist.replace(/^!/, '');
  2657. }
  2658. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2659. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2660. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2661. }
  2662. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2663. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2664. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2665. }
  2666. const comment = document.getElementById('filter-modal-comment').value.trim();
  2667. const disabled = document.getElementById('filter-modal-disabled').checked;
  2668. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2669. const states = [];
  2670. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2671. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2672. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2673. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2674. try {
  2675. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2676. method: 'POST',
  2677. headers: { 'Content-Type': 'application/json' },
  2678. body: JSON.stringify({
  2679. id,
  2680. chain,
  2681. action,
  2682. reject_with: rejectWith,
  2683. protocol: proto,
  2684. src_address: src,
  2685. dst_address: dst,
  2686. src_port: sport,
  2687. dst_port: dport,
  2688. in_interface: inIface,
  2689. out_interface: outIface,
  2690. connection_state: states,
  2691. connection_mark: connmark,
  2692. src_address_list: srclist,
  2693. dst_address_list: dstlist,
  2694. src_geoip: srcgeoip,
  2695. dst_geoip: dstgeoip,
  2696. comment,
  2697. disabled
  2698. })
  2699. });
  2700. if (res.ok) {
  2701. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2702. closeFilterModal();
  2703. loadFirewall(false);
  2704. } else {
  2705. const err = await res.json();
  2706. showToast('Error', err.message, 'error');
  2707. }
  2708. } catch (err) {
  2709. showToast('Error', err.message, 'error');
  2710. }
  2711. }
  2712. async function moveFilterRule(id, dir) {
  2713. try {
  2714. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2715. method: 'POST',
  2716. headers: { 'Content-Type': 'application/json' },
  2717. body: JSON.stringify({ direction: dir })
  2718. });
  2719. if (res.ok) loadFirewall(false);
  2720. } catch (err) {
  2721. showToast('Error', err.message, 'error');
  2722. }
  2723. }
  2724. async function toggleFilterRuleState(id, disabled) {
  2725. try {
  2726. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2727. method: 'POST',
  2728. headers: { 'Content-Type': 'application/json' },
  2729. body: JSON.stringify({ disabled })
  2730. });
  2731. if (res.ok) loadFirewall(false);
  2732. } catch (err) {
  2733. showToast('Error', err.message, 'error');
  2734. }
  2735. }
  2736. async function deleteFilterRule(id) {
  2737. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2738. try {
  2739. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2740. if (res.ok) {
  2741. showToast('Deleted', 'Filter rule removed', 'success');
  2742. loadFirewall(false);
  2743. }
  2744. } catch (err) {
  2745. showToast('Error', err.message, 'error');
  2746. }
  2747. }
  2748. // ----------------- NAT Rules -----------------
  2749. function renderNATRules() {
  2750. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2751. const tbody = document.getElementById('nat-table-body');
  2752. const empty = document.getElementById('nat-empty');
  2753. if (!tbody) return;
  2754. tbody.innerHTML = '';
  2755. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2756. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2757. if (rules.length === 0) {
  2758. empty?.classList.remove('hidden');
  2759. return;
  2760. }
  2761. empty?.classList.add('hidden');
  2762. rules.forEach((r, idx) => {
  2763. const tr = document.createElement('tr');
  2764. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2765. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2766. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2767. tr.innerHTML = `
  2768. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2769. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2770. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2771. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2772. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2773. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2774. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2775. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2776. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2777. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2778. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2779. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2780. </td>
  2781. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2782. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2783. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2784. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2785. <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>
  2786. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2787. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2788. </td>
  2789. `;
  2790. tbody.appendChild(tr);
  2791. });
  2792. }
  2793. function openAddNATModal() {
  2794. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2795. document.getElementById('nat-modal-id').value = '';
  2796. document.getElementById('nat-modal-chain').value = 'srcnat';
  2797. document.getElementById('nat-modal-action').value = 'masquerade';
  2798. document.getElementById('nat-modal-toaddr').value = '';
  2799. document.getElementById('nat-modal-toport').value = '';
  2800. document.getElementById('nat-modal-proto').value = 'all';
  2801. document.getElementById('nat-modal-src').value = '';
  2802. document.getElementById('nat-modal-dst').value = '';
  2803. document.getElementById('nat-modal-dport').value = '';
  2804. document.getElementById('nat-modal-comment').value = '';
  2805. document.getElementById('nat-modal-disabled').checked = false;
  2806. populateInterfaceSelect('nat-modal-iniface');
  2807. populateInterfaceSelect('nat-modal-outiface');
  2808. populateAddressListSelect('nat-modal-srclist');
  2809. populateAddressListSelect('nat-modal-dstlist');
  2810. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2811. if (srcInvEl) srcInvEl.checked = false;
  2812. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2813. if (dstInvEl) dstInvEl.checked = false;
  2814. populateGeoIPSelect('nat-modal-srcgeoip');
  2815. populateGeoIPSelect('nat-modal-dstgeoip');
  2816. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2817. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2818. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2819. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2820. toggleNATActionFields();
  2821. document.getElementById('nat-modal').classList.remove('hidden');
  2822. }
  2823. function openEditNATModal(id) {
  2824. const r = (state.natRules || []).find(rule => rule.id === id);
  2825. if (!r) return;
  2826. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2827. document.getElementById('nat-modal-id').value = r.id;
  2828. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2829. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2830. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2831. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2832. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2833. document.getElementById('nat-modal-src').value = r.src_address || '';
  2834. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2835. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2836. document.getElementById('nat-modal-comment').value = r.comment || '';
  2837. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2838. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2839. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2840. const srcInv = (r.src_address_list || '').startsWith('!');
  2841. const dstInv = (r.dst_address_list || '').startsWith('!');
  2842. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2843. if (srcInvEl) srcInvEl.checked = srcInv;
  2844. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2845. if (dstInvEl) dstInvEl.checked = dstInv;
  2846. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2847. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2848. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2849. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2850. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2851. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2852. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2853. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2854. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2855. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2856. toggleNATActionFields();
  2857. document.getElementById('nat-modal').classList.remove('hidden');
  2858. }
  2859. function closeNATModal() {
  2860. document.getElementById('nat-modal').classList.add('hidden');
  2861. }
  2862. function toggleNATChainFields() {
  2863. const ch = document.getElementById('nat-modal-chain').value;
  2864. const actSel = document.getElementById('nat-modal-action');
  2865. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2866. actSel.value = 'masquerade';
  2867. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2868. actSel.value = 'dst-nat';
  2869. }
  2870. toggleNATActionFields();
  2871. }
  2872. function toggleNATActionFields() {
  2873. const act = document.getElementById('nat-modal-action').value;
  2874. const toBox = document.getElementById('nat-action-to-box');
  2875. if (toBox) {
  2876. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2877. else toBox.classList.remove('hidden');
  2878. }
  2879. }
  2880. async function submitSaveNATRule(e) {
  2881. e.preventDefault();
  2882. const id = document.getElementById('nat-modal-id').value;
  2883. const chain = document.getElementById('nat-modal-chain').value;
  2884. const action = document.getElementById('nat-modal-action').value;
  2885. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2886. const toport = document.getElementById('nat-modal-toport').value.trim();
  2887. const proto = document.getElementById('nat-modal-proto').value;
  2888. const src = document.getElementById('nat-modal-src').value.trim();
  2889. const dst = document.getElementById('nat-modal-dst').value.trim();
  2890. const dport = document.getElementById('nat-modal-dport').value.trim();
  2891. const inIface = document.getElementById('nat-modal-iniface').value;
  2892. const outIface = document.getElementById('nat-modal-outiface').value;
  2893. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2894. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2895. srclist = '!' + srclist.replace(/^!/, '');
  2896. }
  2897. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2898. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2899. dstlist = '!' + dstlist.replace(/^!/, '');
  2900. }
  2901. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2902. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2903. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2904. }
  2905. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2906. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2907. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2908. }
  2909. const comment = document.getElementById('nat-modal-comment').value.trim();
  2910. const disabled = document.getElementById('nat-modal-disabled').checked;
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2913. method: 'POST',
  2914. headers: { 'Content-Type': 'application/json' },
  2915. body: JSON.stringify({
  2916. id,
  2917. chain,
  2918. action,
  2919. to_addresses: toaddr,
  2920. to_ports: toport,
  2921. protocol: proto,
  2922. src_address: src,
  2923. dst_address: dst,
  2924. dst_port: dport,
  2925. in_interface: inIface,
  2926. out_interface: outIface,
  2927. src_address_list: srclist,
  2928. dst_address_list: dstlist,
  2929. src_geoip: srcgeoip,
  2930. dst_geoip: dstgeoip,
  2931. comment,
  2932. disabled
  2933. })
  2934. });
  2935. if (res.ok) {
  2936. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2937. closeNATModal();
  2938. loadFirewall(false);
  2939. }
  2940. } catch (err) {
  2941. showToast('Error', err.message, 'error');
  2942. }
  2943. }
  2944. async function moveNATRule(id, dir) {
  2945. try {
  2946. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2947. method: 'POST',
  2948. headers: { 'Content-Type': 'application/json' },
  2949. body: JSON.stringify({ direction: dir })
  2950. });
  2951. if (res.ok) loadFirewall(false);
  2952. } catch (err) {
  2953. showToast('Error', err.message, 'error');
  2954. }
  2955. }
  2956. async function toggleNATRuleState(id, disabled) {
  2957. try {
  2958. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2959. method: 'POST',
  2960. headers: { 'Content-Type': 'application/json' },
  2961. body: JSON.stringify({ disabled })
  2962. });
  2963. if (res.ok) loadFirewall(false);
  2964. } catch (err) {
  2965. showToast('Error', err.message, 'error');
  2966. }
  2967. }
  2968. async function deleteNATRule(id) {
  2969. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2970. try {
  2971. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2972. if (res.ok) {
  2973. showToast('Deleted', 'NAT rule removed', 'success');
  2974. loadFirewall(false);
  2975. }
  2976. } catch (err) {
  2977. showToast('Error', err.message, 'error');
  2978. }
  2979. }
  2980. // ----------------- Mangle Rules -----------------
  2981. function renderMangleRules() {
  2982. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2983. const tbody = document.getElementById('mangle-table-body');
  2984. const empty = document.getElementById('mangle-empty');
  2985. if (!tbody) return;
  2986. tbody.innerHTML = '';
  2987. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2988. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2989. if (rules.length === 0) {
  2990. empty?.classList.remove('hidden');
  2991. return;
  2992. }
  2993. empty?.classList.add('hidden');
  2994. rules.forEach((r, idx) => {
  2995. const tr = document.createElement('tr');
  2996. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2997. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2998. tr.innerHTML = `
  2999. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3000. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3001. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3002. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3003. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3004. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3005. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  3006. <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>
  3007. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3008. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3009. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3010. </td>
  3011. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3012. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3013. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3014. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3015. <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>
  3016. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3017. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3018. </td>
  3019. `;
  3020. tbody.appendChild(tr);
  3021. });
  3022. }
  3023. function openAddMangleModal() {
  3024. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  3025. document.getElementById('mangle-modal-id').value = '';
  3026. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3027. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3028. document.getElementById('mangle-modal-newmark').value = '';
  3029. document.getElementById('mangle-modal-passthrough').checked = true;
  3030. document.getElementById('mangle-modal-src').value = '';
  3031. document.getElementById('mangle-modal-dst').value = '';
  3032. document.getElementById('mangle-modal-connmark').value = '';
  3033. document.getElementById('mangle-modal-comment').value = '';
  3034. document.getElementById('mangle-modal-disabled').checked = false;
  3035. populateInterfaceSelect('mangle-modal-iniface');
  3036. populateAddressListSelect('mangle-modal-srclist');
  3037. populateAddressListSelect('mangle-modal-dstlist');
  3038. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3039. if (srcInvEl) srcInvEl.checked = false;
  3040. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3041. if (dstInvEl) dstInvEl.checked = false;
  3042. populateGeoIPSelect('mangle-modal-srcgeoip');
  3043. populateGeoIPSelect('mangle-modal-dstgeoip');
  3044. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3045. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  3046. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3047. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  3048. document.getElementById('mangle-modal').classList.remove('hidden');
  3049. }
  3050. function openEditMangleModal(id) {
  3051. const r = (state.mangleRules || []).find(rule => rule.id === id);
  3052. if (!r) return;
  3053. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  3054. document.getElementById('mangle-modal-id').value = r.id;
  3055. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  3056. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  3057. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  3058. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  3059. document.getElementById('mangle-modal-src').value = r.src_address || '';
  3060. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  3061. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  3062. document.getElementById('mangle-modal-comment').value = r.comment || '';
  3063. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  3064. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  3065. const srcInv = (r.src_address_list || '').startsWith('!');
  3066. const dstInv = (r.dst_address_list || '').startsWith('!');
  3067. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3068. if (srcInvEl) srcInvEl.checked = srcInv;
  3069. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3070. if (dstInvEl) dstInvEl.checked = dstInv;
  3071. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  3072. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  3073. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  3074. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  3075. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3076. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  3077. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3078. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  3079. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  3080. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  3081. document.getElementById('mangle-modal').classList.remove('hidden');
  3082. }
  3083. function closeMangleModal() {
  3084. document.getElementById('mangle-modal').classList.add('hidden');
  3085. }
  3086. function toggleMangleActionFields() {
  3087. // Handled smoothly by single dynamic input
  3088. }
  3089. async function submitSaveMangleRule(e) {
  3090. e.preventDefault();
  3091. const id = document.getElementById('mangle-modal-id').value;
  3092. const chain = document.getElementById('mangle-modal-chain').value;
  3093. const action = document.getElementById('mangle-modal-action').value;
  3094. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  3095. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  3096. const src = document.getElementById('mangle-modal-src').value.trim();
  3097. const dst = document.getElementById('mangle-modal-dst').value.trim();
  3098. const inIface = document.getElementById('mangle-modal-iniface').value;
  3099. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  3100. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  3101. srclist = '!' + srclist.replace(/^!/, '');
  3102. }
  3103. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  3104. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  3105. dstlist = '!' + dstlist.replace(/^!/, '');
  3106. }
  3107. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  3108. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  3109. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  3110. }
  3111. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  3112. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  3113. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  3114. }
  3115. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  3116. const comment = document.getElementById('mangle-modal-comment').value.trim();
  3117. const disabled = document.getElementById('mangle-modal-disabled').checked;
  3118. const payload = {
  3119. id,
  3120. chain,
  3121. action,
  3122. passthrough,
  3123. src_address: src,
  3124. dst_address: dst,
  3125. in_interface: inIface,
  3126. src_address_list: srclist,
  3127. dst_address_list: dstlist,
  3128. src_geoip: srcgeoip,
  3129. dst_geoip: dstgeoip,
  3130. connection_mark: connmark,
  3131. comment,
  3132. disabled
  3133. };
  3134. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  3135. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  3136. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  3137. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  3138. try {
  3139. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  3140. method: 'POST',
  3141. headers: { 'Content-Type': 'application/json' },
  3142. body: JSON.stringify(payload)
  3143. });
  3144. if (res.ok) {
  3145. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  3146. closeMangleModal();
  3147. loadFirewall(false);
  3148. }
  3149. } catch (err) {
  3150. showToast('Error', err.message, 'error');
  3151. }
  3152. }
  3153. async function moveMangleRule(id, dir) {
  3154. try {
  3155. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  3156. method: 'POST',
  3157. headers: { 'Content-Type': 'application/json' },
  3158. body: JSON.stringify({ direction: dir })
  3159. });
  3160. if (res.ok) loadFirewall(false);
  3161. } catch (err) {
  3162. showToast('Error', err.message, 'error');
  3163. }
  3164. }
  3165. async function toggleMangleRuleState(id, disabled) {
  3166. try {
  3167. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  3168. method: 'POST',
  3169. headers: { 'Content-Type': 'application/json' },
  3170. body: JSON.stringify({ disabled })
  3171. });
  3172. if (res.ok) loadFirewall(false);
  3173. } catch (err) {
  3174. showToast('Error', err.message, 'error');
  3175. }
  3176. }
  3177. async function deleteMangleRule(id) {
  3178. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  3179. try {
  3180. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3181. if (res.ok) {
  3182. showToast('Deleted', 'Mangle rule removed', 'success');
  3183. loadFirewall(false);
  3184. }
  3185. } catch (err) {
  3186. showToast('Error', err.message, 'error');
  3187. }
  3188. }
  3189. // ----------------- Address Lists -----------------
  3190. function renderAddressLists() {
  3191. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  3192. const tbody = document.getElementById('addrlist-table-body');
  3193. const empty = document.getElementById('addrlist-empty');
  3194. if (!tbody) return;
  3195. tbody.innerHTML = '';
  3196. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  3197. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  3198. // Update filter select
  3199. const sel = document.getElementById('addrlist-filter-name');
  3200. if (sel) {
  3201. const cur = sel.value;
  3202. sel.innerHTML = '<option value="">All Lists</option>';
  3203. const set = new Set((state.addressLists || []).map(a => a.name));
  3204. set.forEach(n => {
  3205. const opt = document.createElement('option');
  3206. opt.value = n;
  3207. opt.innerText = n;
  3208. if (n === cur) opt.selected = true;
  3209. sel.appendChild(opt);
  3210. });
  3211. }
  3212. if (entries.length === 0) {
  3213. empty?.classList.remove('hidden');
  3214. return;
  3215. }
  3216. empty?.classList.add('hidden');
  3217. entries.forEach((e, idx) => {
  3218. const tr = document.createElement('tr');
  3219. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  3220. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  3221. tr.innerHTML = `
  3222. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  3223. <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>
  3224. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  3225. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  3226. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  3227. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3228. <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>
  3229. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  3230. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3231. </td>
  3232. `;
  3233. tbody.appendChild(tr);
  3234. });
  3235. }
  3236. function openAddAddrListModal() {
  3237. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  3238. document.getElementById('addrlist-modal-id').value = '';
  3239. document.getElementById('addrlist-modal-name').value = '';
  3240. document.getElementById('addrlist-modal-addr').value = '';
  3241. document.getElementById('addrlist-modal-comment').value = '';
  3242. document.getElementById('addrlist-modal-disabled').checked = false;
  3243. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3244. if (submitBtn) submitBtn.innerText = 'Add to List';
  3245. document.getElementById('addrlist-modal').classList.remove('hidden');
  3246. }
  3247. function openEditAddrListModal(id) {
  3248. const e = (state.addressLists || []).find(item => item.id === id);
  3249. if (!e) return;
  3250. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  3251. document.getElementById('addrlist-modal-id').value = e.id;
  3252. document.getElementById('addrlist-modal-name').value = e.name;
  3253. document.getElementById('addrlist-modal-addr').value = e.address;
  3254. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  3255. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  3256. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3257. if (submitBtn) submitBtn.innerText = 'Save Changes';
  3258. document.getElementById('addrlist-modal').classList.remove('hidden');
  3259. }
  3260. function closeAddrListModal() {
  3261. document.getElementById('addrlist-modal').classList.add('hidden');
  3262. }
  3263. async function submitSaveAddrList(e) {
  3264. e.preventDefault();
  3265. const id = document.getElementById('addrlist-modal-id').value;
  3266. const name = document.getElementById('addrlist-modal-name').value.trim();
  3267. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  3268. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  3269. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  3270. try {
  3271. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  3272. method: 'POST',
  3273. headers: { 'Content-Type': 'application/json' },
  3274. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  3275. });
  3276. if (res.ok) {
  3277. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  3278. closeAddrListModal();
  3279. loadFirewall(false);
  3280. } else {
  3281. const err = await res.json();
  3282. showToast('Error', err.message || 'Failed to save address list', 'error');
  3283. }
  3284. } catch (err) {
  3285. showToast('Error', err.message, 'error');
  3286. }
  3287. }
  3288. async function toggleAddrListState(id, disabled) {
  3289. try {
  3290. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  3291. method: 'POST',
  3292. headers: { 'Content-Type': 'application/json' },
  3293. body: JSON.stringify({ disabled })
  3294. });
  3295. if (res.ok) {
  3296. loadFirewall(false);
  3297. }
  3298. } catch (err) {
  3299. showToast('Error', err.message, 'error');
  3300. }
  3301. }
  3302. async function deleteAddrList(id) {
  3303. if (!confirm('Are you sure you want to delete this address list item?')) return;
  3304. try {
  3305. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3306. if (res.ok) {
  3307. showToast('Deleted', 'Address list item removed', 'info');
  3308. loadFirewall(false);
  3309. }
  3310. } catch (err) {
  3311. showToast('Error', err.message, 'error');
  3312. }
  3313. }
  3314. // ----------------- Geo-Location IP Management -----------------
  3315. async function loadGeoIP() {
  3316. try {
  3317. const [statusRes, countriesRes] = await Promise.all([
  3318. fetch(`${API_BASE}/firewall/geoip/status`),
  3319. fetch(`${API_BASE}/firewall/geoip/countries`)
  3320. ]);
  3321. if (statusRes.ok) state.geoStatus = await statusRes.json();
  3322. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  3323. updateGeoHeader();
  3324. renderGeoCountries();
  3325. } catch (err) {
  3326. console.error('Failed to load GeoIP:', err);
  3327. }
  3328. }
  3329. function getGeoUsageMap() {
  3330. const usage = {};
  3331. const checkRule = (r, type) => {
  3332. ['src_geoip', 'dst_geoip'].forEach(field => {
  3333. let val = (r && r[field]) || '';
  3334. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  3335. if (code) {
  3336. if (!usage[code]) usage[code] = [];
  3337. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  3338. if (!usage[code].includes(label)) usage[code].push(label);
  3339. }
  3340. });
  3341. };
  3342. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  3343. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  3344. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  3345. return usage;
  3346. }
  3347. function updateGeoHeader() {
  3348. const s = state.geoStatus || {};
  3349. const statusBadge = document.getElementById('geo-status-badge');
  3350. if (statusBadge) {
  3351. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  3352. statusBadge.className = s.auto_update
  3353. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  3354. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  3355. }
  3356. const intervalLabel = document.getElementById('geo-interval-label');
  3357. if (intervalLabel) {
  3358. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3359. }
  3360. const usageMap = getGeoUsageMap();
  3361. const inUseCount = Object.keys(usageMap).length;
  3362. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3363. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3364. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3365. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3366. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3367. if (lastSyncEl) {
  3368. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3369. const d = new Date(s.last_updated);
  3370. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3371. } else {
  3372. lastSyncEl.innerText = 'Never (Sync Pending)';
  3373. }
  3374. }
  3375. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3376. if (nextSyncEl) {
  3377. if (s.next_update && !s.next_update.startsWith('0001')) {
  3378. const d = new Date(s.next_update);
  3379. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3380. } else {
  3381. nextSyncEl.innerText = '-';
  3382. }
  3383. }
  3384. const badge = document.getElementById('fw-badge-geo');
  3385. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3386. }
  3387. function renderGeoCountries() {
  3388. const tbody = document.getElementById('geo-table-body');
  3389. const empty = document.getElementById('geo-empty');
  3390. if (!tbody) return;
  3391. tbody.innerHTML = '';
  3392. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3393. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3394. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3395. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3396. const usageMap = getGeoUsageMap();
  3397. const countries = (state.geoCountries || []).filter(c => {
  3398. const isUsed = !!usageMap[c.code];
  3399. if (inUseOnly && !isUsed) return false;
  3400. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3401. if (continent && c.continent !== continent) return false;
  3402. if (q) {
  3403. const matchCode = c.code.toLowerCase().includes(q);
  3404. const matchName = c.name.toLowerCase().includes(q);
  3405. if (!matchCode && !matchName) return false;
  3406. }
  3407. return true;
  3408. });
  3409. if (countries.length === 0) {
  3410. empty?.classList.remove('hidden');
  3411. return;
  3412. }
  3413. empty?.classList.add('hidden');
  3414. countries.forEach(c => {
  3415. const tr = document.createElement('tr');
  3416. const isUsed = !!usageMap[c.code];
  3417. const rulesUsing = usageMap[c.code] || [];
  3418. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3419. let statusHtml = '';
  3420. if (isUsed) {
  3421. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  3422. } else if (c.subnet_count > 0) {
  3423. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  3424. } else {
  3425. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3426. }
  3427. tr.innerHTML = `
  3428. <td class="py-2.5 px-3 text-center">
  3429. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  3430. ${c.code}
  3431. </span>
  3432. </td>
  3433. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3434. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3435. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3436. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3437. </td>
  3438. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3439. <td class="py-2.5 px-3">
  3440. ${statusHtml}
  3441. </td>
  3442. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3443. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  3444. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3445. </td>
  3446. `;
  3447. tbody.appendChild(tr);
  3448. });
  3449. }
  3450. function quickFilterGeo(preset) {
  3451. const searchInput = document.getElementById('geo-search-input');
  3452. const continentSel = document.getElementById('geo-continent-filter');
  3453. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3454. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3455. if (searchInput) searchInput.value = '';
  3456. if (continentSel) continentSel.value = '';
  3457. if (inUseCheck) inUseCheck.checked = false;
  3458. if (cachedCheck) cachedCheck.checked = false;
  3459. if (preset === 'GR') {
  3460. if (searchInput) searchInput.value = 'Greece';
  3461. } else if (preset === 'Europe') {
  3462. if (continentSel) continentSel.value = 'Europe';
  3463. } else if (preset === 'HIGHRISK') {
  3464. if (searchInput) searchInput.value = 'China';
  3465. }
  3466. renderGeoCountries();
  3467. }
  3468. async function toggleGeoCountry(code, enabled) {
  3469. try {
  3470. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3471. method: 'POST',
  3472. headers: { 'Content-Type': 'application/json' },
  3473. body: JSON.stringify({ enabled })
  3474. });
  3475. if (res.ok) {
  3476. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3477. loadGeoIP();
  3478. } else {
  3479. const err = await res.json();
  3480. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3481. }
  3482. } catch (err) {
  3483. showToast('Error', err.message, 'error');
  3484. }
  3485. }
  3486. async function updateGeoCountry(code) {
  3487. try {
  3488. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3489. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3490. if (res.ok) {
  3491. const data = await res.json();
  3492. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3493. loadGeoIP();
  3494. } else {
  3495. const err = await res.json();
  3496. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3497. }
  3498. } catch (err) {
  3499. showToast('Error', err.message, 'error');
  3500. }
  3501. }
  3502. async function triggerGeoUpdateNow() {
  3503. const spinner = document.getElementById('geo-update-spinner');
  3504. if (spinner) spinner.classList.remove('hidden');
  3505. try {
  3506. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3507. if (res.ok) {
  3508. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3509. setTimeout(() => {
  3510. loadGeoIP();
  3511. if (spinner) spinner.classList.add('hidden');
  3512. }, 2500);
  3513. } else {
  3514. const err = await res.json();
  3515. showToast('Notice', err.message || 'Update in progress', 'info');
  3516. if (spinner) spinner.classList.add('hidden');
  3517. }
  3518. } catch (err) {
  3519. showToast('Error', err.message, 'error');
  3520. if (spinner) spinner.classList.add('hidden');
  3521. }
  3522. }
  3523. async function applyGeoPreset(preset) {
  3524. try {
  3525. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3526. method: 'POST',
  3527. headers: { 'Content-Type': 'application/json' },
  3528. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3529. });
  3530. if (res.ok) {
  3531. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3532. loadGeoIP();
  3533. }
  3534. } catch (err) {
  3535. showToast('Error', err.message, 'error');
  3536. }
  3537. }
  3538. function openGeoIntervalModal() {
  3539. const s = state.geoStatus || {};
  3540. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3541. const sel = document.getElementById('geo-cfg-interval');
  3542. const customBox = document.getElementById('geo-cfg-custom-box');
  3543. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3544. const curHours = s.interval_hours || 24;
  3545. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3546. if (matchOption) {
  3547. sel.value = String(curHours);
  3548. customBox.classList.add('hidden');
  3549. } else {
  3550. sel.value = 'custom';
  3551. customHoursInput.value = curHours;
  3552. customBox.classList.remove('hidden');
  3553. }
  3554. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3555. }
  3556. function closeGeoIntervalModal() {
  3557. document.getElementById('geo-interval-modal').classList.add('hidden');
  3558. }
  3559. function toggleCustomGeoInterval() {
  3560. const val = document.getElementById('geo-cfg-interval').value;
  3561. const customBox = document.getElementById('geo-cfg-custom-box');
  3562. if (val === 'custom') {
  3563. customBox.classList.remove('hidden');
  3564. } else {
  3565. customBox.classList.add('hidden');
  3566. }
  3567. }
  3568. async function submitGeoIntervalSettings(e) {
  3569. e.preventDefault();
  3570. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3571. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3572. let hours = 24;
  3573. if (intervalVal === 'custom') {
  3574. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3575. } else {
  3576. hours = parseInt(intervalVal, 10) || 24;
  3577. }
  3578. try {
  3579. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3580. method: 'POST',
  3581. headers: { 'Content-Type': 'application/json' },
  3582. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3583. });
  3584. if (res.ok) {
  3585. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3586. closeGeoIntervalModal();
  3587. loadGeoIP();
  3588. } else {
  3589. const err = await res.json();
  3590. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3591. }
  3592. } catch (err) {
  3593. showToast('Error', err.message, 'error');
  3594. }
  3595. }
  3596. async function viewGeoSubnets(code, name) {
  3597. if (!name) {
  3598. const found = (state.geoCountries || []).find(x => x.code === code);
  3599. name = found ? found.name : code;
  3600. }
  3601. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3602. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3603. const listEl = document.getElementById('geo-subnets-list');
  3604. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3605. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3606. try {
  3607. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3608. if (res.ok) {
  3609. const data = await res.json();
  3610. const subnets = data.subnets || [];
  3611. if (subnets.length === 0) {
  3612. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3613. } else {
  3614. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3615. }
  3616. } else {
  3617. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3618. }
  3619. } catch (err) {
  3620. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3621. }
  3622. }
  3623. function closeGeoSubnetsModal() {
  3624. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3625. }
  3626. // ----------------- Active Connections Tracking -----------------
  3627. async function loadConnections() {
  3628. try {
  3629. const res = await fetch(`${API_BASE}/firewall/connections`);
  3630. const data = await res.json();
  3631. state.connections = Array.isArray(data) ? data : [];
  3632. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3633. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3634. renderConnections();
  3635. } catch (err) {
  3636. console.error('Failed to load connections:', err);
  3637. }
  3638. }
  3639. function renderConnections() {
  3640. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3641. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3642. const tbody = document.getElementById('conns-table-body');
  3643. const empty = document.getElementById('conns-empty');
  3644. if (!tbody) return;
  3645. tbody.innerHTML = '';
  3646. const conns = (state.connections || []).filter(c => {
  3647. if (protoFilter && c.protocol !== protoFilter) return false;
  3648. if (search) {
  3649. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3650. if (!line.includes(search)) return false;
  3651. }
  3652. return true;
  3653. });
  3654. if (conns.length === 0) {
  3655. empty?.classList.remove('hidden');
  3656. return;
  3657. }
  3658. empty?.classList.add('hidden');
  3659. conns.slice(0, 150).forEach(c => {
  3660. const tr = document.createElement('tr');
  3661. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3662. let stateColor = 'text-slate-400';
  3663. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3664. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3665. tr.innerHTML = `
  3666. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3667. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3668. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3669. <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>
  3670. <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>
  3671. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3672. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3673. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3674. <td class="py-2.5 px-3 text-right font-sans">
  3675. <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>
  3676. </td>
  3677. `;
  3678. tbody.appendChild(tr);
  3679. });
  3680. }
  3681. async function killConnection(protocol, src, sport, dst, dport) {
  3682. try {
  3683. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3684. method: 'POST',
  3685. headers: { 'Content-Type': 'application/json' },
  3686. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3687. });
  3688. if (res.ok) {
  3689. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3690. loadConnections();
  3691. }
  3692. } catch (err) {
  3693. showToast('Error', err.message, 'error');
  3694. }
  3695. }
  3696. async function resetFirewallCounters() {
  3697. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3698. try {
  3699. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3700. if (res.ok) {
  3701. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3702. loadFirewall(false);
  3703. }
  3704. } catch (err) {
  3705. showToast('Error', err.message, 'error');
  3706. }
  3707. }
  3708. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3709. function switchRoutesSubTab(tab) {
  3710. state.routesSubTab = tab;
  3711. const tabs = ['routes', 'rules', 'tables'];
  3712. tabs.forEach(t => {
  3713. const panel = document.getElementById(`routes-subtab-${t}`);
  3714. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3715. if (panel) {
  3716. if (t === tab) panel.classList.remove('hidden');
  3717. else panel.classList.add('hidden');
  3718. }
  3719. if (btn) {
  3720. if (t === tab) {
  3721. 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';
  3722. } else {
  3723. 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';
  3724. }
  3725. }
  3726. });
  3727. }
  3728. async function loadRoutes() {
  3729. try {
  3730. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3731. fetch(`${API_BASE}/routes`),
  3732. fetch(`${API_BASE}/routing/rules`),
  3733. fetch(`${API_BASE}/routing/tables`)
  3734. ]);
  3735. if (routesRes.ok) state.routes = await routesRes.json();
  3736. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3737. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3738. const bRoutes = document.getElementById('routes-badge-routes');
  3739. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3740. const bRules = document.getElementById('routes-badge-rules');
  3741. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3742. const bTables = document.getElementById('routes-badge-tables');
  3743. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3744. const bRoutesCount = document.getElementById('badge-routes-count');
  3745. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3746. renderRoutesList();
  3747. renderPolicyRules();
  3748. renderRoutingTables();
  3749. } catch (err) {
  3750. console.error('Failed to load routing:', err);
  3751. }
  3752. }
  3753. function renderRoutesList() {
  3754. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3755. const tbody = document.getElementById('routes-table-body');
  3756. const empty = document.getElementById('routes-empty');
  3757. if (!tbody) return;
  3758. tbody.innerHTML = '';
  3759. // Update table filter select
  3760. const sel = document.getElementById('routes-filter-table');
  3761. if (sel) {
  3762. const cur = sel.value;
  3763. sel.innerHTML = '<option value="">All Tables</option>';
  3764. (state.routingTables || []).forEach(t => {
  3765. const opt = document.createElement('option');
  3766. opt.value = t.name;
  3767. opt.innerText = t.name;
  3768. if (t.name === cur) opt.selected = true;
  3769. sel.appendChild(opt);
  3770. });
  3771. }
  3772. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3773. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3774. if (routes.length === 0) {
  3775. empty?.classList.remove('hidden');
  3776. return;
  3777. }
  3778. empty?.classList.add('hidden');
  3779. routes.forEach(r => {
  3780. const tr = document.createElement('tr');
  3781. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3782. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3783. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3784. let flags = '';
  3785. if (r.dynamic) flags += 'D';
  3786. if (r.active) flags += 'A';
  3787. if (r.connect) flags += 'C';
  3788. if (r.static) flags += 'S';
  3789. if (r.disabled) flags += 'X';
  3790. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3791. tr.innerHTML = `
  3792. <td class="py-2.5 px-3 text-center">
  3793. <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'}">
  3794. ${flags || '-'}
  3795. </span>
  3796. </td>
  3797. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3798. <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>
  3799. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3800. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3801. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3802. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3803. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3804. ${r.static ? `
  3805. <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>
  3806. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3807. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3808. ` : `
  3809. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3810. `}
  3811. </td>
  3812. `;
  3813. tbody.appendChild(tr);
  3814. });
  3815. }
  3816. function openAddRouteModal() {
  3817. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3818. document.getElementById('route-modal-id').value = '';
  3819. document.getElementById('route-modal-old-dst').value = '';
  3820. document.getElementById('route-modal-old-gw').value = '';
  3821. document.getElementById('route-modal-old-distance').value = '';
  3822. document.getElementById('route-modal-old-table').value = '';
  3823. document.getElementById('route-modal-old-iface').value = '';
  3824. const dstInput = document.getElementById('route-modal-dst');
  3825. const gwInput = document.getElementById('route-modal-gw');
  3826. const distInput = document.getElementById('route-modal-distance');
  3827. const ifaceSelect = document.getElementById('route-modal-iface');
  3828. const tableSelect = document.getElementById('route-modal-table');
  3829. const commentInput = document.getElementById('route-modal-comment');
  3830. const disCheck = document.getElementById('route-modal-disabled');
  3831. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3832. dstInput.disabled = false;
  3833. dstInput.value = '0.0.0.0/0';
  3834. gwInput.disabled = false;
  3835. gwInput.value = '';
  3836. distInput.disabled = false;
  3837. distInput.value = '1';
  3838. ifaceSelect.disabled = false;
  3839. tableSelect.disabled = false;
  3840. commentInput.disabled = false;
  3841. commentInput.value = '';
  3842. disCheck.disabled = false;
  3843. disCheck.checked = false;
  3844. if (saveBtn) saveBtn.classList.remove('hidden');
  3845. populateInterfaceSelect('route-modal-iface');
  3846. // Populate tables
  3847. tableSelect.innerHTML = '';
  3848. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3849. const opt = document.createElement('option');
  3850. opt.value = t.name;
  3851. opt.innerText = t.name;
  3852. if (t.name === 'main') opt.selected = true;
  3853. tableSelect.appendChild(opt);
  3854. });
  3855. document.getElementById('route-modal').classList.remove('hidden');
  3856. }
  3857. function openEditRouteModal(id) {
  3858. const r = (state.routes || []).find(route => route.id === id);
  3859. if (!r) return;
  3860. const isStatic = !!r.static;
  3861. document.getElementById('route-modal-title').innerText = isStatic
  3862. ? `Edit Route: ${r.dst_address}`
  3863. : `Route Properties (Read Only): ${r.dst_address}`;
  3864. document.getElementById('route-modal-id').value = r.id;
  3865. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3866. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3867. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3868. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3869. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3870. const dstInput = document.getElementById('route-modal-dst');
  3871. const gwInput = document.getElementById('route-modal-gw');
  3872. const distInput = document.getElementById('route-modal-distance');
  3873. const ifaceSelect = document.getElementById('route-modal-iface');
  3874. const tableSelect = document.getElementById('route-modal-table');
  3875. const commentInput = document.getElementById('route-modal-comment');
  3876. const disCheck = document.getElementById('route-modal-disabled');
  3877. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3878. dstInput.value = r.dst_address;
  3879. gwInput.value = r.gateway || '';
  3880. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3881. commentInput.value = r.comment || '';
  3882. disCheck.checked = !!r.disabled;
  3883. dstInput.disabled = !isStatic;
  3884. gwInput.disabled = !isStatic;
  3885. distInput.disabled = !isStatic;
  3886. ifaceSelect.disabled = !isStatic;
  3887. tableSelect.disabled = !isStatic;
  3888. commentInput.disabled = !isStatic;
  3889. disCheck.disabled = !isStatic;
  3890. if (saveBtn) {
  3891. if (isStatic) {
  3892. saveBtn.classList.remove('hidden');
  3893. } else {
  3894. saveBtn.classList.add('hidden');
  3895. }
  3896. }
  3897. populateInterfaceSelect('route-modal-iface', r.interface);
  3898. tableSelect.innerHTML = '';
  3899. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3900. const opt = document.createElement('option');
  3901. opt.value = t.name;
  3902. opt.innerText = t.name;
  3903. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3904. tableSelect.appendChild(opt);
  3905. });
  3906. document.getElementById('route-modal').classList.remove('hidden');
  3907. }
  3908. function closeRouteModal() {
  3909. document.getElementById('route-modal').classList.add('hidden');
  3910. }
  3911. async function submitSaveRoute(e) {
  3912. e.preventDefault();
  3913. const id = document.getElementById('route-modal-id').value;
  3914. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3915. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3916. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3917. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3918. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3919. const dst = document.getElementById('route-modal-dst').value.trim();
  3920. const gw = document.getElementById('route-modal-gw').value.trim();
  3921. const table = document.getElementById('route-modal-table').value;
  3922. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3923. const iface = document.getElementById('route-modal-iface').value;
  3924. const comment = document.getElementById('route-modal-comment').value.trim();
  3925. const disabled = document.getElementById('route-modal-disabled').checked;
  3926. if (!dst) {
  3927. showToast('Error', 'Destination address is required', 'error');
  3928. return;
  3929. }
  3930. if (!gw && !iface) {
  3931. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3932. return;
  3933. }
  3934. const payload = {
  3935. id,
  3936. old_dst_address: oldDst,
  3937. old_gateway: oldGw,
  3938. old_routing_table: oldTable,
  3939. old_interface: oldIface,
  3940. dst_address: dst,
  3941. gateway: gw || iface,
  3942. routing_table: table,
  3943. distance,
  3944. interface: iface,
  3945. comment,
  3946. disabled
  3947. };
  3948. if (oldDistStr !== undefined && oldDistStr !== '') {
  3949. payload.old_distance = parseInt(oldDistStr, 10);
  3950. }
  3951. try {
  3952. const res = await fetch(`${API_BASE}/routes`, {
  3953. method: 'POST',
  3954. headers: { 'Content-Type': 'application/json' },
  3955. body: JSON.stringify(payload)
  3956. });
  3957. if (res.ok) {
  3958. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3959. closeRouteModal();
  3960. loadRoutes();
  3961. } else {
  3962. const err = await res.json();
  3963. showToast('Error', err.message || 'Failed to save route', 'error');
  3964. }
  3965. } catch (err) {
  3966. showToast('Error', err.message, 'error');
  3967. }
  3968. }
  3969. async function toggleRouteState(id, disabled) {
  3970. try {
  3971. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3972. method: 'POST',
  3973. headers: { 'Content-Type': 'application/json' },
  3974. body: JSON.stringify({ disabled })
  3975. });
  3976. if (res.ok) loadRoutes();
  3977. } catch (err) {
  3978. showToast('Error', err.message, 'error');
  3979. }
  3980. }
  3981. async function deleteRoute(id) {
  3982. if (!confirm('Are you sure you want to delete this route?')) return;
  3983. try {
  3984. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3985. if (res.ok) {
  3986. showToast('Deleted', 'Route removed', 'success');
  3987. loadRoutes();
  3988. }
  3989. } catch (err) {
  3990. showToast('Error', err.message, 'error');
  3991. }
  3992. }
  3993. // ----------------- Policy Rules (/ip route rule) -----------------
  3994. function renderPolicyRules() {
  3995. const tbody = document.getElementById('rules-table-body');
  3996. const empty = document.getElementById('rules-empty');
  3997. if (!tbody) return;
  3998. tbody.innerHTML = '';
  3999. const rules = state.policyRules || [];
  4000. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  4001. if (rules.length === 0) {
  4002. empty?.classList.remove('hidden');
  4003. return;
  4004. }
  4005. empty?.classList.add('hidden');
  4006. rules.forEach(pr => {
  4007. const tr = document.createElement('tr');
  4008. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4009. tr.innerHTML = `
  4010. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  4011. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  4012. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  4013. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  4014. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  4015. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  4016. <td class="py-2.5 px-3 text-right font-sans">
  4017. ${pr.priority < 32766 && pr.priority > 0 ? `
  4018. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4019. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  4020. </td>
  4021. `;
  4022. tbody.appendChild(tr);
  4023. });
  4024. }
  4025. function openAddPolicyRuleModal() {
  4026. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  4027. document.getElementById('prule-modal-mark').value = '';
  4028. document.getElementById('prule-modal-src').value = '';
  4029. document.getElementById('prule-modal-dst').value = '';
  4030. const sel = document.getElementById('prule-modal-table');
  4031. sel.innerHTML = '';
  4032. (state.routingTables || []).forEach(t => {
  4033. const opt = document.createElement('option');
  4034. opt.value = t.name;
  4035. opt.innerText = t.name;
  4036. sel.appendChild(opt);
  4037. });
  4038. document.getElementById('prule-modal').classList.remove('hidden');
  4039. }
  4040. function closePolicyRuleModal() {
  4041. document.getElementById('prule-modal').classList.add('hidden');
  4042. }
  4043. async function submitSavePolicyRule(e) {
  4044. e.preventDefault();
  4045. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  4046. const mark = document.getElementById('prule-modal-mark').value.trim();
  4047. const src = document.getElementById('prule-modal-src').value.trim();
  4048. const dst = document.getElementById('prule-modal-dst').value.trim();
  4049. const table = document.getElementById('prule-modal-table').value;
  4050. const action = document.getElementById('prule-modal-action').value;
  4051. try {
  4052. const res = await fetch(`${API_BASE}/routing/rules`, {
  4053. method: 'POST',
  4054. headers: { 'Content-Type': 'application/json' },
  4055. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  4056. });
  4057. if (res.ok) {
  4058. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  4059. closePolicyRuleModal();
  4060. loadRoutes();
  4061. } else {
  4062. const err = await res.json();
  4063. showToast('Error', err.message, 'error');
  4064. }
  4065. } catch (err) {
  4066. showToast('Error', err.message, 'error');
  4067. }
  4068. }
  4069. async function deletePolicyRule(id) {
  4070. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  4071. try {
  4072. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4073. if (res.ok) {
  4074. showToast('Rule Removed', 'Policy rule deleted', 'success');
  4075. loadRoutes();
  4076. }
  4077. } catch (err) {
  4078. showToast('Error', err.message, 'error');
  4079. }
  4080. }
  4081. // ----------------- Routing Tables -----------------
  4082. function renderRoutingTables() {
  4083. const tbody = document.getElementById('tables-table-body');
  4084. if (!tbody) return;
  4085. tbody.innerHTML = '';
  4086. (state.routingTables || []).forEach(t => {
  4087. const tr = document.createElement('tr');
  4088. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4089. tr.innerHTML = `
  4090. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  4091. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  4092. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  4093. `;
  4094. tbody.appendChild(tr);
  4095. });
  4096. }
  4097. function openAddTableModal() {
  4098. document.getElementById('table-modal-name').value = '';
  4099. document.getElementById('table-modal-id').value = '';
  4100. document.getElementById('table-modal-comment').value = '';
  4101. document.getElementById('table-modal').classList.remove('hidden');
  4102. }
  4103. function closeTableModal() {
  4104. document.getElementById('table-modal').classList.add('hidden');
  4105. }
  4106. async function submitSaveTable(e) {
  4107. e.preventDefault();
  4108. const name = document.getElementById('table-modal-name').value.trim();
  4109. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  4110. const comment = document.getElementById('table-modal-comment').value.trim();
  4111. try {
  4112. const res = await fetch(`${API_BASE}/routing/tables`, {
  4113. method: 'POST',
  4114. headers: { 'Content-Type': 'application/json' },
  4115. body: JSON.stringify({ name, table_id: id, comment })
  4116. });
  4117. if (res.ok) {
  4118. showToast('Table Created', `Routing table ${name} registered`, 'success');
  4119. closeTableModal();
  4120. loadRoutes();
  4121. } else {
  4122. const err = await res.json();
  4123. showToast('Error', err.message, 'error');
  4124. }
  4125. } catch (err) {
  4126. showToast('Error', err.message, 'error');
  4127. }
  4128. }
  4129. async function loadDebianConfig() {
  4130. const view = document.getElementById('debian-config-view');
  4131. view.innerText = 'Generating live configuration...';
  4132. try {
  4133. const res = await fetch(`${API_BASE}/debian/config`);
  4134. const data = await res.json();
  4135. view.innerText = data.content || '# Empty config';
  4136. } catch (err) {
  4137. view.innerText = 'Failed to generate Debian network config.';
  4138. }
  4139. }
  4140. async function saveDebianConfig() {
  4141. try {
  4142. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  4143. const data = await res.json();
  4144. if (res.ok) {
  4145. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  4146. loadDebianConfig();
  4147. }
  4148. } catch (err) {
  4149. showToast('Error', err.message, 'error');
  4150. }
  4151. }
  4152. function showToast(title, message, type = 'info') {
  4153. const container = document.getElementById('toast-container');
  4154. const toast = document.createElement('div');
  4155. const borderColors = {
  4156. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  4157. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  4158. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  4159. };
  4160. 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}`;
  4161. toast.innerHTML = `
  4162. <div class="flex-1">
  4163. <div class="font-bold text-xs text-white">${title}</div>
  4164. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  4165. </div>
  4166. `;
  4167. container.appendChild(toast);
  4168. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  4169. setTimeout(() => {
  4170. toast.classList.add('opacity-0', 'translate-y-2');
  4171. setTimeout(() => toast.remove(), 300);
  4172. }, 4000);
  4173. }
  4174. function formatTraffic(bytesPerSec) {
  4175. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  4176. const kb = bytesPerSec / 1024;
  4177. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  4178. const mb = kb / 1024;
  4179. return `${mb.toFixed(2)} MB/s`;
  4180. }
  4181. function toggleSidebar() {
  4182. const sb = document.getElementById('sidebar');
  4183. sb.classList.toggle('-translate-x-full');
  4184. }
  4185. // ======================== EoIP (Ethernet over IP) ========================
  4186. async function loadEoIP(populate = true) {
  4187. try {
  4188. const res = await fetch(`${API_BASE}/vpn/eoip`);
  4189. const data = await res.json();
  4190. state.eoipTunnels = Array.isArray(data) ? data : [];
  4191. const badge = document.getElementById('eoip-count-badge');
  4192. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  4193. const sideBadge = document.getElementById('badge-eoip-count');
  4194. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  4195. renderEoIPTunnels();
  4196. } catch (err) {
  4197. console.error('Failed to load EoIP:', err);
  4198. }
  4199. }
  4200. function renderEoIPTunnels() {
  4201. const tbody = document.getElementById('eoip-table-body');
  4202. const empty = document.getElementById('eoip-empty');
  4203. if (!tbody) return;
  4204. tbody.innerHTML = '';
  4205. const tunnels = state.eoipTunnels || [];
  4206. if (tunnels.length === 0) {
  4207. empty?.classList.remove('hidden');
  4208. return;
  4209. }
  4210. empty?.classList.add('hidden');
  4211. tunnels.forEach(t => {
  4212. const tr = document.createElement('tr');
  4213. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  4214. tr.innerHTML = `
  4215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  4216. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  4217. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  4218. <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>
  4219. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  4220. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  4221. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  4222. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  4223. <td class="py-2.5 px-3 font-mono text-[11px]">
  4224. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  4225. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  4226. </td>
  4227. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  4228. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4229. <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>
  4230. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4231. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4232. </td>
  4233. `;
  4234. tbody.appendChild(tr);
  4235. });
  4236. }
  4237. function openAddEoIPModal() {
  4238. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  4239. document.getElementById('eoip-modal-id').value = '';
  4240. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  4241. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  4242. document.getElementById('eoip-modal-remote').value = '';
  4243. document.getElementById('eoip-modal-ip').value = '';
  4244. document.getElementById('eoip-modal-local').value = '';
  4245. document.getElementById('eoip-modal-mac').value = '';
  4246. document.getElementById('eoip-modal-mtu').value = '1500';
  4247. document.getElementById('eoip-modal-comment').value = '';
  4248. document.getElementById('eoip-modal-clampmss').checked = true;
  4249. document.getElementById('eoip-modal-disabled').checked = false;
  4250. document.getElementById('eoip-modal').classList.remove('hidden');
  4251. }
  4252. function openEditEoIPModal(id) {
  4253. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  4254. if (!t) return;
  4255. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  4256. document.getElementById('eoip-modal-id').value = t.id;
  4257. document.getElementById('eoip-modal-name').value = t.name;
  4258. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  4259. document.getElementById('eoip-modal-remote').value = t.remote_address;
  4260. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  4261. document.getElementById('eoip-modal-local').value = t.local_address || '';
  4262. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  4263. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  4264. document.getElementById('eoip-modal-comment').value = t.comment || '';
  4265. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  4266. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  4267. document.getElementById('eoip-modal').classList.remove('hidden');
  4268. }
  4269. function closeEoIPModal() {
  4270. document.getElementById('eoip-modal').classList.add('hidden');
  4271. }
  4272. async function submitSaveEoIP(e) {
  4273. e.preventDefault();
  4274. const id = document.getElementById('eoip-modal-id').value;
  4275. const name = document.getElementById('eoip-modal-name').value.trim();
  4276. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  4277. const remote = document.getElementById('eoip-modal-remote').value.trim();
  4278. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  4279. const local = document.getElementById('eoip-modal-local').value.trim();
  4280. const mac = document.getElementById('eoip-modal-mac').value.trim();
  4281. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  4282. const comment = document.getElementById('eoip-modal-comment').value.trim();
  4283. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  4284. const disabled = document.getElementById('eoip-modal-disabled').checked;
  4285. try {
  4286. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  4287. method: 'POST',
  4288. headers: { 'Content-Type': 'application/json' },
  4289. body: JSON.stringify({
  4290. id,
  4291. name,
  4292. tunnel_id: tunnelId,
  4293. remote_address: remote,
  4294. ip_address: ipAddress,
  4295. local_address: local,
  4296. mac_address: mac,
  4297. mtu,
  4298. clamp_mss: clampMss,
  4299. comment,
  4300. disabled
  4301. })
  4302. });
  4303. if (res.ok) {
  4304. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  4305. closeEoIPModal();
  4306. loadEoIP(false);
  4307. fetchData(false);
  4308. } else {
  4309. const err = await res.json();
  4310. showToast('Error', err.message, 'error');
  4311. }
  4312. } catch (err) {
  4313. showToast('Error', err.message, 'error');
  4314. }
  4315. }
  4316. async function toggleEoIPState(id, disabled) {
  4317. try {
  4318. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  4319. method: 'POST',
  4320. headers: { 'Content-Type': 'application/json' },
  4321. body: JSON.stringify({ disabled })
  4322. });
  4323. if (res.ok) {
  4324. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  4325. loadEoIP(false);
  4326. fetchData(false);
  4327. }
  4328. } catch (err) {
  4329. showToast('Error', err.message, 'error');
  4330. }
  4331. }
  4332. async function deleteEoIP(id) {
  4333. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  4334. try {
  4335. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4336. if (res.ok) {
  4337. showToast('Deleted', 'EoIP tunnel removed', 'success');
  4338. loadEoIP(false);
  4339. fetchData(false);
  4340. }
  4341. } catch (err) {
  4342. showToast('Error', err.message, 'error');
  4343. }
  4344. }
  4345. // ======================== PPP Central Hub & Servers ========================
  4346. function switchPPPSubTab(tab) {
  4347. state.pppSubTab = tab;
  4348. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  4349. tabs.forEach(t => {
  4350. const panel = document.getElementById(`ppp-subtab-${t}`);
  4351. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  4352. if (panel) {
  4353. if (t === tab) panel.classList.remove('hidden');
  4354. else panel.classList.add('hidden');
  4355. }
  4356. if (btn) {
  4357. if (t === tab) {
  4358. 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';
  4359. } else {
  4360. 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';
  4361. }
  4362. }
  4363. });
  4364. const addBtn = document.getElementById('ppp-primary-add-btn');
  4365. if (addBtn) {
  4366. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4367. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4368. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4369. else addBtn.innerHTML = '<span>Save Config</span>';
  4370. }
  4371. if (tab === 'active') loadPPPSessions();
  4372. }
  4373. function openCurrentPPPModal() {
  4374. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4375. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4376. else if (state.pppSubTab === 'active') loadPPPSessions();
  4377. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4378. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4379. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4380. }
  4381. async function loadPPP(populateDropdowns = true) {
  4382. await Promise.all([
  4383. loadPPPSecrets(),
  4384. loadPPPProfiles(),
  4385. loadPPPServers(),
  4386. loadPPPSessions()
  4387. ]);
  4388. }
  4389. async function loadPPPSecrets() {
  4390. try {
  4391. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4392. const data = await res.json();
  4393. state.pppSecrets = Array.isArray(data) ? data : [];
  4394. const b = document.getElementById('ppp-badge-secrets');
  4395. if (b) b.innerText = state.pppSecrets.length;
  4396. const b2 = document.getElementById('secrets-count-badge');
  4397. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4398. renderPPPSecrets();
  4399. } catch (err) {
  4400. console.error('Failed to load PPP secrets:', err);
  4401. }
  4402. }
  4403. function renderPPPSecrets() {
  4404. const tbody = document.getElementById('secrets-table-body');
  4405. const empty = document.getElementById('secrets-empty');
  4406. if (!tbody) return;
  4407. tbody.innerHTML = '';
  4408. const secrets = state.pppSecrets || [];
  4409. if (secrets.length === 0) {
  4410. empty?.classList.remove('hidden');
  4411. return;
  4412. }
  4413. empty?.classList.add('hidden');
  4414. secrets.forEach(s => {
  4415. const tr = document.createElement('tr');
  4416. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4417. tr.innerHTML = `
  4418. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4419. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4420. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4421. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4422. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4423. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4424. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4425. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4426. <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>
  4427. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4428. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4429. </td>
  4430. `;
  4431. tbody.appendChild(tr);
  4432. });
  4433. }
  4434. async function loadPPPProfiles() {
  4435. try {
  4436. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4437. const data = await res.json();
  4438. state.pppProfiles = Array.isArray(data) ? data : [];
  4439. const b = document.getElementById('ppp-badge-profiles');
  4440. if (b) b.innerText = state.pppProfiles.length;
  4441. const b2 = document.getElementById('profiles-count-badge');
  4442. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4443. // Populate profile selects across modals
  4444. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4445. selects.forEach(sid => {
  4446. const el = document.getElementById(sid);
  4447. if (!el) return;
  4448. const cur = el.value;
  4449. el.innerHTML = '';
  4450. state.pppProfiles.forEach(p => {
  4451. const opt = document.createElement('option');
  4452. opt.value = p.name;
  4453. opt.innerText = `${p.name} (${p.remote_address})`;
  4454. if (p.name === cur) opt.selected = true;
  4455. el.appendChild(opt);
  4456. });
  4457. });
  4458. renderPPPProfiles();
  4459. } catch (err) {
  4460. console.error('Failed to load PPP profiles:', err);
  4461. }
  4462. }
  4463. function renderPPPProfiles() {
  4464. const tbody = document.getElementById('profiles-table-body');
  4465. if (!tbody) return;
  4466. tbody.innerHTML = '';
  4467. (state.pppProfiles || []).forEach(p => {
  4468. const isDefault = p.name.startsWith('default');
  4469. const tr = document.createElement('tr');
  4470. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4471. tr.innerHTML = `
  4472. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4473. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4474. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4475. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4476. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4477. <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>
  4478. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4479. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4480. ${!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>`}
  4481. </td>
  4482. `;
  4483. tbody.appendChild(tr);
  4484. });
  4485. }
  4486. async function loadPPPServers() {
  4487. try {
  4488. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4489. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4490. fetch(`${API_BASE}/vpn/servers/pptp`),
  4491. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4492. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4493. ]);
  4494. if (pppoeRes.ok) {
  4495. state.pppoeServer = await pppoeRes.json();
  4496. const s = state.pppoeServer;
  4497. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4498. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4499. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4500. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4501. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4502. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4503. const pill = document.getElementById('pppoe-server-status-pill');
  4504. if (pill) {
  4505. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4506. 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';
  4507. }
  4508. setDotBadge('ppp-badge-pppoe-state', s.running);
  4509. }
  4510. if (pptpRes.ok) {
  4511. state.pptpServer = await pptpRes.json();
  4512. const s = state.pptpServer;
  4513. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4514. document.getElementById('pptp-server-port').value = s.port || 1723;
  4515. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4516. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4517. const pill = document.getElementById('pptp-server-status-pill');
  4518. if (pill) {
  4519. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4520. 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';
  4521. }
  4522. setDotBadge('ppp-badge-pptp-state', s.running);
  4523. }
  4524. if (l2tpRes.ok) {
  4525. state.l2tpServer = await l2tpRes.json();
  4526. const s = state.l2tpServer;
  4527. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4528. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4529. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4530. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4531. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4532. const pill = document.getElementById('l2tp-server-status-pill');
  4533. if (pill) {
  4534. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4535. 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';
  4536. }
  4537. setDotBadge('ppp-badge-l2tp-state', s.running);
  4538. }
  4539. if (ipsecRes.ok) {
  4540. state.ipsecServer = await ipsecRes.json();
  4541. const s = state.ipsecServer;
  4542. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4543. if (modalEn) modalEn.checked = !!s.enabled;
  4544. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4545. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4546. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4547. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4548. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4549. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4550. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4551. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4552. const pill = document.getElementById('modal-ipsec-server-status');
  4553. if (pill) {
  4554. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4555. 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';
  4556. }
  4557. }
  4558. } catch (err) {
  4559. console.error('Failed to load VPN servers:', err);
  4560. }
  4561. }
  4562. async function loadPPPSessions() {
  4563. try {
  4564. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4565. const data = await res.json();
  4566. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4567. const b = document.getElementById('ppp-badge-active');
  4568. if (b) b.innerText = state.pppActiveSessions.length;
  4569. const sideB = document.getElementById('badge-ppp-sessions');
  4570. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4571. renderPPPSessions();
  4572. } catch (err) {
  4573. console.error('Failed to load active PPP sessions:', err);
  4574. }
  4575. }
  4576. function renderPPPSessions() {
  4577. const tbody = document.getElementById('active-ppp-table-body');
  4578. const empty = document.getElementById('active-ppp-empty');
  4579. if (!tbody) return;
  4580. tbody.innerHTML = '';
  4581. const list = state.pppActiveSessions || [];
  4582. if (list.length === 0) {
  4583. empty?.classList.remove('hidden');
  4584. return;
  4585. }
  4586. empty?.classList.add('hidden');
  4587. list.forEach(s => {
  4588. const tr = document.createElement('tr');
  4589. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4590. tr.innerHTML = `
  4591. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4592. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4593. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4594. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4595. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4596. <td class="py-2.5 px-3 text-[11px]">
  4597. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4598. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4599. </td>
  4600. <td class="py-2.5 px-3 text-right font-sans">
  4601. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4602. </td>
  4603. `;
  4604. tbody.appendChild(tr);
  4605. });
  4606. }
  4607. async function disconnectPPPSession(iface) {
  4608. if (!confirm(`Disconnect session ${iface}?`)) return;
  4609. try {
  4610. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4611. if (res.ok) {
  4612. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4613. loadPPPSessions();
  4614. }
  4615. } catch (err) {
  4616. showToast('Error', err.message, 'error');
  4617. }
  4618. }
  4619. // PPP Secret Modal handlers
  4620. function openAddPPPSecretModal() {
  4621. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4622. document.getElementById('secret-modal-id').value = '';
  4623. document.getElementById('secret-modal-name').value = '';
  4624. document.getElementById('secret-modal-password').value = '';
  4625. document.getElementById('secret-modal-service').value = 'any';
  4626. document.getElementById('secret-modal-profile').value = 'default';
  4627. document.getElementById('secret-modal-local').value = '';
  4628. document.getElementById('secret-modal-remote').value = '';
  4629. document.getElementById('secret-modal-comment').value = '';
  4630. document.getElementById('secret-modal-disabled').checked = false;
  4631. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4632. }
  4633. function openEditPPPSecretModal(id) {
  4634. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4635. if (!s) return;
  4636. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4637. document.getElementById('secret-modal-id').value = s.id;
  4638. document.getElementById('secret-modal-name').value = s.name;
  4639. document.getElementById('secret-modal-password').value = s.password;
  4640. document.getElementById('secret-modal-service').value = s.service || 'any';
  4641. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4642. document.getElementById('secret-modal-local').value = s.local_address || '';
  4643. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4644. document.getElementById('secret-modal-comment').value = s.comment || '';
  4645. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4646. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4647. }
  4648. function closePPPSecretModal() {
  4649. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4650. }
  4651. async function submitSavePPPSecret(e) {
  4652. e.preventDefault();
  4653. const id = document.getElementById('secret-modal-id').value;
  4654. const name = document.getElementById('secret-modal-name').value.trim();
  4655. const password = document.getElementById('secret-modal-password').value.trim();
  4656. const service = document.getElementById('secret-modal-service').value;
  4657. const profile = document.getElementById('secret-modal-profile').value;
  4658. const local = document.getElementById('secret-modal-local').value.trim();
  4659. const remote = document.getElementById('secret-modal-remote').value.trim();
  4660. const comment = document.getElementById('secret-modal-comment').value.trim();
  4661. const disabled = document.getElementById('secret-modal-disabled').checked;
  4662. try {
  4663. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4664. method: 'POST',
  4665. headers: { 'Content-Type': 'application/json' },
  4666. body: JSON.stringify({
  4667. id,
  4668. name,
  4669. password,
  4670. service,
  4671. profile,
  4672. local_address: local,
  4673. remote_address: remote,
  4674. comment,
  4675. disabled
  4676. })
  4677. });
  4678. if (res.ok) {
  4679. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4680. closePPPSecretModal();
  4681. loadPPPSecrets();
  4682. } else {
  4683. const err = await res.json();
  4684. showToast('Error', err.message, 'error');
  4685. }
  4686. } catch (err) {
  4687. showToast('Error', err.message, 'error');
  4688. }
  4689. }
  4690. async function togglePPPSecretState(id, disabled) {
  4691. try {
  4692. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4693. method: 'POST',
  4694. headers: { 'Content-Type': 'application/json' },
  4695. body: JSON.stringify({ disabled })
  4696. });
  4697. if (res.ok) {
  4698. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4699. loadPPPSecrets();
  4700. }
  4701. } catch (err) {
  4702. showToast('Error', err.message, 'error');
  4703. }
  4704. }
  4705. async function deletePPPSecret(id) {
  4706. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4707. try {
  4708. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4709. if (res.ok) {
  4710. showToast('Deleted', 'Secret account removed', 'success');
  4711. loadPPPSecrets();
  4712. }
  4713. } catch (err) {
  4714. showToast('Error', err.message, 'error');
  4715. }
  4716. }
  4717. // PPP Profile Modal handlers
  4718. function openAddPPPProfileModal() {
  4719. document.getElementById('profile-modal-name').value = '';
  4720. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4721. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4722. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4723. document.getElementById('profile-modal-encryption').value = 'required';
  4724. document.getElementById('profile-modal-onlyone').checked = true;
  4725. document.getElementById('profile-modal-comment').value = '';
  4726. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4727. }
  4728. function closePPPProfileModal() {
  4729. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4730. }
  4731. async function submitSavePPPProfile(e) {
  4732. e.preventDefault();
  4733. const name = document.getElementById('profile-modal-name').value.trim();
  4734. const local = document.getElementById('profile-modal-local').value.trim();
  4735. const remote = document.getElementById('profile-modal-remote').value.trim();
  4736. const dns = document.getElementById('profile-modal-dns').value.trim();
  4737. const enc = document.getElementById('profile-modal-encryption').value;
  4738. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4739. const comment = document.getElementById('profile-modal-comment').value.trim();
  4740. try {
  4741. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4742. method: 'POST',
  4743. headers: { 'Content-Type': 'application/json' },
  4744. body: JSON.stringify({
  4745. id: name,
  4746. name,
  4747. local_address: local,
  4748. remote_address: remote,
  4749. dns_servers: dns,
  4750. use_encryption: enc,
  4751. only_one: onlyone,
  4752. comment
  4753. })
  4754. });
  4755. if (res.ok) {
  4756. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4757. closePPPProfileModal();
  4758. loadPPPProfiles();
  4759. } else {
  4760. const err = await res.json();
  4761. showToast('Error', err.message, 'error');
  4762. }
  4763. } catch (err) {
  4764. showToast('Error', err.message, 'error');
  4765. }
  4766. }
  4767. async function deletePPPProfile(name) {
  4768. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4769. try {
  4770. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4771. if (res.ok) {
  4772. showToast('Deleted', 'Profile removed', 'success');
  4773. loadPPPProfiles();
  4774. } else {
  4775. const err = await res.json();
  4776. showToast('Error', err.message, 'error');
  4777. }
  4778. } catch (err) {
  4779. showToast('Error', err.message, 'error');
  4780. }
  4781. }
  4782. // Server Config submissions
  4783. async function savePPPoEServerConfig(e) {
  4784. e.preventDefault();
  4785. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4786. const name = document.getElementById('pppoe-server-name').value.trim();
  4787. const iface = document.getElementById('pppoe-server-iface').value;
  4788. const profile = document.getElementById('pppoe-server-profile').value;
  4789. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4790. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4791. try {
  4792. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4793. method: 'POST',
  4794. headers: { 'Content-Type': 'application/json' },
  4795. body: JSON.stringify({
  4796. enabled,
  4797. service_name: name,
  4798. interface: iface,
  4799. default_profile: profile,
  4800. max_mtu: mtu,
  4801. max_mru: mtu,
  4802. one_session_per_host: onesession
  4803. })
  4804. });
  4805. if (res.ok) {
  4806. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4807. loadPPPServers();
  4808. fetchData(false);
  4809. } else {
  4810. const err = await res.json();
  4811. showToast('Error', err.message, 'error');
  4812. }
  4813. } catch (err) {
  4814. showToast('Error', err.message, 'error');
  4815. }
  4816. }
  4817. async function savePPTPServerConfig(e) {
  4818. e.preventDefault();
  4819. const enabled = document.getElementById('pptp-server-enabled').checked;
  4820. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4821. const profile = document.getElementById('pptp-server-profile').value;
  4822. const mppe = document.getElementById('pptp-server-mppe').checked;
  4823. try {
  4824. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4825. method: 'POST',
  4826. headers: { 'Content-Type': 'application/json' },
  4827. body: JSON.stringify({
  4828. enabled,
  4829. port,
  4830. default_profile: profile,
  4831. require_mppe: mppe
  4832. })
  4833. });
  4834. if (res.ok) {
  4835. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4836. loadPPPServers();
  4837. fetchData(false);
  4838. } else {
  4839. const err = await res.json();
  4840. showToast('Error', err.message, 'error');
  4841. }
  4842. } catch (err) {
  4843. showToast('Error', err.message, 'error');
  4844. }
  4845. }
  4846. async function saveL2TPServerConfig(e) {
  4847. e.preventDefault();
  4848. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4849. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4850. const profile = document.getElementById('l2tp-server-profile').value;
  4851. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4852. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4853. try {
  4854. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4855. method: 'POST',
  4856. headers: { 'Content-Type': 'application/json' },
  4857. body: JSON.stringify({
  4858. enabled,
  4859. port,
  4860. default_profile: profile,
  4861. use_ipsec: useipsec,
  4862. ipsec_secret: psk
  4863. })
  4864. });
  4865. if (res.ok) {
  4866. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4867. loadPPPServers();
  4868. fetchData(false);
  4869. } else {
  4870. const err = await res.json();
  4871. showToast('Error', err.message, 'error');
  4872. }
  4873. } catch (err) {
  4874. showToast('Error', err.message, 'error');
  4875. }
  4876. }
  4877. // IPSec Server Modal
  4878. function openIPSecServerModal() {
  4879. loadPPPServers();
  4880. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4881. }
  4882. function closeIPSecServerModal() {
  4883. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4884. }
  4885. async function submitSaveIPSecServer(e) {
  4886. e.preventDefault();
  4887. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4888. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4889. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4890. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4891. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4892. try {
  4893. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4894. method: 'POST',
  4895. headers: { 'Content-Type': 'application/json' },
  4896. body: JSON.stringify({
  4897. enabled,
  4898. preshared_key: psk,
  4899. pool_address: pool,
  4900. dns_servers: dns,
  4901. local_subnet: subnet
  4902. })
  4903. });
  4904. if (res.ok) {
  4905. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4906. closeIPSecServerModal();
  4907. loadPPPServers();
  4908. fetchData(false);
  4909. } else {
  4910. const err = await res.json();
  4911. showToast('Error', err.message, 'error');
  4912. }
  4913. } catch (err) {
  4914. showToast('Error', err.message, 'error');
  4915. }
  4916. }
  4917. // WireGuard Client Config Viewer
  4918. let currentWGClientConf = '';
  4919. async function openWGClientConfModal(iface, clientIP) {
  4920. try {
  4921. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4922. method: 'POST',
  4923. headers: { 'Content-Type': 'application/json' },
  4924. body: JSON.stringify({
  4925. interface: iface,
  4926. address: clientIP || '10.10.0.2/32',
  4927. dns: '1.1.1.1, 8.8.8.8'
  4928. })
  4929. });
  4930. if (res.ok) {
  4931. const data = await res.json();
  4932. currentWGClientConf = data.config;
  4933. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4934. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4935. } else {
  4936. const err = await res.json();
  4937. showToast('Error', err.message, 'error');
  4938. }
  4939. } catch (err) {
  4940. showToast('Error', err.message, 'error');
  4941. }
  4942. }
  4943. function closeWGClientConfModal() {
  4944. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4945. }
  4946. function copyWGClientConf() {
  4947. if (!currentWGClientConf) return;
  4948. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4949. }
  4950. function downloadWGClientConf() {
  4951. if (!currentWGClientConf) return;
  4952. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4953. const a = document.createElement('a');
  4954. a.href = URL.createObjectURL(blob);
  4955. a.download = 'wireguard-client.conf';
  4956. document.body.appendChild(a);
  4957. a.click();
  4958. document.body.removeChild(a);
  4959. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4960. }
  4961. // =========================================================================
  4962. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4963. // =========================================================================
  4964. state.activeDynSubTab = 'bgp-peers';
  4965. state.activeBgpSubTab = 'bgp-peers';
  4966. state.activeOspfSubTab = 'ospf-ifaces';
  4967. state.bgpInstance = null;
  4968. state.bgpPeers = [];
  4969. state.bgpNets = [];
  4970. state.bgpRoutes = [];
  4971. state.ospfInstance = null;
  4972. state.ospfInterfaces = [];
  4973. state.ospfAreas = [];
  4974. state.ospfNeighbors = [];
  4975. state.ospfRoutes = [];
  4976. function switchBgpSubTab(subTab) {
  4977. state.activeBgpSubTab = subTab;
  4978. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4979. tabs.forEach(t => {
  4980. const el = document.getElementById(`dyn-subtab-${t}`);
  4981. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4982. if (el) el.classList.toggle('hidden', t !== subTab);
  4983. if (btn) {
  4984. if (t === subTab) {
  4985. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  4986. } else {
  4987. 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';
  4988. }
  4989. }
  4990. });
  4991. }
  4992. function switchOspfSubTab(subTab) {
  4993. state.activeOspfSubTab = subTab;
  4994. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4995. tabs.forEach(t => {
  4996. const el = document.getElementById(`dyn-subtab-${t}`);
  4997. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4998. if (el) el.classList.toggle('hidden', t !== subTab);
  4999. if (btn) {
  5000. if (t === subTab) {
  5001. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  5002. } else {
  5003. 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';
  5004. }
  5005. }
  5006. });
  5007. }
  5008. function switchDynSubTab(subTab) {
  5009. if (subTab.startsWith('bgp')) {
  5010. if (state.activeTab !== 'bgp') navigate('bgp');
  5011. switchBgpSubTab(subTab);
  5012. } else if (subTab.startsWith('ospf')) {
  5013. if (state.activeTab !== 'ospf') navigate('ospf');
  5014. switchOspfSubTab(subTab);
  5015. }
  5016. }
  5017. async function loadDynamicRouting(showToastMsg = false) {
  5018. try {
  5019. const fetchSafeJson = async (url) => {
  5020. try {
  5021. const r = await fetch(url);
  5022. return r.ok ? await r.json() : null;
  5023. } catch (e) {
  5024. return null;
  5025. }
  5026. };
  5027. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  5028. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  5029. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  5030. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  5031. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  5032. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  5033. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  5034. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  5035. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  5036. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  5037. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  5038. fetchSafeJson(`${API_BASE}/routing/filters`)
  5039. ]);
  5040. if (sum) state.dynSummary = sum;
  5041. if (bgpInst) state.bgpInstance = bgpInst;
  5042. if (bgpPeers) state.bgpPeers = bgpPeers;
  5043. if (bgpNets) state.bgpNets = bgpNets;
  5044. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  5045. if (ospfInst) state.ospfInstance = ospfInst;
  5046. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  5047. if (ospfAreas) state.ospfAreas = ospfAreas;
  5048. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  5049. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  5050. if (filters) state.routingFilters = filters;
  5051. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  5052. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  5053. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  5054. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  5055. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  5056. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  5057. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  5058. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  5059. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  5060. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  5061. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  5062. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  5063. } catch (err) {
  5064. console.error('Failed to load dynamic routing:', err);
  5065. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  5066. }
  5067. }
  5068. function renderBgpStatusPill() {
  5069. const pill = document.getElementById('bgp-live-status-pill');
  5070. if (!pill) return;
  5071. const inst = state.bgpInstance;
  5072. if (!inst || !inst.enabled) {
  5073. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5074. pill.innerText = 'BGP DISABLED';
  5075. } else if (inst.running) {
  5076. 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';
  5077. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  5078. } else {
  5079. 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';
  5080. pill.innerText = 'BGP STARTING...';
  5081. }
  5082. }
  5083. function renderBgpPeers() {
  5084. const tbody = document.getElementById('bgp-peers-table-body');
  5085. if (!tbody) return;
  5086. const empty = document.getElementById('bgp-peers-empty');
  5087. const countBadge = document.getElementById('bgp-peers-count-badge');
  5088. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  5089. const peers = state.bgpPeers || [];
  5090. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  5091. if (navBadge) navBadge.innerText = peers.length;
  5092. if (peers.length === 0) {
  5093. tbody.innerHTML = '';
  5094. if (empty) empty.classList.remove('hidden');
  5095. return;
  5096. }
  5097. if (empty) empty.classList.add('hidden');
  5098. tbody.innerHTML = peers.map(p => {
  5099. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5100. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  5101. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5102. let stateBadge = '';
  5103. if (p.disabled) {
  5104. 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>';
  5105. } else if (p.state === 'Established') {
  5106. 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>';
  5107. } else if (p.state === 'Connect' || p.state === 'Active') {
  5108. 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>`;
  5109. } else {
  5110. 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>`;
  5111. }
  5112. return `
  5113. <tr class="hover:bg-slate-800/40 transition">
  5114. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  5115. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  5116. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  5117. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  5118. <td class="py-2.5 px-3">${stateBadge}</td>
  5119. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  5120. <td class="py-2.5 px-3 text-slate-300">
  5121. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  5122. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  5123. </td>
  5124. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  5125. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  5126. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  5127. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  5128. </td>
  5129. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  5130. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5131. <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'}">
  5132. ${p.disabled ? 'Enable' : 'Disable'}
  5133. </button>
  5134. <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">
  5135. Edit
  5136. </button>
  5137. <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">
  5138. Delete
  5139. </button>
  5140. </td>
  5141. </tr>
  5142. `;
  5143. }).join('');
  5144. }
  5145. function renderBgpNetworks() {
  5146. const tbody = document.getElementById('bgp-nets-table-body');
  5147. if (!tbody) return;
  5148. const empty = document.getElementById('bgp-nets-empty');
  5149. const countBadge = document.getElementById('bgp-nets-count-badge');
  5150. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  5151. const nets = state.bgpNets || [];
  5152. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  5153. if (navBadge) navBadge.innerText = nets.length;
  5154. if (nets.length === 0) {
  5155. tbody.innerHTML = '';
  5156. if (empty) empty.classList.remove('hidden');
  5157. return;
  5158. }
  5159. if (empty) empty.classList.add('hidden');
  5160. tbody.innerHTML = nets.map(n => `
  5161. <tr class="hover:bg-slate-800/40 transition">
  5162. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  5163. <td class="py-2.5 px-3">
  5164. ${n.disabled
  5165. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  5166. : '<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>'}
  5167. </td>
  5168. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  5169. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  5170. <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">
  5171. Delete
  5172. </button>
  5173. </td>
  5174. </tr>
  5175. `).join('');
  5176. }
  5177. function renderBgpRoutes() {
  5178. const tbody = document.getElementById('bgp-routes-table-body');
  5179. if (!tbody) return;
  5180. const empty = document.getElementById('bgp-routes-empty');
  5181. const countBadge = document.getElementById('bgp-routes-count-badge');
  5182. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  5183. const routes = state.bgpRoutes || [];
  5184. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5185. if (navBadge) navBadge.innerText = routes.length;
  5186. if (routes.length === 0) {
  5187. tbody.innerHTML = '';
  5188. if (empty) empty.classList.remove('hidden');
  5189. return;
  5190. }
  5191. if (empty) empty.classList.add('hidden');
  5192. tbody.innerHTML = routes.map(r => `
  5193. <tr class="hover:bg-slate-800/40 transition">
  5194. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  5195. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  5196. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  5197. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  5198. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  5199. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  5200. </tr>
  5201. `).join('');
  5202. }
  5203. function renderOspfStatusPill() {
  5204. const pill = document.getElementById('ospf-live-status-pill');
  5205. if (!pill) return;
  5206. const inst = state.ospfInstance;
  5207. if (!inst || !inst.enabled) {
  5208. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5209. pill.innerText = 'OSPF DISABLED';
  5210. } else if (inst.running) {
  5211. 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';
  5212. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  5213. } else {
  5214. 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';
  5215. pill.innerText = 'OSPF STARTING...';
  5216. }
  5217. }
  5218. function renderOspfInterfaces() {
  5219. const tbody = document.getElementById('ospf-ifaces-table-body');
  5220. if (!tbody) return;
  5221. const empty = document.getElementById('ospf-ifaces-empty');
  5222. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  5223. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  5224. const ifaces = state.ospfInterfaces || [];
  5225. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  5226. if (navBadge) navBadge.innerText = ifaces.length;
  5227. if (ifaces.length === 0) {
  5228. tbody.innerHTML = '';
  5229. if (empty) empty.classList.remove('hidden');
  5230. return;
  5231. }
  5232. if (empty) empty.classList.add('hidden');
  5233. tbody.innerHTML = ifaces.map(i => {
  5234. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5235. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  5236. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5237. return `
  5238. <tr class="hover:bg-slate-800/40 transition">
  5239. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  5240. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  5241. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  5242. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  5243. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  5244. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  5245. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  5246. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  5247. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  5248. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5249. <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'}">
  5250. ${i.disabled ? 'Enable' : 'Disable'}
  5251. </button>
  5252. <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">
  5253. Edit
  5254. </button>
  5255. <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">
  5256. Delete
  5257. </button>
  5258. </td>
  5259. </tr>
  5260. `;
  5261. }).join('');
  5262. }
  5263. function renderOspfAreas() {
  5264. const tbody = document.getElementById('ospf-areas-table-body');
  5265. if (!tbody) return;
  5266. const countBadge = document.getElementById('ospf-areas-count-badge');
  5267. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  5268. const areas = state.ospfAreas || [];
  5269. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  5270. if (navBadge) navBadge.innerText = areas.length;
  5271. tbody.innerHTML = areas.map(a => `
  5272. <tr class="hover:bg-slate-800/40 transition">
  5273. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  5274. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  5275. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  5276. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  5277. <td class="py-2.5 px-3 text-right font-sans">
  5278. <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">
  5279. Delete
  5280. </button>
  5281. </td>
  5282. </tr>
  5283. `).join('');
  5284. }
  5285. function renderOspfNeighbors() {
  5286. const tbody = document.getElementById('ospf-nbrs-table-body');
  5287. if (!tbody) return;
  5288. const empty = document.getElementById('ospf-nbrs-empty');
  5289. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  5290. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  5291. const nbrs = state.ospfNeighbors || [];
  5292. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  5293. if (navBadge) navBadge.innerText = nbrs.length;
  5294. if (nbrs.length === 0) {
  5295. tbody.innerHTML = '';
  5296. if (empty) empty.classList.remove('hidden');
  5297. return;
  5298. }
  5299. if (empty) empty.classList.add('hidden');
  5300. tbody.innerHTML = nbrs.map(n => {
  5301. let stateBadge = '';
  5302. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  5303. 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>`;
  5304. } else {
  5305. 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>`;
  5306. }
  5307. return `
  5308. <tr class="hover:bg-slate-800/40 transition">
  5309. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  5310. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  5311. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  5312. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  5313. <td class="py-2.5 px-3">${stateBadge}</td>
  5314. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  5315. </tr>
  5316. `;
  5317. }).join('');
  5318. }
  5319. function renderOspfRoutes() {
  5320. const tbody = document.getElementById('ospf-routes-table-body');
  5321. if (!tbody) return;
  5322. const empty = document.getElementById('ospf-routes-empty');
  5323. const countBadge = document.getElementById('ospf-routes-count-badge');
  5324. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  5325. const routes = state.ospfRoutes || [];
  5326. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5327. if (navBadge) navBadge.innerText = routes.length;
  5328. if (routes.length === 0) {
  5329. tbody.innerHTML = '';
  5330. if (empty) empty.classList.remove('hidden');
  5331. return;
  5332. }
  5333. if (empty) empty.classList.add('hidden');
  5334. tbody.innerHTML = routes.map(r => `
  5335. <tr class="hover:bg-slate-800/40 transition">
  5336. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  5337. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  5338. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  5339. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  5340. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  5341. </tr>
  5342. `).join('');
  5343. }
  5344. // BGP Modals & Actions
  5345. function openBgpInstanceModal() {
  5346. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  5347. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  5348. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  5349. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  5350. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  5351. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  5352. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  5353. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  5354. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  5355. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  5356. }
  5357. function closeBgpInstanceModal() {
  5358. document.getElementById('bgp-instance-modal').classList.add('hidden');
  5359. }
  5360. async function submitBgpInstance(e) {
  5361. e.preventDefault();
  5362. const payload = {
  5363. enabled: document.getElementById('modal-bgp-enabled').checked,
  5364. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  5365. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5366. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5367. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5368. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5369. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5370. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5371. };
  5372. try {
  5373. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5374. method: 'POST',
  5375. headers: { 'Content-Type': 'application/json' },
  5376. body: JSON.stringify(payload)
  5377. });
  5378. if (res.ok) {
  5379. closeBgpInstanceModal();
  5380. showToast('Success', 'BGP instance configuration updated', 'success');
  5381. loadDynamicRouting();
  5382. } else {
  5383. const err = await res.json();
  5384. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5385. }
  5386. } catch (err) {
  5387. showToast('Error', err.message, 'error');
  5388. }
  5389. }
  5390. function openAddBgpPeerModal() {
  5391. document.getElementById('bgp-peer-form').reset();
  5392. document.getElementById('modal-bgp-peer-id').value = '';
  5393. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5394. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5395. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5396. if (inFilterEl) inFilterEl.value = '';
  5397. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5398. if (outFilterEl) outFilterEl.value = '';
  5399. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5400. }
  5401. function openEditBgpPeerModal(id) {
  5402. const p = (state.bgpPeers || []).find(item => item.id === id);
  5403. if (!p) return;
  5404. document.getElementById('modal-bgp-peer-id').value = p.id;
  5405. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5406. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5407. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5408. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5409. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5410. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5411. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5412. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5413. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5414. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5415. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5416. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5417. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5418. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5419. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5420. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5421. }
  5422. function closeBgpPeerModal() {
  5423. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5424. }
  5425. async function submitBgpPeer(e) {
  5426. e.preventDefault();
  5427. const payload = {
  5428. id: document.getElementById('modal-bgp-peer-id').value,
  5429. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5430. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5431. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5432. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5433. password: document.getElementById('modal-bgp-peer-password').value,
  5434. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5435. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5436. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5437. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5438. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5439. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5440. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5441. };
  5442. try {
  5443. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5444. method: 'POST',
  5445. headers: { 'Content-Type': 'application/json' },
  5446. body: JSON.stringify(payload)
  5447. });
  5448. if (res.ok) {
  5449. closeBgpPeerModal();
  5450. showToast('Success', 'BGP Peer saved', 'success');
  5451. loadDynamicRouting();
  5452. } else {
  5453. const err = await res.json();
  5454. showToast('Error', err.error || 'Failed to save peer', 'error');
  5455. }
  5456. } catch (err) {
  5457. showToast('Error', err.message, 'error');
  5458. }
  5459. }
  5460. async function deleteBgpPeer(id) {
  5461. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5462. try {
  5463. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5464. if (res.ok) {
  5465. showToast('Deleted', 'BGP peer removed', 'success');
  5466. loadDynamicRouting();
  5467. }
  5468. } catch (err) {
  5469. showToast('Error', err.message, 'error');
  5470. }
  5471. }
  5472. async function toggleBgpPeerState(id, disabled) {
  5473. try {
  5474. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5475. method: 'POST',
  5476. headers: { 'Content-Type': 'application/json' },
  5477. body: JSON.stringify({ disabled })
  5478. });
  5479. if (res.ok) {
  5480. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5481. loadDynamicRouting();
  5482. }
  5483. } catch (err) {
  5484. showToast('Error', err.message, 'error');
  5485. }
  5486. }
  5487. function openAddBgpNetworkModal() {
  5488. document.getElementById('bgp-network-form').reset();
  5489. document.getElementById('modal-bgp-net-id').value = '';
  5490. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5491. }
  5492. function closeBgpNetworkModal() {
  5493. document.getElementById('bgp-network-modal').classList.add('hidden');
  5494. }
  5495. async function submitBgpNetwork(e) {
  5496. e.preventDefault();
  5497. const payload = {
  5498. id: document.getElementById('modal-bgp-net-id').value,
  5499. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5500. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5501. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5502. };
  5503. try {
  5504. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5505. method: 'POST',
  5506. headers: { 'Content-Type': 'application/json' },
  5507. body: JSON.stringify(payload)
  5508. });
  5509. if (res.ok) {
  5510. closeBgpNetworkModal();
  5511. showToast('Success', 'BGP network advertisement saved', 'success');
  5512. loadDynamicRouting();
  5513. } else {
  5514. const err = await res.json();
  5515. showToast('Error', err.error || 'Failed to save network', 'error');
  5516. }
  5517. } catch (err) {
  5518. showToast('Error', err.message, 'error');
  5519. }
  5520. }
  5521. async function deleteBgpNetwork(id) {
  5522. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5523. try {
  5524. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5525. if (res.ok) {
  5526. showToast('Deleted', 'Network advertisement removed', 'success');
  5527. loadDynamicRouting();
  5528. }
  5529. } catch (err) {
  5530. showToast('Error', err.message, 'error');
  5531. }
  5532. }
  5533. // OSPF Modals & Actions
  5534. function openOspfInstanceModal() {
  5535. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5536. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5537. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5538. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5539. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5540. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5541. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5542. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5543. }
  5544. function closeOspfInstanceModal() {
  5545. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5546. }
  5547. async function submitOspfInstance(e) {
  5548. e.preventDefault();
  5549. const payload = {
  5550. enabled: document.getElementById('modal-ospf-enabled').checked,
  5551. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5552. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5553. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5554. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5555. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5556. };
  5557. try {
  5558. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5559. method: 'POST',
  5560. headers: { 'Content-Type': 'application/json' },
  5561. body: JSON.stringify(payload)
  5562. });
  5563. if (res.ok) {
  5564. closeOspfInstanceModal();
  5565. showToast('Success', 'OSPF instance configuration updated', 'success');
  5566. loadDynamicRouting();
  5567. } else {
  5568. const err = await res.json();
  5569. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5570. }
  5571. } catch (err) {
  5572. showToast('Error', err.message, 'error');
  5573. }
  5574. }
  5575. function openAddOspfAreaModal() {
  5576. document.getElementById('ospf-area-form').reset();
  5577. document.getElementById('modal-ospf-area-id').value = '';
  5578. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5579. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5580. }
  5581. function closeOspfAreaModal() {
  5582. document.getElementById('ospf-area-modal').classList.add('hidden');
  5583. }
  5584. async function submitOspfArea(e) {
  5585. e.preventDefault();
  5586. const payload = {
  5587. id: document.getElementById('modal-ospf-area-id').value,
  5588. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5589. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5590. area_type: document.getElementById('modal-ospf-area-type').value,
  5591. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5592. };
  5593. try {
  5594. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5595. method: 'POST',
  5596. headers: { 'Content-Type': 'application/json' },
  5597. body: JSON.stringify(payload)
  5598. });
  5599. if (res.ok) {
  5600. closeOspfAreaModal();
  5601. showToast('Success', 'OSPF area saved', 'success');
  5602. loadDynamicRouting();
  5603. } else {
  5604. const err = await res.json();
  5605. showToast('Error', err.error || 'Failed to save area', 'error');
  5606. }
  5607. } catch (err) {
  5608. showToast('Error', err.message, 'error');
  5609. }
  5610. }
  5611. async function deleteOspfArea(id) {
  5612. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5613. try {
  5614. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5615. if (res.ok) {
  5616. showToast('Deleted', 'OSPF area removed', 'success');
  5617. loadDynamicRouting();
  5618. }
  5619. } catch (err) {
  5620. showToast('Error', err.message, 'error');
  5621. }
  5622. }
  5623. function populateOspfInterfaceDevices() {
  5624. const select = document.getElementById('modal-ospf-iface-device');
  5625. if (!select) return;
  5626. const current = select.value;
  5627. select.innerHTML = '<option value="">Any matching interface</option>';
  5628. (state.interfaces || []).forEach(iface => {
  5629. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5630. });
  5631. if (current) select.value = current;
  5632. }
  5633. function openAddOspfInterfaceModal() {
  5634. document.getElementById('ospf-interface-form').reset();
  5635. document.getElementById('modal-ospf-iface-id').value = '';
  5636. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5637. document.getElementById('modal-ospf-iface-cost').value = '10';
  5638. document.getElementById('modal-ospf-iface-priority').value = '1';
  5639. document.getElementById('modal-ospf-iface-hello').value = '10';
  5640. document.getElementById('modal-ospf-iface-dead').value = '40';
  5641. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5642. populateOspfInterfaceDevices();
  5643. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5644. }
  5645. function openEditOspfInterfaceModal(id) {
  5646. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5647. if (!item) return;
  5648. populateOspfInterfaceDevices();
  5649. document.getElementById('modal-ospf-iface-id').value = item.id;
  5650. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5651. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5652. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5653. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5654. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5655. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5656. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5657. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5658. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5659. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5660. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5661. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5662. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5663. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5664. }
  5665. function closeOspfInterfaceModal() {
  5666. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5667. }
  5668. async function submitOspfInterface(e) {
  5669. e.preventDefault();
  5670. const payload = {
  5671. id: document.getElementById('modal-ospf-iface-id').value,
  5672. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5673. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5674. interface: document.getElementById('modal-ospf-iface-device').value,
  5675. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5676. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5677. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5678. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5679. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5680. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5681. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5682. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5683. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5684. };
  5685. try {
  5686. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5687. method: 'POST',
  5688. headers: { 'Content-Type': 'application/json' },
  5689. body: JSON.stringify(payload)
  5690. });
  5691. if (res.ok) {
  5692. closeOspfInterfaceModal();
  5693. showToast('Success', 'OSPF interface template saved', 'success');
  5694. loadDynamicRouting();
  5695. } else {
  5696. const err = await res.json();
  5697. showToast('Error', err.error || 'Failed to save interface', 'error');
  5698. }
  5699. } catch (err) {
  5700. showToast('Error', err.message, 'error');
  5701. }
  5702. }
  5703. async function deleteOspfInterface(id) {
  5704. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5705. try {
  5706. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5707. if (res.ok) {
  5708. showToast('Deleted', 'OSPF interface removed', 'success');
  5709. loadDynamicRouting();
  5710. }
  5711. } catch (err) {
  5712. showToast('Error', err.message, 'error');
  5713. }
  5714. }
  5715. async function toggleOspfInterfaceState(id, disabled) {
  5716. try {
  5717. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5718. method: 'POST',
  5719. headers: { 'Content-Type': 'application/json' },
  5720. body: JSON.stringify({ disabled })
  5721. });
  5722. if (res.ok) {
  5723. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5724. loadDynamicRouting();
  5725. }
  5726. } catch (err) {
  5727. showToast('Error', err.message, 'error');
  5728. }
  5729. }
  5730. // ============================================================================
  5731. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5732. // ============================================================================
  5733. function switchBridgeSubTab(tab) {
  5734. state.bridgeSubTab = tab;
  5735. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5736. tabs.forEach(t => {
  5737. const panel = document.getElementById(`bridge-subtab-${t}`);
  5738. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5739. if (panel) {
  5740. if (t === tab) panel.classList.remove('hidden');
  5741. else panel.classList.add('hidden');
  5742. }
  5743. if (btn) {
  5744. if (t === tab) {
  5745. 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';
  5746. } else {
  5747. 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';
  5748. }
  5749. }
  5750. });
  5751. const addBtn = document.getElementById('bridge-top-action-btn');
  5752. if (addBtn) {
  5753. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5754. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5755. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5756. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5757. }
  5758. if (tab === 'hosts') loadBridgeHosts();
  5759. }
  5760. function openCurrentBridgeModal() {
  5761. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5762. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5763. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5764. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5765. }
  5766. async function loadBridge() {
  5767. try {
  5768. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5769. fetch(`${API_BASE}/bridge/bridges`),
  5770. fetch(`${API_BASE}/bridge/ports`),
  5771. fetch(`${API_BASE}/bridge/vlans`),
  5772. fetch(`${API_BASE}/bridge/summary`),
  5773. fetch(`${API_BASE}/vpn/eoip`),
  5774. fetch(`${API_BASE}/vlans`)
  5775. ]);
  5776. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5777. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5778. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5779. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5780. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5781. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5782. // Badges & Stats
  5783. const bBridges = document.getElementById('bridge-badge-bridges');
  5784. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5785. const bPorts = document.getElementById('bridge-badge-ports');
  5786. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5787. const bVlans = document.getElementById('bridge-badge-vlans');
  5788. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5789. const bHosts = document.getElementById('bridge-badge-hosts');
  5790. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5791. const sBr = document.getElementById('bridge-stat-bridges');
  5792. if (sBr) sBr.innerText = (state.bridges || []).length;
  5793. const sPorts = document.getElementById('bridge-stat-ports');
  5794. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5795. const sHosts = document.getElementById('bridge-stat-hosts');
  5796. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5797. renderBridges();
  5798. renderBridgePorts();
  5799. renderBridgeVLANs();
  5800. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5801. } catch (err) {
  5802. console.error('Failed to load bridge subsystem:', err);
  5803. }
  5804. }
  5805. // ----------------- Bridges -----------------
  5806. function renderBridges() {
  5807. const tbody = document.getElementById('bridge-table-body');
  5808. const empty = document.getElementById('bridge-empty-bridges');
  5809. const countBadge = document.getElementById('bridge-count-badge');
  5810. if (!tbody) return;
  5811. tbody.innerHTML = '';
  5812. const bridges = state.bridges || [];
  5813. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5814. if (bridges.length === 0) {
  5815. empty?.classList.remove('hidden');
  5816. return;
  5817. }
  5818. empty?.classList.add('hidden');
  5819. bridges.forEach((b, idx) => {
  5820. const tr = document.createElement('tr');
  5821. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5822. // Format IP addresses pill list
  5823. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5824. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5825. ipsHtml = b.ip_addresses.map(ip => `
  5826. <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">
  5827. <span>${ip}</span>
  5828. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5829. </span>
  5830. `).join(' ');
  5831. }
  5832. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5833. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5834. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5835. tr.innerHTML = `
  5836. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5837. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5838. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5839. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5840. </td>
  5841. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5842. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5843. <td class="py-2.5 px-3">
  5844. <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>
  5845. </td>
  5846. <td class="py-2.5 px-3 text-center">
  5847. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5848. </td>
  5849. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5850. <td class="py-2.5 px-3">
  5851. <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>
  5852. </td>
  5853. <td class="py-2.5 px-3">
  5854. <div class="flex items-center gap-1.5 flex-wrap">
  5855. ${ipsHtml}
  5856. <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>
  5857. </div>
  5858. </td>
  5859. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5860. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5861. </td>
  5862. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5863. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5864. <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>
  5865. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5866. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5867. </td>
  5868. `;
  5869. tbody.appendChild(tr);
  5870. });
  5871. }
  5872. function openAddBridgeModal() {
  5873. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5874. document.getElementById('bridge-modal-id').value = '';
  5875. document.getElementById('bridge-modal-name').value = 'bridge1';
  5876. document.getElementById('bridge-modal-name').disabled = false;
  5877. document.getElementById('bridge-modal-mtu').value = '1500';
  5878. document.getElementById('bridge-modal-mac').value = '';
  5879. document.getElementById('bridge-modal-stp').value = 'rstp';
  5880. document.getElementById('bridge-modal-priority').value = '32768';
  5881. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5882. document.getElementById('bridge-modal-pvid').value = '1';
  5883. document.getElementById('bridge-modal-fastforward').checked = true;
  5884. document.getElementById('bridge-modal-comment').value = '';
  5885. document.getElementById('bridge-modal-disabled').checked = false;
  5886. toggleBridgeModalVlanFiltering();
  5887. document.getElementById('bridge-modal').classList.remove('hidden');
  5888. }
  5889. function openEditBridgeModal(id) {
  5890. const b = (state.bridges || []).find(x => x.id === id);
  5891. if (!b) return;
  5892. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5893. document.getElementById('bridge-modal-id').value = b.id;
  5894. document.getElementById('bridge-modal-name').value = b.name;
  5895. document.getElementById('bridge-modal-name').disabled = true;
  5896. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5897. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5898. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5899. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5900. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5901. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5902. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5903. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5904. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5905. toggleBridgeModalVlanFiltering();
  5906. document.getElementById('bridge-modal').classList.remove('hidden');
  5907. }
  5908. function closeBridgeModal() {
  5909. document.getElementById('bridge-modal').classList.add('hidden');
  5910. }
  5911. function toggleBridgeModalVlanFiltering() {
  5912. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5913. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5914. if (pvidBox) {
  5915. if (chk) pvidBox.classList.remove('opacity-40');
  5916. else pvidBox.classList.add('opacity-40');
  5917. }
  5918. }
  5919. async function submitSaveBridge(e) {
  5920. e.preventDefault();
  5921. const id = document.getElementById('bridge-modal-id').value;
  5922. const name = document.getElementById('bridge-modal-name').value.trim();
  5923. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5924. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5925. const stp = document.getElementById('bridge-modal-stp').value;
  5926. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5927. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5928. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5929. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5930. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5931. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5932. try {
  5933. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5934. method: 'POST',
  5935. headers: { 'Content-Type': 'application/json' },
  5936. body: JSON.stringify({
  5937. id,
  5938. name,
  5939. mtu,
  5940. mac_address: mac,
  5941. stp,
  5942. priority,
  5943. vlan_filtering: vlanFiltering,
  5944. pvid,
  5945. fast_forward: fastForward,
  5946. comment,
  5947. disabled
  5948. })
  5949. });
  5950. if (res.ok) {
  5951. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5952. closeBridgeModal();
  5953. loadBridge();
  5954. fetchData(false);
  5955. } else {
  5956. const err = await res.json();
  5957. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5958. }
  5959. } catch (err) {
  5960. showToast('Error', err.message, 'error');
  5961. }
  5962. }
  5963. async function toggleBridgeState(id, disabled) {
  5964. try {
  5965. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5966. method: 'POST',
  5967. headers: { 'Content-Type': 'application/json' },
  5968. body: JSON.stringify({ disabled })
  5969. });
  5970. if (res.ok) {
  5971. loadBridge();
  5972. fetchData(false);
  5973. }
  5974. } catch (err) {
  5975. showToast('Error', err.message, 'error');
  5976. }
  5977. }
  5978. async function deleteBridge(id) {
  5979. const b = (state.bridges || []).find(x => x.id === id);
  5980. const name = b ? b.name : id;
  5981. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5982. try {
  5983. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5984. if (res.ok) {
  5985. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5986. loadBridge();
  5987. fetchData(false);
  5988. } else {
  5989. const err = await res.json();
  5990. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5991. }
  5992. } catch (err) {
  5993. showToast('Error', err.message, 'error');
  5994. }
  5995. }
  5996. // ----------------- Bridge IP Assignments -----------------
  5997. function openAddBridgeIPModal(id, name) {
  5998. document.getElementById('bridge-ip-modal-id').value = id;
  5999. document.getElementById('bridge-ip-modal-sub').innerText = name;
  6000. document.getElementById('bridge-ip-modal-cidr').value = '';
  6001. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  6002. }
  6003. function closeBridgeIPModal() {
  6004. document.getElementById('bridge-ip-modal').classList.add('hidden');
  6005. }
  6006. async function submitAddBridgeIP(e) {
  6007. e.preventDefault();
  6008. const id = document.getElementById('bridge-ip-modal-id').value;
  6009. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  6010. try {
  6011. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  6012. method: 'POST',
  6013. headers: { 'Content-Type': 'application/json' },
  6014. body: JSON.stringify({ ip })
  6015. });
  6016. if (res.ok) {
  6017. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  6018. closeBridgeIPModal();
  6019. loadBridge();
  6020. fetchData(false);
  6021. } else {
  6022. const err = await res.json();
  6023. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  6024. }
  6025. } catch (err) {
  6026. showToast('Error', err.message, 'error');
  6027. }
  6028. }
  6029. async function deleteBridgeIP(id, ip) {
  6030. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  6031. try {
  6032. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  6033. method: 'DELETE',
  6034. headers: { 'Content-Type': 'application/json' },
  6035. body: JSON.stringify({ ip })
  6036. });
  6037. if (res.ok) {
  6038. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  6039. loadBridge();
  6040. fetchData(false);
  6041. }
  6042. } catch (err) {
  6043. showToast('Error', err.message, 'error');
  6044. }
  6045. }
  6046. // ----------------- Bridge Ports -----------------
  6047. function renderBridgePorts() {
  6048. const tbody = document.getElementById('bridge-ports-table-body');
  6049. const empty = document.getElementById('bridge-empty-ports');
  6050. const countBadge = document.getElementById('bridge-ports-count-badge');
  6051. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  6052. if (!tbody) return;
  6053. tbody.innerHTML = '';
  6054. // Update filter select
  6055. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  6056. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  6057. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  6058. if (ports.length === 0) {
  6059. empty?.classList.remove('hidden');
  6060. return;
  6061. }
  6062. empty?.classList.add('hidden');
  6063. ports.forEach((p, idx) => {
  6064. const tr = document.createElement('tr');
  6065. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  6066. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6067. tr.innerHTML = `
  6068. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6069. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6070. <td class="py-2.5 px-3 font-bold text-white text-sm">
  6071. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  6072. </td>
  6073. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  6074. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  6075. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  6076. <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>
  6077. <td class="py-2.5 px-3">
  6078. ${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>'}
  6079. </td>
  6080. <td class="py-2.5 px-3">
  6081. <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>
  6082. </td>
  6083. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  6084. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6085. <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>
  6086. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6087. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6088. </td>
  6089. `;
  6090. tbody.appendChild(tr);
  6091. });
  6092. }
  6093. function openAddBridgePortModal() {
  6094. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  6095. document.getElementById('bridge-port-modal-id').value = '';
  6096. populateBridgeSelect('bridge-port-modal-bridge');
  6097. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  6098. document.getElementById('bridge-port-modal-pvid').value = '1';
  6099. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  6100. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  6101. document.getElementById('bridge-port-modal-horizon').value = '0';
  6102. document.getElementById('bridge-port-modal-pathcost').value = '10';
  6103. document.getElementById('bridge-port-modal-priority').value = '128';
  6104. document.getElementById('bridge-port-modal-learn').checked = true;
  6105. document.getElementById('bridge-port-modal-comment').value = '';
  6106. document.getElementById('bridge-port-modal-disabled').checked = false;
  6107. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6108. }
  6109. function openEditBridgePortModal(id) {
  6110. const p = (state.bridgePorts || []).find(x => x.id === id);
  6111. if (!p) return;
  6112. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  6113. document.getElementById('bridge-port-modal-id').value = p.id;
  6114. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  6115. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  6116. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  6117. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  6118. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  6119. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  6120. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  6121. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  6122. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  6123. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  6124. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  6125. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6126. }
  6127. function closeBridgePortModal() {
  6128. document.getElementById('bridge-port-modal').classList.add('hidden');
  6129. }
  6130. async function submitSaveBridgePort(e) {
  6131. e.preventDefault();
  6132. const id = document.getElementById('bridge-port-modal-id').value;
  6133. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  6134. const iface = document.getElementById('bridge-port-modal-interface').value;
  6135. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  6136. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  6137. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  6138. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  6139. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  6140. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  6141. const learn = document.getElementById('bridge-port-modal-learn').checked;
  6142. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  6143. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  6144. try {
  6145. const res = await fetch(`${API_BASE}/bridge/ports`, {
  6146. method: 'POST',
  6147. headers: { 'Content-Type': 'application/json' },
  6148. body: JSON.stringify({
  6149. id,
  6150. bridge,
  6151. interface: iface,
  6152. pvid,
  6153. frame_types: frameTypes,
  6154. ingress_filtering: ingressFiltering,
  6155. horizon,
  6156. path_cost: pathCost,
  6157. priority,
  6158. learn,
  6159. comment,
  6160. disabled
  6161. })
  6162. });
  6163. if (res.ok) {
  6164. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  6165. closeBridgePortModal();
  6166. loadBridge();
  6167. fetchData(false);
  6168. } else {
  6169. const err = await res.json();
  6170. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  6171. }
  6172. } catch (err) {
  6173. showToast('Error', err.message, 'error');
  6174. }
  6175. }
  6176. async function toggleBridgePortState(id, disabled) {
  6177. try {
  6178. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  6179. method: 'POST',
  6180. headers: { 'Content-Type': 'application/json' },
  6181. body: JSON.stringify({ disabled })
  6182. });
  6183. if (res.ok) {
  6184. loadBridge();
  6185. fetchData(false);
  6186. }
  6187. } catch (err) {
  6188. showToast('Error', err.message, 'error');
  6189. }
  6190. }
  6191. async function deleteBridgePort(id) {
  6192. const p = (state.bridgePorts || []).find(x => x.id === id);
  6193. const iface = p ? p.interface : id;
  6194. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  6195. try {
  6196. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6197. if (res.ok) {
  6198. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  6199. loadBridge();
  6200. fetchData(false);
  6201. }
  6202. } catch (err) {
  6203. showToast('Error', err.message, 'error');
  6204. }
  6205. }
  6206. // ----------------- Bridge VLANs -----------------
  6207. function renderBridgeVLANs() {
  6208. const tbody = document.getElementById('bridge-vlans-table-body');
  6209. const empty = document.getElementById('bridge-empty-vlans');
  6210. const countBadge = document.getElementById('bridge-vlans-count-badge');
  6211. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  6212. if (!tbody) return;
  6213. tbody.innerHTML = '';
  6214. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  6215. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  6216. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  6217. if (vlans.length === 0) {
  6218. empty?.classList.remove('hidden');
  6219. return;
  6220. }
  6221. empty?.classList.add('hidden');
  6222. vlans.forEach((v, idx) => {
  6223. const tr = document.createElement('tr');
  6224. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  6225. const taggedHtml = (v.tagged && v.tagged.length > 0)
  6226. ? 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(' ')
  6227. : '<span class="text-slate-600">none</span>';
  6228. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  6229. ? 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(' ')
  6230. : '<span class="text-slate-600">none</span>';
  6231. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6232. tr.innerHTML = `
  6233. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6234. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6235. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  6236. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  6237. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  6238. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  6239. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  6240. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6241. <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>
  6242. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6243. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6244. </td>
  6245. `;
  6246. tbody.appendChild(tr);
  6247. });
  6248. }
  6249. function openAddBridgeVLANModal() {
  6250. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  6251. document.getElementById('bridge-vlan-modal-id').value = '';
  6252. populateBridgeSelect('bridge-vlan-modal-bridge');
  6253. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  6254. document.getElementById('bridge-vlan-modal-comment').value = '';
  6255. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  6256. updateBridgeVlanPortCheckboxes();
  6257. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6258. }
  6259. function openEditBridgeVLANModal(id) {
  6260. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  6261. if (!v) return;
  6262. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  6263. document.getElementById('bridge-vlan-modal-id').value = v.id;
  6264. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  6265. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  6266. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  6267. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  6268. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  6269. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6270. }
  6271. function closeBridgeVlanModal() {
  6272. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  6273. }
  6274. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  6275. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  6276. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  6277. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  6278. if (!taggedBox || !untaggedBox) return;
  6279. // Ports belonging to the selected bridge
  6280. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  6281. if (memberPorts.length === 0) {
  6282. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6283. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6284. return;
  6285. }
  6286. taggedBox.innerHTML = memberPorts.map(p => `
  6287. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6288. <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">
  6289. <span>${p.interface}</span>
  6290. </label>
  6291. `).join('');
  6292. untaggedBox.innerHTML = memberPorts.map(p => `
  6293. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6294. <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">
  6295. <span>${p.interface}</span>
  6296. </label>
  6297. `).join('');
  6298. }
  6299. async function submitSaveBridgeVLAN(e) {
  6300. e.preventDefault();
  6301. const id = document.getElementById('bridge-vlan-modal-id').value;
  6302. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  6303. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  6304. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  6305. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  6306. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  6307. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  6308. try {
  6309. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  6310. method: 'POST',
  6311. headers: { 'Content-Type': 'application/json' },
  6312. body: JSON.stringify({
  6313. id,
  6314. bridge,
  6315. vlan_ids: vlanIDs,
  6316. tagged,
  6317. untagged,
  6318. comment,
  6319. disabled
  6320. })
  6321. });
  6322. if (res.ok) {
  6323. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  6324. closeBridgeVlanModal();
  6325. loadBridge();
  6326. } else {
  6327. const err = await res.json();
  6328. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  6329. }
  6330. } catch (err) {
  6331. showToast('Error', err.message, 'error');
  6332. }
  6333. }
  6334. async function toggleBridgeVLANState(id, disabled) {
  6335. try {
  6336. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  6337. method: 'POST',
  6338. headers: { 'Content-Type': 'application/json' },
  6339. body: JSON.stringify({ disabled })
  6340. });
  6341. if (res.ok) loadBridge();
  6342. } catch (err) {
  6343. showToast('Error', err.message, 'error');
  6344. }
  6345. }
  6346. async function deleteBridgeVLAN(id) {
  6347. if (!confirm('Delete this bridge VLAN entry?')) return;
  6348. try {
  6349. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6350. if (res.ok) {
  6351. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  6352. loadBridge();
  6353. }
  6354. } catch (err) {
  6355. showToast('Error', err.message, 'error');
  6356. }
  6357. }
  6358. // ----------------- Hosts / MAC Table -----------------
  6359. async function loadBridgeHosts() {
  6360. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  6361. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  6362. try {
  6363. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  6364. const res = await fetch(url);
  6365. if (res.ok) {
  6366. state.bridgeHosts = await res.json();
  6367. renderBridgeHosts();
  6368. }
  6369. } catch (err) {
  6370. console.error('Failed to load bridge hosts:', err);
  6371. }
  6372. }
  6373. function renderBridgeHosts() {
  6374. const tbody = document.getElementById('bridge-hosts-table-body');
  6375. const empty = document.getElementById('bridge-empty-hosts');
  6376. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6377. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6378. if (!tbody) return;
  6379. tbody.innerHTML = '';
  6380. const hosts = (state.bridgeHosts || []).filter(h => {
  6381. if (!search) return true;
  6382. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6383. });
  6384. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6385. if (hosts.length === 0) {
  6386. empty?.classList.remove('hidden');
  6387. return;
  6388. }
  6389. empty?.classList.add('hidden');
  6390. hosts.forEach(h => {
  6391. const tr = document.createElement('tr');
  6392. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6393. let flagBadges = '';
  6394. 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>';
  6395. 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>';
  6396. 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>';
  6397. tr.innerHTML = `
  6398. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6399. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6400. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6401. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6402. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6403. <td class="py-2.5 px-3">${flagBadges}</td>
  6404. `;
  6405. tbody.appendChild(tr);
  6406. });
  6407. }
  6408. async function flushBridgeHosts() {
  6409. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6410. if (!selBridge) {
  6411. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6412. return;
  6413. }
  6414. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6415. try {
  6416. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6417. method: 'POST',
  6418. headers: { 'Content-Type': 'application/json' },
  6419. body: JSON.stringify({ bridge: selBridge })
  6420. });
  6421. if (res.ok) {
  6422. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6423. loadBridgeHosts();
  6424. }
  6425. } catch (err) {
  6426. showToast('Error', err.message, 'error');
  6427. }
  6428. }
  6429. // ----------------- Helpers -----------------
  6430. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6431. const sel = document.getElementById(selectId);
  6432. if (!sel) return;
  6433. const prevVal = currentVal || sel.value;
  6434. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6435. (state.bridges || []).forEach(b => {
  6436. const opt = document.createElement('option');
  6437. opt.value = b.name;
  6438. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6439. if (b.name === prevVal) opt.selected = true;
  6440. sel.appendChild(opt);
  6441. });
  6442. }
  6443. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6444. const sel = document.getElementById(selectId);
  6445. if (!sel) return;
  6446. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6447. // 1. Physical Interfaces
  6448. const grpPhys = document.createElement('optgroup');
  6449. grpPhys.label = 'Physical Interfaces';
  6450. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6451. const opt = document.createElement('option');
  6452. opt.value = i.name;
  6453. opt.innerText = `${i.name} (${i.role || i.type})`;
  6454. if (i.name === currentVal) opt.selected = true;
  6455. grpPhys.appendChild(opt);
  6456. });
  6457. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6458. // 2. VLAN Sub-interfaces
  6459. const grpVlans = document.createElement('optgroup');
  6460. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6461. (state.vlans || []).forEach(v => {
  6462. const opt = document.createElement('option');
  6463. opt.value = v.name;
  6464. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6465. if (v.name === currentVal) opt.selected = true;
  6466. grpVlans.appendChild(opt);
  6467. });
  6468. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6469. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6470. const grpEoip = document.createElement('optgroup');
  6471. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6472. (state.eoipTunnels || []).forEach(t => {
  6473. const opt = document.createElement('option');
  6474. opt.value = t.name;
  6475. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6476. if (t.name === currentVal) opt.selected = true;
  6477. grpEoip.appendChild(opt);
  6478. });
  6479. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6480. }
  6481. // -------------------------------------------------------------
  6482. // Routing Filters Management (/routing filter)
  6483. // -------------------------------------------------------------
  6484. function renderRoutingFilters() {
  6485. const tbody = document.getElementById('routing-filters-table-body');
  6486. if (!tbody) return;
  6487. const empty = document.getElementById('routing-filters-empty');
  6488. const countBadge = document.getElementById('routing-filters-count-badge');
  6489. const navBadge = document.getElementById('badge-filters-count');
  6490. const chainSelect = document.getElementById('routing-filter-chain-select');
  6491. const allRules = state.routingFilters || [];
  6492. if (navBadge) navBadge.innerText = allRules.length;
  6493. // Populate chain filter select options dynamically
  6494. if (chainSelect) {
  6495. const currentVal = state.filterChainSelected || 'all';
  6496. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6497. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6498. uniqueChains.map(ch => {
  6499. const count = allRules.filter(r => r.chain === ch).length;
  6500. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6501. }).join('');
  6502. chainSelect.value = currentVal;
  6503. }
  6504. // Filter rules by selected chain
  6505. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6506. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6507. : allRules.slice();
  6508. // Sort by chain then rule_order
  6509. filteredRules.sort((a, b) => {
  6510. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6511. return (a.rule_order || 0) - (b.rule_order || 0);
  6512. });
  6513. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6514. if (filteredRules.length === 0) {
  6515. tbody.innerHTML = '';
  6516. if (empty) empty.classList.remove('hidden');
  6517. return;
  6518. }
  6519. if (empty) empty.classList.add('hidden');
  6520. tbody.innerHTML = filteredRules.map(r => {
  6521. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6522. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6523. let actionBadge = '';
  6524. if (r.action === 'accept') {
  6525. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">accept</span>';
  6526. } else if (r.action === 'discard') {
  6527. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20">discard</span>';
  6528. } else if (r.action === 'reject') {
  6529. actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-red-950 text-red-300 border border-red-800/40">reject</span>';
  6530. } else {
  6531. actionBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/20">${escapeHtml(r.action || 'accept')}</span>`;
  6532. }
  6533. // Prefix match
  6534. let matchPfx = '';
  6535. if (r.prefix) {
  6536. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6537. if (r.prefix_len) {
  6538. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6539. }
  6540. } else {
  6541. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6542. }
  6543. // Other matches
  6544. const matchExtra = [];
  6545. if (r.match_protocol && r.match_protocol !== 'any') {
  6546. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700">proto:${escapeHtml(r.match_protocol)}</span>`);
  6547. }
  6548. if (r.match_as_path) {
  6549. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">as-path:${escapeHtml(r.match_as_path)}</span>`);
  6550. }
  6551. if (r.match_community) {
  6552. matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">comm:${escapeHtml(r.match_community)}</span>`);
  6553. }
  6554. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6555. // Set modifications
  6556. const setBadges = [];
  6557. if (r.set_local_pref > 0) {
  6558. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950 text-cyan-300 border border-cyan-800/40">loc-pref: ${r.set_local_pref}</span>`);
  6559. }
  6560. if (r.set_metric > 0) {
  6561. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40">med: ${r.set_metric}</span>`);
  6562. }
  6563. if (r.set_as_prepend > 0) {
  6564. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40">prepend: +${r.set_as_prepend}</span>`);
  6565. }
  6566. if (r.set_community) {
  6567. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40">comm: ${escapeHtml(r.set_community)}</span>`);
  6568. }
  6569. if (r.set_next_hop) {
  6570. setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/40">nh: ${escapeHtml(r.set_next_hop)}</span>`);
  6571. }
  6572. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6573. return `
  6574. <tr class="hover:bg-slate-800/40 transition">
  6575. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6576. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6577. <td class="py-2.5 px-3">
  6578. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  6579. </td>
  6580. <td class="py-2.5 px-3">${actionBadge}</td>
  6581. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6582. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6583. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6584. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6585. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6586. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-1 rounded text-[11px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  6587. ${r.disabled ? 'Enable' : 'Disable'}
  6588. </button>
  6589. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  6590. Edit
  6591. </button>
  6592. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  6593. Delete
  6594. </button>
  6595. </td>
  6596. </tr>
  6597. `;
  6598. }).join('');
  6599. }
  6600. function filterRoutingFiltersByChain(chain) {
  6601. state.filterChainSelected = chain;
  6602. renderRoutingFilters();
  6603. }
  6604. function openAddRoutingFilterModal(defaultChain = '') {
  6605. const form = document.getElementById('routing-filter-form');
  6606. if (form) form.reset();
  6607. const idEl = document.getElementById('modal-rf-id');
  6608. if (idEl) idEl.value = '';
  6609. const titleEl = document.getElementById('modal-rf-title');
  6610. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6611. const chainEl = document.getElementById('modal-rf-chain');
  6612. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6613. const orderEl = document.getElementById('modal-rf-order');
  6614. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6615. const actEl = document.getElementById('modal-rf-action');
  6616. if (actEl) actEl.value = 'accept';
  6617. const protoEl = document.getElementById('modal-rf-protocol');
  6618. if (protoEl) protoEl.value = 'any';
  6619. const disEl = document.getElementById('modal-rf-disabled');
  6620. if (disEl) disEl.checked = false;
  6621. const modal = document.getElementById('modal-routing-filter');
  6622. if (modal) modal.classList.remove('hidden');
  6623. }
  6624. function openEditRoutingFilterModal(id) {
  6625. const r = (state.routingFilters || []).find(item => item.id === id);
  6626. if (!r) return;
  6627. const idEl = document.getElementById('modal-rf-id');
  6628. if (idEl) idEl.value = r.id;
  6629. const titleEl = document.getElementById('modal-rf-title');
  6630. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6631. const chainEl = document.getElementById('modal-rf-chain');
  6632. if (chainEl) chainEl.value = r.chain || '';
  6633. const orderEl = document.getElementById('modal-rf-order');
  6634. if (orderEl) orderEl.value = r.rule_order || 10;
  6635. const actEl = document.getElementById('modal-rf-action');
  6636. if (actEl) actEl.value = r.action || 'accept';
  6637. const pfxEl = document.getElementById('modal-rf-prefix');
  6638. if (pfxEl) pfxEl.value = r.prefix || '';
  6639. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6640. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6641. const protoEl = document.getElementById('modal-rf-protocol');
  6642. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6643. const aspEl = document.getElementById('modal-rf-as-path');
  6644. if (aspEl) aspEl.value = r.match_as_path || '';
  6645. const commEl = document.getElementById('modal-rf-community');
  6646. if (commEl) commEl.value = r.match_community || '';
  6647. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6648. if (lpEl) lpEl.value = r.set_local_pref || '';
  6649. const metEl = document.getElementById('modal-rf-set-metric');
  6650. if (metEl) metEl.value = r.set_metric || '';
  6651. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6652. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6653. const setCommEl = document.getElementById('modal-rf-set-community');
  6654. if (setCommEl) setCommEl.value = r.set_community || '';
  6655. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6656. if (nhEl) nhEl.value = r.set_next_hop || '';
  6657. const comEl = document.getElementById('modal-rf-comment');
  6658. if (comEl) comEl.value = r.comment || '';
  6659. const disEl = document.getElementById('modal-rf-disabled');
  6660. if (disEl) disEl.checked = !!r.disabled;
  6661. const modal = document.getElementById('modal-routing-filter');
  6662. if (modal) modal.classList.remove('hidden');
  6663. }
  6664. function closeRoutingFilterModal() {
  6665. const modal = document.getElementById('modal-routing-filter');
  6666. if (modal) modal.classList.add('hidden');
  6667. }
  6668. async function submitRoutingFilter(e) {
  6669. e.preventDefault();
  6670. const payload = {
  6671. id: document.getElementById('modal-rf-id').value,
  6672. chain: document.getElementById('modal-rf-chain').value.trim(),
  6673. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6674. action: document.getElementById('modal-rf-action').value,
  6675. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6676. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6677. match_protocol: document.getElementById('modal-rf-protocol').value,
  6678. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6679. match_community: document.getElementById('modal-rf-community').value.trim(),
  6680. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6681. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6682. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6683. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6684. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6685. comment: document.getElementById('modal-rf-comment').value.trim(),
  6686. disabled: document.getElementById('modal-rf-disabled').checked
  6687. };
  6688. try {
  6689. const res = await fetch(`${API_BASE}/routing/filters`, {
  6690. method: 'POST',
  6691. headers: { 'Content-Type': 'application/json' },
  6692. body: JSON.stringify(payload)
  6693. });
  6694. if (res.ok) {
  6695. closeRoutingFilterModal();
  6696. showToast('Success', 'Routing filter rule saved', 'success');
  6697. loadDynamicRouting();
  6698. } else {
  6699. const err = await res.json();
  6700. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6701. }
  6702. } catch (err) {
  6703. showToast('Error', err.message, 'error');
  6704. }
  6705. }
  6706. async function deleteRoutingFilter(id) {
  6707. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6708. try {
  6709. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6710. if (res.ok) {
  6711. showToast('Deleted', 'Routing filter rule removed', 'info');
  6712. loadDynamicRouting();
  6713. } else {
  6714. const err = await res.json();
  6715. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6716. }
  6717. } catch (err) {
  6718. showToast('Error', err.message, 'error');
  6719. }
  6720. }
  6721. async function toggleRoutingFilterState(id, disabled) {
  6722. try {
  6723. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6724. method: 'POST',
  6725. headers: { 'Content-Type': 'application/json' },
  6726. body: JSON.stringify({ disabled })
  6727. });
  6728. if (res.ok) {
  6729. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6730. loadDynamicRouting();
  6731. } else {
  6732. const err = await res.json();
  6733. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6734. }
  6735. } catch (err) {
  6736. showToast('Error', err.message, 'error');
  6737. }
  6738. }
  6739. // ==========================================
  6740. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6741. // ==========================================
  6742. function loadToolsView() {
  6743. populateToolsInterfaces();
  6744. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6745. }
  6746. function populateToolsInterfaces() {
  6747. const pingSel = document.getElementById('tools-ping-iface');
  6748. const traceSel = document.getElementById('tools-tr-iface');
  6749. let opts = '<option value="">Auto (Default Route)</option>';
  6750. if (Array.isArray(state.interfaces)) {
  6751. state.interfaces.forEach(iface => {
  6752. if (iface.name) {
  6753. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6754. }
  6755. });
  6756. }
  6757. if (pingSel) {
  6758. const cur = pingSel.value;
  6759. pingSel.innerHTML = opts;
  6760. if (cur) pingSel.value = cur;
  6761. }
  6762. if (traceSel) {
  6763. const cur = traceSel.value;
  6764. traceSel.innerHTML = opts;
  6765. if (cur) traceSel.value = cur;
  6766. }
  6767. }
  6768. function switchToolsSubTab(subTab) {
  6769. state.activeToolsSubTab = subTab;
  6770. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6771. tabs.forEach(t => {
  6772. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6773. const view = document.getElementById(`tools-view-${t}`);
  6774. if (btn) {
  6775. if (t === subTab) {
  6776. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  6777. } else {
  6778. 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';
  6779. }
  6780. }
  6781. if (view) {
  6782. if (t === subTab) {
  6783. view.classList.remove('hidden');
  6784. } else {
  6785. view.classList.add('hidden');
  6786. }
  6787. }
  6788. });
  6789. }
  6790. function setPortPreset(port) {
  6791. const input = document.getElementById('tools-port-num');
  6792. if (input) input.value = port;
  6793. }
  6794. let pingAbortController = null;
  6795. let tracerouteAbortController = null;
  6796. function clearPingTable() {
  6797. const tbody = document.getElementById('tools-ping-tbody');
  6798. if (tbody) tbody.innerHTML = '';
  6799. const rawEl = document.getElementById('tools-ping-raw');
  6800. if (rawEl) rawEl.innerText = '';
  6801. const sentEl = document.getElementById('tools-ping-stat-sent');
  6802. if (sentEl) sentEl.innerText = '0';
  6803. const recvEl = document.getElementById('tools-ping-stat-recv');
  6804. if (recvEl) recvEl.innerText = '0';
  6805. const lossEl = document.getElementById('tools-ping-stat-loss');
  6806. if (lossEl) lossEl.innerText = '0%';
  6807. const avgEl = document.getElementById('tools-ping-stat-avg');
  6808. if (avgEl) avgEl.innerText = '0 ms';
  6809. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6810. if (minMaxEl) minMaxEl.innerText = '-';
  6811. const badge = document.getElementById('tools-ping-status-badge');
  6812. if (badge) {
  6813. badge.className = '';
  6814. badge.innerText = '';
  6815. }
  6816. }
  6817. function clearTracerouteTable() {
  6818. const tbody = document.getElementById('tools-tr-tbody');
  6819. if (tbody) tbody.innerHTML = '';
  6820. const rawEl = document.getElementById('tools-tr-raw');
  6821. if (rawEl) rawEl.innerText = '';
  6822. const statHops = document.getElementById('tools-tr-hops-count');
  6823. if (statHops) statHops.innerText = '0 Hops';
  6824. }
  6825. function resetPingButton() {
  6826. const btn = document.getElementById('tools-ping-btn');
  6827. const btnText = document.getElementById('tools-ping-btn-text');
  6828. const spinner = document.getElementById('tools-ping-spinner');
  6829. if (btn) {
  6830. btn.disabled = false;
  6831. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  6832. }
  6833. if (btnText) btnText.innerText = 'Start Ping';
  6834. if (spinner) spinner.classList.add('hidden');
  6835. }
  6836. function setPingRunningButton() {
  6837. const btn = document.getElementById('tools-ping-btn');
  6838. const btnText = document.getElementById('tools-ping-btn-text');
  6839. const spinner = document.getElementById('tools-ping-spinner');
  6840. if (btn) {
  6841. btn.disabled = false;
  6842. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  6843. }
  6844. if (btnText) btnText.innerText = 'Stop Ping';
  6845. if (spinner) spinner.classList.remove('hidden');
  6846. }
  6847. function resetTracerouteButton() {
  6848. const btn = document.getElementById('tools-tr-btn');
  6849. const btnText = document.getElementById('tools-tr-btn-text');
  6850. const spinner = document.getElementById('tools-tr-spinner');
  6851. if (btn) {
  6852. btn.disabled = false;
  6853. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  6854. }
  6855. if (btnText) btnText.innerText = 'Start Traceroute';
  6856. if (spinner) spinner.classList.add('hidden');
  6857. }
  6858. function setTracerouteRunningButton() {
  6859. const btn = document.getElementById('tools-tr-btn');
  6860. const btnText = document.getElementById('tools-tr-btn-text');
  6861. const spinner = document.getElementById('tools-tr-spinner');
  6862. if (btn) {
  6863. btn.disabled = false;
  6864. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  6865. }
  6866. if (btnText) btnText.innerText = 'Stop Traceroute';
  6867. if (spinner) spinner.classList.remove('hidden');
  6868. }
  6869. async function executePing(e) {
  6870. if (e) e.preventDefault();
  6871. // If already running, clicking the button stops the stream!
  6872. if (pingAbortController) {
  6873. pingAbortController.abort();
  6874. pingAbortController = null;
  6875. resetPingButton();
  6876. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  6877. return;
  6878. }
  6879. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6880. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6881. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6882. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  6883. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6884. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6885. if (!target) {
  6886. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6887. return;
  6888. }
  6889. clearPingTable();
  6890. const resCard = document.getElementById('tools-ping-results');
  6891. if (resCard) resCard.classList.remove('hidden');
  6892. pingAbortController = new AbortController();
  6893. setPingRunningButton();
  6894. try {
  6895. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  6896. method: 'POST',
  6897. headers: { 'Content-Type': 'application/json' },
  6898. body: JSON.stringify({
  6899. target,
  6900. count,
  6901. size,
  6902. timeout,
  6903. interface: iface,
  6904. dont_frag: dontFrag
  6905. }),
  6906. signal: pingAbortController.signal
  6907. });
  6908. if (!res.ok) {
  6909. const errText = await res.text();
  6910. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  6911. resetPingButton();
  6912. pingAbortController = null;
  6913. return;
  6914. }
  6915. const reader = res.body.getReader();
  6916. const decoder = new TextDecoder('utf-8');
  6917. let buffer = '';
  6918. while (true) {
  6919. const { done, value } = await reader.read();
  6920. if (done) break;
  6921. buffer += decoder.decode(value, { stream: true });
  6922. const blocks = buffer.split('\n\n');
  6923. buffer = blocks.pop() || '';
  6924. for (const block of blocks) {
  6925. const trimmed = block.trim();
  6926. if (!trimmed) continue;
  6927. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  6928. try {
  6929. const evt = JSON.parse(line);
  6930. handleLivePingEvent(evt);
  6931. } catch (parseErr) {
  6932. console.warn('Ping SSE parse error:', parseErr, line);
  6933. }
  6934. }
  6935. }
  6936. } catch (err) {
  6937. if (err.name === 'AbortError') {
  6938. // User aborted normally
  6939. } else {
  6940. showToast('Ping Error', err.message, 'error');
  6941. }
  6942. } finally {
  6943. pingAbortController = null;
  6944. resetPingButton();
  6945. }
  6946. }
  6947. function handleLivePingEvent(evt) {
  6948. const sentEl = document.getElementById('tools-ping-stat-sent');
  6949. const recvEl = document.getElementById('tools-ping-stat-recv');
  6950. const lossEl = document.getElementById('tools-ping-stat-loss');
  6951. const avgEl = document.getElementById('tools-ping-stat-avg');
  6952. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6953. const badge = document.getElementById('tools-ping-status-badge');
  6954. const tbody = document.getElementById('tools-ping-tbody');
  6955. const rawEl = document.getElementById('tools-ping-raw');
  6956. if (evt.raw && rawEl) {
  6957. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  6958. rawEl.scrollTop = rawEl.scrollHeight;
  6959. }
  6960. if (evt.type === 'reply') {
  6961. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6962. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6963. if (lossEl && evt.packet_loss_pct !== undefined) {
  6964. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6965. lossEl.className = evt.packet_loss_pct === 0
  6966. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  6967. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  6968. }
  6969. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6970. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6971. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6972. }
  6973. if (badge) {
  6974. if (evt.packet_loss_pct === 0) {
  6975. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  6976. badge.innerText = '100% OK';
  6977. } else {
  6978. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  6979. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  6980. }
  6981. }
  6982. if (tbody) {
  6983. const tr = document.createElement('tr');
  6984. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6985. tr.innerHTML = `
  6986. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  6987. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  6988. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  6989. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  6990. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  6991. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  6992. `;
  6993. tbody.appendChild(tr);
  6994. }
  6995. } else if (evt.type === 'timeout') {
  6996. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6997. if (lossEl && evt.packet_loss_pct !== undefined) {
  6998. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6999. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  7000. }
  7001. if (badge) {
  7002. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  7003. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  7004. }
  7005. if (tbody) {
  7006. const tr = document.createElement('tr');
  7007. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  7008. tr.innerHTML = `
  7009. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  7010. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  7011. <td class="py-2 px-3 text-slate-600">--</td>
  7012. <td class="py-2 px-3 text-slate-600">--</td>
  7013. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  7014. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  7015. `;
  7016. tbody.appendChild(tr);
  7017. }
  7018. } else if (evt.type === 'unreach') {
  7019. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7020. if (lossEl && evt.packet_loss_pct !== undefined) {
  7021. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7022. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  7023. }
  7024. if (badge) {
  7025. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  7026. badge.innerText = 'UNREACHABLE';
  7027. }
  7028. if (tbody) {
  7029. const tr = document.createElement('tr');
  7030. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  7031. tr.innerHTML = `
  7032. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  7033. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  7034. <td class="py-2 px-3 text-slate-600">--</td>
  7035. <td class="py-2 px-3 text-slate-600">--</td>
  7036. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  7037. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  7038. `;
  7039. tbody.appendChild(tr);
  7040. }
  7041. } else if (evt.type === 'stats') {
  7042. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  7043. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  7044. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  7045. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  7046. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  7047. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  7048. }
  7049. } else if (evt.type === 'done') {
  7050. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  7051. }
  7052. }
  7053. async function executeTraceroute(e) {
  7054. if (e) e.preventDefault();
  7055. if (tracerouteAbortController) {
  7056. tracerouteAbortController.abort();
  7057. tracerouteAbortController = null;
  7058. resetTracerouteButton();
  7059. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  7060. return;
  7061. }
  7062. const target = document.getElementById('tools-tr-target')?.value?.trim();
  7063. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  7064. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  7065. const iface = document.getElementById('tools-tr-iface')?.value || '';
  7066. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  7067. if (!target) {
  7068. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7069. return;
  7070. }
  7071. clearTracerouteTable();
  7072. const resCard = document.getElementById('tools-tr-results');
  7073. if (resCard) resCard.classList.remove('hidden');
  7074. tracerouteAbortController = new AbortController();
  7075. setTracerouteRunningButton();
  7076. try {
  7077. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  7078. method: 'POST',
  7079. headers: { 'Content-Type': 'application/json' },
  7080. body: JSON.stringify({
  7081. target,
  7082. max_hops: maxHops,
  7083. protocol,
  7084. interface: iface,
  7085. resolve
  7086. }),
  7087. signal: tracerouteAbortController.signal
  7088. });
  7089. if (!res.ok) {
  7090. const errText = await res.text();
  7091. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  7092. resetTracerouteButton();
  7093. tracerouteAbortController = null;
  7094. return;
  7095. }
  7096. const reader = res.body.getReader();
  7097. const decoder = new TextDecoder('utf-8');
  7098. let buffer = '';
  7099. while (true) {
  7100. const { done, value } = await reader.read();
  7101. if (done) break;
  7102. buffer += decoder.decode(value, { stream: true });
  7103. const blocks = buffer.split('\n\n');
  7104. buffer = blocks.pop() || '';
  7105. for (const block of blocks) {
  7106. const trimmed = block.trim();
  7107. if (!trimmed) continue;
  7108. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  7109. try {
  7110. const evt = JSON.parse(line);
  7111. handleLiveTracerouteEvent(evt);
  7112. } catch (parseErr) {
  7113. console.warn('Traceroute SSE parse error:', parseErr, line);
  7114. }
  7115. }
  7116. }
  7117. } catch (err) {
  7118. if (err.name === 'AbortError') {
  7119. // User aborted normally
  7120. } else {
  7121. showToast('Traceroute Error', err.message, 'error');
  7122. }
  7123. } finally {
  7124. tracerouteAbortController = null;
  7125. resetTracerouteButton();
  7126. }
  7127. }
  7128. function handleLiveTracerouteEvent(evt) {
  7129. const statHops = document.getElementById('tools-tr-hops-count');
  7130. const tbody = document.getElementById('tools-tr-tbody');
  7131. const rawEl = document.getElementById('tools-tr-raw');
  7132. if (evt.raw && rawEl) {
  7133. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  7134. rawEl.scrollTop = rawEl.scrollHeight;
  7135. }
  7136. if (evt.hops_count !== undefined && statHops) {
  7137. statHops.innerText = `${evt.hops_count} Hops`;
  7138. }
  7139. if (evt.type === 'hop' && evt.hop && tbody) {
  7140. const h = evt.hop;
  7141. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  7142. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  7143. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  7144. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  7145. const tr = document.createElement('tr');
  7146. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  7147. tr.innerHTML = `
  7148. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7149. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  7150. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  7151. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  7152. <td class="py-2.5 px-3 text-right">
  7153. ${isTimeout
  7154. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  7155. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  7156. </td>
  7157. `;
  7158. tbody.appendChild(tr);
  7159. } else if (evt.type === 'done') {
  7160. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  7161. }
  7162. }
  7163. async function executeMTR(e) {
  7164. if (e) e.preventDefault();
  7165. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  7166. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  7167. if (!target) {
  7168. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7169. return;
  7170. }
  7171. const btn = document.getElementById('tools-mtr-btn');
  7172. const spinner = document.getElementById('tools-mtr-spinner');
  7173. if (btn) btn.disabled = true;
  7174. if (spinner) spinner.classList.remove('hidden');
  7175. try {
  7176. const res = await fetch(`${API_BASE}/tools/mtr`, {
  7177. method: 'POST',
  7178. headers: { 'Content-Type': 'application/json' },
  7179. body: JSON.stringify({ target, count: cycles })
  7180. });
  7181. const data = await res.json();
  7182. if (!res.ok) {
  7183. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  7184. return;
  7185. }
  7186. const resCard = document.getElementById('tools-mtr-results');
  7187. if (resCard) resCard.classList.remove('hidden');
  7188. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  7189. const statHops = document.getElementById('tools-mtr-hops-count');
  7190. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  7191. const tbody = document.getElementById('tools-mtr-tbody');
  7192. if (tbody) {
  7193. if (hopsCount > 0) {
  7194. tbody.innerHTML = data.hops.map(h => {
  7195. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  7196. return `
  7197. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7198. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7199. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  7200. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  7201. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  7202. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  7203. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  7204. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  7205. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  7206. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  7207. </tr>
  7208. `;
  7209. }).join('');
  7210. } else {
  7211. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  7212. }
  7213. }
  7214. const rawEl = document.getElementById('tools-mtr-raw');
  7215. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7216. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  7217. } catch (err) {
  7218. showToast('MTR Error', err.message, 'error');
  7219. } finally {
  7220. if (btn) btn.disabled = false;
  7221. if (spinner) spinner.classList.add('hidden');
  7222. }
  7223. }
  7224. async function executeDNS(e) {
  7225. if (e) e.preventDefault();
  7226. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  7227. const type = document.getElementById('tools-dns-type')?.value || 'A';
  7228. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  7229. if (!domain) {
  7230. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  7231. return;
  7232. }
  7233. const btn = document.getElementById('tools-dns-btn');
  7234. const spinner = document.getElementById('tools-dns-spinner');
  7235. if (btn) btn.disabled = true;
  7236. if (spinner) spinner.classList.remove('hidden');
  7237. try {
  7238. const res = await fetch(`${API_BASE}/tools/dns`, {
  7239. method: 'POST',
  7240. headers: { 'Content-Type': 'application/json' },
  7241. body: JSON.stringify({ domain, type, server })
  7242. });
  7243. const data = await res.json();
  7244. if (!res.ok) {
  7245. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  7246. return;
  7247. }
  7248. const resCard = document.getElementById('tools-dns-results');
  7249. if (resCard) resCard.classList.remove('hidden');
  7250. const metaEl = document.getElementById('tools-dns-meta');
  7251. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  7252. const tbody = document.getElementById('tools-dns-tbody');
  7253. if (tbody) {
  7254. if (Array.isArray(data.records) && data.records.length > 0) {
  7255. tbody.innerHTML = data.records.map(r => `
  7256. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7257. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  7258. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  7259. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  7260. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  7261. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  7262. </tr>
  7263. `).join('');
  7264. } else {
  7265. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  7266. }
  7267. }
  7268. const rawEl = document.getElementById('tools-dns-raw');
  7269. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7270. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  7271. } catch (err) {
  7272. showToast('DNS Error', err.message, 'error');
  7273. } finally {
  7274. if (btn) btn.disabled = false;
  7275. if (spinner) spinner.classList.add('hidden');
  7276. }
  7277. }
  7278. async function executePortProbe(e) {
  7279. if (e) e.preventDefault();
  7280. const target = document.getElementById('tools-port-target')?.value?.trim();
  7281. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  7282. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  7283. if (!target || !port) {
  7284. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  7285. return;
  7286. }
  7287. const btn = document.getElementById('tools-port-btn');
  7288. const spinner = document.getElementById('tools-port-spinner');
  7289. if (btn) btn.disabled = true;
  7290. if (spinner) spinner.classList.remove('hidden');
  7291. try {
  7292. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  7293. method: 'POST',
  7294. headers: { 'Content-Type': 'application/json' },
  7295. body: JSON.stringify({ target, port, timeout })
  7296. });
  7297. const data = await res.json();
  7298. if (!res.ok) {
  7299. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  7300. return;
  7301. }
  7302. const resCard = document.getElementById('tools-port-results');
  7303. if (resCard) resCard.classList.remove('hidden');
  7304. const banner = document.getElementById('tools-port-banner');
  7305. const icon = document.getElementById('tools-port-icon');
  7306. const title = document.getElementById('tools-port-title');
  7307. const sub = document.getElementById('tools-port-sub');
  7308. const latency = document.getElementById('tools-port-latency');
  7309. if (data.open) {
  7310. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  7311. if (icon) {
  7312. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  7313. icon.innerText = '✓';
  7314. }
  7315. if (title) {
  7316. title.className = 'text-sm font-bold text-emerald-300';
  7317. title.innerText = `PORT ${port} OPEN / LISTENING`;
  7318. }
  7319. if (sub) {
  7320. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  7321. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  7322. }
  7323. if (latency) {
  7324. latency.className = 'text-base font-bold font-mono text-emerald-300';
  7325. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  7326. }
  7327. } else {
  7328. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  7329. if (icon) {
  7330. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  7331. icon.innerText = '✕';
  7332. }
  7333. if (title) {
  7334. title.className = 'text-sm font-bold text-rose-300';
  7335. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  7336. }
  7337. if (sub) {
  7338. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  7339. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  7340. }
  7341. if (latency) {
  7342. latency.className = 'text-base font-bold font-mono text-slate-500';
  7343. latency.innerText = '--';
  7344. }
  7345. }
  7346. const rawEl = document.getElementById('tools-port-raw');
  7347. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  7348. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  7349. } catch (err) {
  7350. showToast('Probe Error', err.message, 'error');
  7351. } finally {
  7352. if (btn) btn.disabled = false;
  7353. if (spinner) spinner.classList.add('hidden');
  7354. }
  7355. }
  7356. // ==========================================
  7357. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  7358. // ==========================================
  7359. async function loadDHCPClients(showToastMsg = false) {
  7360. try {
  7361. const [clientsRes, sumRes] = await Promise.all([
  7362. fetch(`${API_BASE}/dhcp/clients`),
  7363. fetch(`${API_BASE}/dhcp/clients/summary`)
  7364. ]);
  7365. if (clientsRes.ok) {
  7366. state.dhcpClients = await clientsRes.json();
  7367. }
  7368. if (sumRes.ok) {
  7369. state.dhcpSummary = await sumRes.json();
  7370. }
  7371. renderDHCPClients();
  7372. updateDHCPSummaryCards();
  7373. const bDhcp = document.getElementById('badge-dhcp-client-count');
  7374. if (bDhcp && state.dhcpSummary) {
  7375. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  7376. }
  7377. if (showToastMsg) {
  7378. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  7379. }
  7380. } catch (err) {
  7381. console.error('Failed to load DHCP clients:', err);
  7382. if (showToastMsg) {
  7383. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  7384. }
  7385. }
  7386. }
  7387. function updateDHCPSummaryCards() {
  7388. const sum = state.dhcpSummary || {
  7389. total_clients: (state.dhcpClients || []).length,
  7390. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  7391. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  7392. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  7393. };
  7394. const totalEl = document.getElementById('dhcp-stat-total');
  7395. const boundEl = document.getElementById('dhcp-stat-bound');
  7396. const searchEl = document.getElementById('dhcp-stat-searching');
  7397. const disEl = document.getElementById('dhcp-stat-disabled');
  7398. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  7399. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  7400. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  7401. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  7402. }
  7403. function renderDHCPClients() {
  7404. const tbody = document.getElementById('dhcp-clients-tbody');
  7405. const emptyState = document.getElementById('dhcp-clients-empty');
  7406. if (!tbody) return;
  7407. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  7408. if (clients.length === 0) {
  7409. tbody.innerHTML = '';
  7410. if (emptyState) emptyState.classList.remove('hidden');
  7411. return;
  7412. }
  7413. if (emptyState) emptyState.classList.add('hidden');
  7414. tbody.innerHTML = clients.map(c => {
  7415. let statusBadge = '';
  7416. if (!c.enabled) {
  7417. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  7418. } else if (c.status === 'bound') {
  7419. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  7420. } else if (c.status === 'searching') {
  7421. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  7422. } else if (c.status === 'stopped') {
  7423. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  7424. } else {
  7425. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  7426. }
  7427. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  7428. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  7429. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  7430. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  7431. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  7432. // Option flags
  7433. const flags = [];
  7434. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  7435. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  7436. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  7437. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  7438. return `
  7439. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  7440. <td class="py-3 px-4">
  7441. <div class="flex items-center gap-2">
  7442. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  7443. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  7444. </div>
  7445. </td>
  7446. <td class="py-3 px-4">${statusBadge}</td>
  7447. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  7448. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  7449. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  7450. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  7451. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  7452. <td class="py-3 px-4">
  7453. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  7454. </td>
  7455. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  7456. ${c.enabled ? `
  7457. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  7458. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  7459. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  7460. ` : `
  7461. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  7462. `}
  7463. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  7464. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  7465. </td>
  7466. </tr>
  7467. `;
  7468. }).join('');
  7469. }
  7470. function openDHCPClientModal(clientId = null) {
  7471. const modal = document.getElementById('modal-dhcp-client');
  7472. if (!modal) return;
  7473. const title = document.getElementById('modal-dhcp-title');
  7474. const idInput = document.getElementById('modal-dhcp-id');
  7475. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7476. const distInput = document.getElementById('modal-dhcp-distance');
  7477. const commentInput = document.getElementById('modal-dhcp-comment');
  7478. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  7479. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  7480. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  7481. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  7482. // Populate interfaces
  7483. if (ifaceSelect) {
  7484. let opts = '<option value="">Select interface...</option>';
  7485. const allIfaces = state.interfaces || [];
  7486. const allVlans = state.vlans || [];
  7487. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  7488. // Group 1: Physical & Bridge Interfaces
  7489. opts += '<optgroup label="Physical & Bridge Interfaces">';
  7490. allIfaces.forEach(i => {
  7491. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  7492. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  7493. });
  7494. opts += '</optgroup>';
  7495. // Group 2: VLAN Interfaces
  7496. if (allVlans.length > 0) {
  7497. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  7498. allVlans.forEach(v => {
  7499. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  7500. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  7501. });
  7502. opts += '</optgroup>';
  7503. }
  7504. ifaceSelect.innerHTML = opts;
  7505. }
  7506. if (clientId) {
  7507. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  7508. if (client) {
  7509. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  7510. if (idInput) idInput.value = client.id;
  7511. if (ifaceSelect) {
  7512. ifaceSelect.value = client.interface;
  7513. ifaceSelect.disabled = true; // interface cannot be changed on edit
  7514. }
  7515. if (distInput) distInput.value = client.default_route_distance || 1;
  7516. if (commentInput) commentInput.value = client.comment || '';
  7517. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  7518. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  7519. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  7520. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  7521. }
  7522. } else {
  7523. if (title) title.innerText = 'Add DHCP Client';
  7524. if (idInput) idInput.value = '';
  7525. if (ifaceSelect) {
  7526. ifaceSelect.value = '';
  7527. ifaceSelect.disabled = false;
  7528. }
  7529. if (distInput) distInput.value = 1;
  7530. if (commentInput) commentInput.value = '';
  7531. if (defRouteCheck) defRouteCheck.checked = true;
  7532. if (peerDnsCheck) peerDnsCheck.checked = true;
  7533. if (peerNtpCheck) peerNtpCheck.checked = true;
  7534. if (enabledCheck) enabledCheck.checked = true;
  7535. }
  7536. modal.classList.remove('hidden');
  7537. }
  7538. function openDHCPClientModalForIface(ifaceName) {
  7539. openDHCPClientModal();
  7540. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7541. if (ifaceSelect && ifaceName) {
  7542. ifaceSelect.value = ifaceName;
  7543. }
  7544. }
  7545. function closeDHCPClientModal() {
  7546. const modal = document.getElementById('modal-dhcp-client');
  7547. if (modal) modal.classList.add('hidden');
  7548. }
  7549. async function submitSaveDHCPClient(e) {
  7550. if (e) e.preventDefault();
  7551. const id = document.getElementById('modal-dhcp-id')?.value;
  7552. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  7553. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  7554. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  7555. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  7556. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  7557. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  7558. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  7559. if (!id && !iface) {
  7560. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  7561. return;
  7562. }
  7563. try {
  7564. let res;
  7565. if (id) {
  7566. // PUT update
  7567. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7568. method: 'PUT',
  7569. headers: { 'Content-Type': 'application/json' },
  7570. body: JSON.stringify({
  7571. enabled,
  7572. add_default_route: defRoute,
  7573. default_route_distance: distance,
  7574. use_peer_dns: peerDns,
  7575. use_peer_ntp: peerNtp,
  7576. comment
  7577. })
  7578. });
  7579. } else {
  7580. // POST create
  7581. res = await fetch(`${API_BASE}/dhcp/clients`, {
  7582. method: 'POST',
  7583. headers: { 'Content-Type': 'application/json' },
  7584. body: JSON.stringify({
  7585. interface: iface,
  7586. enabled,
  7587. add_default_route: defRoute,
  7588. default_route_distance: distance,
  7589. use_peer_dns: peerDns,
  7590. use_peer_ntp: peerNtp,
  7591. comment
  7592. })
  7593. });
  7594. }
  7595. const data = await res.json();
  7596. if (!res.ok) {
  7597. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  7598. return;
  7599. }
  7600. closeDHCPClientModal();
  7601. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  7602. await loadDHCPClients();
  7603. fetchData(); // refresh interfaces list with new lease/status
  7604. } catch (err) {
  7605. showToast('Error', err.message, 'error');
  7606. }
  7607. }
  7608. async function toggleDHCPClientState(id, enabled) {
  7609. try {
  7610. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  7611. method: 'POST',
  7612. headers: { 'Content-Type': 'application/json' },
  7613. body: JSON.stringify({ enabled })
  7614. });
  7615. const data = await res.json();
  7616. if (!res.ok) {
  7617. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  7618. return;
  7619. }
  7620. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  7621. await loadDHCPClients();
  7622. fetchData();
  7623. } catch (err) {
  7624. showToast('Error', err.message, 'error');
  7625. }
  7626. }
  7627. async function renewDHCPClient(id) {
  7628. try {
  7629. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  7630. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  7631. method: 'POST'
  7632. });
  7633. const data = await res.json();
  7634. if (!res.ok) {
  7635. showToast('Error', data.error || 'Failed to renew lease', 'error');
  7636. return;
  7637. }
  7638. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  7639. setTimeout(() => {
  7640. loadDHCPClients();
  7641. fetchData();
  7642. }, 1500);
  7643. } catch (err) {
  7644. showToast('Error', err.message, 'error');
  7645. }
  7646. }
  7647. async function releaseDHCPClient(id) {
  7648. try {
  7649. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  7650. method: 'POST'
  7651. });
  7652. const data = await res.json();
  7653. if (!res.ok) {
  7654. showToast('Error', data.error || 'Failed to release lease', 'error');
  7655. return;
  7656. }
  7657. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  7658. await loadDHCPClients();
  7659. fetchData();
  7660. } catch (err) {
  7661. showToast('Error', err.message, 'error');
  7662. }
  7663. }
  7664. async function deleteDHCPClient(id, ifaceName) {
  7665. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  7666. return;
  7667. }
  7668. try {
  7669. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7670. method: 'DELETE'
  7671. });
  7672. const data = await res.json();
  7673. if (!res.ok) {
  7674. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  7675. return;
  7676. }
  7677. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  7678. await loadDHCPClients();
  7679. fetchData();
  7680. } catch (err) {
  7681. showToast('Error', err.message, 'error');
  7682. }
  7683. }